mirror of
https://github.com/getpaseo/paseo.git
synced 2026-10-30 13:13:25 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fbe24fcdb6 | ||
|
|
787edb1bf9 | ||
|
|
385c29b655 | ||
|
|
9477fe0c00 | ||
|
|
531370c4ce | ||
|
|
e299b21e94 | ||
|
|
1f79efcd62 | ||
|
|
e3682ba18c | ||
|
|
a8e0effb32 | ||
|
|
c663630bbd | ||
|
|
deb1bdc266 | ||
|
|
9c7925de58 | ||
|
|
4351445467 | ||
|
|
9503537041 | ||
|
|
1aef1ec662 | ||
|
|
946b6e58fd | ||
|
|
ac6e4e9f96 | ||
|
|
c4b4516890 | ||
|
|
75f58c4fe7 | ||
|
|
fb69bf3314 | ||
|
|
f7eef9dd0c | ||
|
|
7d74ae5d6c | ||
|
|
61841d1ed5 | ||
|
|
7c88a48be4 | ||
|
|
3196260bd4 | ||
|
|
870a44bc7f | ||
|
|
e8201ab66b | ||
|
|
e12feb633f | ||
|
|
304cbde651 | ||
|
|
0feaf0d987 | ||
|
|
d3f36e92a5 | ||
|
|
1467121b16 | ||
|
|
2f0fb2a8ba | ||
|
|
83ed52669d | ||
|
|
5cfe8f1218 | ||
|
|
38506ed372 | ||
|
|
abc97e0545 | ||
|
|
33faacc055 | ||
|
|
8537709e72 | ||
|
|
9fb7808191 | ||
|
|
41582eb5fd | ||
|
|
dee0d138e9 | ||
|
|
986687b8fd | ||
|
|
eee70e7fef | ||
|
|
d5a27e0164 | ||
|
|
8e7e8cce21 | ||
|
|
36fc4f0b43 | ||
|
|
4dae66eb8c | ||
|
|
d6d5a266ad | ||
|
|
460ba8e8a3 | ||
|
|
7a0c6fbd82 | ||
|
|
bede2b90ed | ||
|
|
befc3d5663 | ||
|
|
53bbd7522d | ||
|
|
ce412d04c3 | ||
|
|
de45902652 | ||
|
|
abc23d7721 | ||
|
|
2c23cd4927 | ||
|
|
de50243885 | ||
|
|
5b7b8d6e81 | ||
|
|
25721c7847 | ||
|
|
78f580f9e8 |
@@ -3,7 +3,7 @@ name: CI
|
|||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: [main]
|
branches: [main]
|
||||||
# Every base branch, so stacked PRs and PRs into `next` get the same checks.
|
# Every base branch, so stacked PRs and PRs into any base get the same checks.
|
||||||
pull_request:
|
pull_request:
|
||||||
merge_group:
|
merge_group:
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
|||||||
@@ -203,6 +203,31 @@
|
|||||||
"readFileSync",
|
"readFileSync",
|
||||||
"rmSync"
|
"rmSync"
|
||||||
],
|
],
|
||||||
|
// Terminal child process: launcher readiness and PTY record ownership run outside the daemon.
|
||||||
|
"terminal/terminal-worker-process.ts": [
|
||||||
|
"chmodSync",
|
||||||
|
"closeSync",
|
||||||
|
"existsSync",
|
||||||
|
"openSync",
|
||||||
|
"rmSync",
|
||||||
|
"writeSync"
|
||||||
|
],
|
||||||
|
// Worker startup only: choose and secure the local listening socket before accepting a controller.
|
||||||
|
"terminal/terminal-worker-socket-path.ts": ["lstatSync", "mkdirSync"],
|
||||||
|
// Startup only: build an independent worker installation before launching; Electron ASAR sources require plain fs reads.
|
||||||
|
"terminal/terminal-worker-runtime.ts": [
|
||||||
|
"chmodSync",
|
||||||
|
"existsSync",
|
||||||
|
"mkdirSync",
|
||||||
|
"readdirSync",
|
||||||
|
"readFileSync",
|
||||||
|
"renameSync",
|
||||||
|
"rmSync",
|
||||||
|
"statSync",
|
||||||
|
"writeFileSync"
|
||||||
|
],
|
||||||
|
// TODO: CLI shim lookup moved out of terminal.ts; migrate the executable-resolution boundary together.
|
||||||
|
"terminal/paseo-cli-path.ts": ["existsSync"],
|
||||||
// Node loader thread: TypeScript terminal-worker resolution runs in the loader, outside the daemon event loop.
|
// Node loader thread: TypeScript terminal-worker resolution runs in the loader, outside the daemon event loop.
|
||||||
"terminal/terminal-ts-loader.mjs": ["existsSync"],
|
"terminal/terminal-ts-loader.mjs": ["existsSync"],
|
||||||
// Terminal child process: executable preparation and shell integration run in the worker-backed terminal manager.
|
// Terminal child process: executable preparation and shell integration run in the worker-backed terminal manager.
|
||||||
|
|||||||
@@ -1,5 +1,16 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
Not released yet. These changes are on `main` but not in 0.14.0; the next release entry includes them.
|
||||||
|
|
||||||
|
Added:
|
||||||
|
|
||||||
|
- Copy gitignored files selected by `.worktreeinclude` into new worktrees before setup and agents, using the built-in `worktree-include` plugin ([#8100](https://github.com/getpaseo/paseo/pull/8100))
|
||||||
|
- Let plugins choose worktree paths and creation options through `worktree.create.before`, with listing, archive, deletion, and recovery at custom locations; includes a sibling-directory placement example ([#8117](https://github.com/getpaseo/paseo/pull/8117))
|
||||||
|
|
||||||
|
Improved:
|
||||||
|
|
||||||
|
- Added `server.addHook` with `subject.operation.position` names and the awaited `worktree.create.after` hook before setup and agents; deprecated the previous plugin hook registration methods without changing their behavior ([#8081](https://github.com/getpaseo/paseo/pull/8081))
|
||||||
|
|
||||||
## 0.14.0 - 2026-10-29
|
## 0.14.0 - 2026-10-29
|
||||||
|
|
||||||
Plugins can now add tools to individual agents and configure their MCP servers when sessions open.
|
Plugins can now add tools to individual agents and configure their MCP servers when sessions open.
|
||||||
|
|||||||
@@ -1,5 +1,16 @@
|
|||||||
# 更新日志
|
# 更新日志
|
||||||
|
|
||||||
|
尚未发布。以下变更已合入 `main`,但不包含在 0.14.0 中;下一个版本的条目会包含它们。
|
||||||
|
|
||||||
|
新增:
|
||||||
|
|
||||||
|
- 在 setup 和 Agent 启动前,使用内置的 `worktree-include` 插件将 `.worktreeinclude` 选中的被 gitignore 忽略的文件复制到新工作树 ([#8100](https://github.com/getpaseo/paseo/pull/8100))
|
||||||
|
- 插件可通过 `worktree.create.before` 选择工作树路径和创建选项,自定义位置的工作树支持列出、归档、删除和恢复;附带同级目录放置示例 ([#8117](https://github.com/getpaseo/paseo/pull/8117))
|
||||||
|
|
||||||
|
改进:
|
||||||
|
|
||||||
|
- 新增采用 `subject.operation.position` 命名的 `server.addHook` 和在 setup 及 Agent 之前等待的 `worktree.create.after` 钩子,弃用原有的插件钩子注册方法并保留原有行为 ([#8081](https://github.com/getpaseo/paseo/pull/8081))
|
||||||
|
|
||||||
## 0.14.0 - 2026-10-29
|
## 0.14.0 - 2026-10-29
|
||||||
|
|
||||||
插件现在可以为单个 Agent 添加工具,并在会话打开时配置其 MCP 服务器。
|
插件现在可以为单个 Agent 添加工具,并在会话打开时配置其 MCP 服务器。
|
||||||
|
|||||||
@@ -66,6 +66,7 @@ At the start of non-trivial work, list `docs/` and skim anything relevant to the
|
|||||||
| [docs/android.md](docs/android.md) | App variants, local/cloud builds, EAS workflows, version codes, F-Droid source builds and store metadata |
|
| [docs/android.md](docs/android.md) | App variants, local/cloud builds, EAS workflows, version codes, F-Droid source builds and store metadata |
|
||||||
| [docs/docker.md](docs/docker.md) | Running the daemon and bundled web UI in Docker, volumes, agent images, security |
|
| [docs/docker.md](docs/docker.md) | Running the daemon and bundled web UI in Docker, volumes, agent images, security |
|
||||||
| [docs/release.md](docs/release.md) | Release playbook, draft releases, completion checklist |
|
| [docs/release.md](docs/release.md) | Release playbook, draft releases, completion checklist |
|
||||||
|
| [docs/terminal-worker.md](docs/terminal-worker.md) | Terminal worker process model, socket/record/secret, protocol-bump rule and draining, the worker's file copy, Windows desktop |
|
||||||
| [docs/terminal-activity.md](docs/terminal-activity.md) | Terminal activity indicators — source-agnostic tracker, agent hook reporting, adding a new hook provider |
|
| [docs/terminal-activity.md](docs/terminal-activity.md) | Terminal activity indicators — source-agnostic tracker, agent hook reporting, adding a new hook provider |
|
||||||
| [SECURITY.md](SECURITY.md) | Relay threat model, E2E encryption, DNS rebinding, agent auth |
|
| [SECURITY.md](SECURITY.md) | Relay threat model, E2E encryption, DNS rebinding, agent auth |
|
||||||
| [public-docs/hub/security.md](public-docs/hub/security.md) | Public Hub guide — trust boundaries, untrusted triggers, provider controls, and output authority |
|
| [public-docs/hub/security.md](public-docs/hub/security.md) | Public Hub guide — trust boundaries, untrusted triggers, provider controls, and output authority |
|
||||||
@@ -116,10 +117,9 @@ See [docs/development.md](docs/development.md) for full setup, build sync requir
|
|||||||
|
|
||||||
## Release branches
|
## Release branches
|
||||||
|
|
||||||
When the user says "this goes to next", create or
|
Merge normal PRs into `main`, including while a beta soaks or a release is being finalized. Each
|
||||||
retarget the PR to `next` and preserve that destination through delivery. Follow
|
release builds in a short-lived release workspace from `origin/main` or a release tag; see
|
||||||
[release branch discipline](docs/release.md#release-branch-discipline) for creating
|
[release base and source](docs/release.md#release-base-and-source).
|
||||||
and updating `next`, integrating it after a release, and releasing a hotfix from a tag.
|
|
||||||
|
|
||||||
## Critical rules
|
## Critical rules
|
||||||
|
|
||||||
|
|||||||
+24
-2
@@ -12,6 +12,26 @@ initializing → idle → running → idle (or error → closed)
|
|||||||
|
|
||||||
Each live agent in `AgentManager` carries a `lastStatus` of `initializing`, `idle`, `running`, or `error`. `closed` is the persisted, resumable state for an agent record that has no live provider runtime. State transitions persist to disk and stream to subscribed clients via WebSocket.
|
Each live agent in `AgentManager` carries a `lastStatus` of `initializing`, `idle`, `running`, or `error`. `closed` is the persisted, resumable state for an agent record that has no live provider runtime. State transitions persist to disk and stream to subscribed clients via WebSocket.
|
||||||
|
|
||||||
|
## Daemon restart recovery
|
||||||
|
|
||||||
|
Hosts resume interrupted agents by default after graceful shutdown or a crash. The daemon
|
||||||
|
reopens the saved provider conversation and settings, then sends `Resume working.`. Change
|
||||||
|
`agents.resumePrompt` or disable `agents.resumeOnStartup` in host config or Host settings → Agents.
|
||||||
|
Disabling recovery consumes pending intent; enabling it later does not revive old work.
|
||||||
|
|
||||||
|
Only agents recorded as running qualify. Idle and initializing agents stay inactive. Archived
|
||||||
|
agents or workspaces, private helpers and Hub-owned executions retain their own lifecycle.
|
||||||
|
Explicit creation environment overrides are saved with the agent and reapplied when reopening.
|
||||||
|
|
||||||
|
Startup chooses candidates before anything else reads or repairs persisted running state, then
|
||||||
|
opens connections and resumes every candidate in the background. A provider that is slow to reopen
|
||||||
|
holds back only its own agent; a failed reopen is logged. Graceful shutdown records intent before
|
||||||
|
closing runtimes.
|
||||||
|
|
||||||
|
This is best-effort continuation. A crash between saving intent and dispatching a prompt can lose
|
||||||
|
or repeat a continuation. Provider resume owns conversation restoration; there is no recovery retry
|
||||||
|
loop or exactly-once turn guarantee.
|
||||||
|
|
||||||
## Runtime residency
|
## Runtime residency
|
||||||
|
|
||||||
An unarchived agent may be `closed` without being deleted or archived. Closing releases its provider
|
An unarchived agent may be `closed` without being deleted or archived. Closing releases its provider
|
||||||
@@ -139,8 +159,10 @@ caller, child, and host into one watch.
|
|||||||
|
|
||||||
Bootstrap restores these watches after repairing stale running records to `closed` and before opening
|
Bootstrap restores these watches after repairing stale running records to `closed` and before opening
|
||||||
ingress. Reading a closed child's result does not load its provider. A finish notification reports that
|
ingress. Reading a closed child's result does not load its provider. A finish notification reports that
|
||||||
the child's run has settled; the parent decides whether its task is complete. Recovery never resumes
|
the child's run has settled; the parent decides whether its task is complete. A child chosen for restart
|
||||||
child work. Archived or deleted parents suppress delivery; parent-owned creation watches also stop
|
recovery is observed only after its resume was sent, so the parent never hears that it was closed
|
||||||
|
in between. Archived or deleted parents suppress delivery;
|
||||||
|
parent-owned creation watches also stop
|
||||||
reporting after detachment.
|
reporting after detachment.
|
||||||
|
|
||||||
Intent remains stored until the parent's notification dispatch is acknowledged. Dispatch failure
|
Intent remains stored until the parent's notification dispatch is acknowledged. Dispatch failure
|
||||||
|
|||||||
@@ -66,6 +66,9 @@ WebSocket message schemas. Shared configuration schemas belong in protocol leaf
|
|||||||
retaining the daemon's runtime and wire-schema allocations. The server export tests guard
|
retaining the daemon's runtime and wire-schema allocations. The server export tests guard
|
||||||
these dependency trees with tree-shaking disabled to match unbundled production imports.
|
these dependency trees with tree-shaking disabled to match unbundled production imports.
|
||||||
|
|
||||||
|
Terminals do not live in the daemon process: their PTYs run in a detached terminal worker that
|
||||||
|
survives daemon restarts, crashes and upgrades. See [terminal-worker.md](terminal-worker.md).
|
||||||
|
|
||||||
Project identity is daemon-global rather than session-owned. After registry bootstrap, the daemon's
|
Project identity is daemon-global rather than session-owned. After registry bootstrap, the daemon's
|
||||||
project Git observer keeps one non-recursive watch on each lexically equivalent active project root
|
project Git observer keeps one non-recursive watch on each lexically equivalent active project root
|
||||||
and listens only for the root `.git` entry, with a slow rescan as a missed-event fallback. It runs
|
and listens only for the root `.git` entry, with a slow rescan as a missed-event fallback. It runs
|
||||||
@@ -490,6 +493,16 @@ The supervisor alone publishes its ready worker's endpoint in `paseo.pid`, clear
|
|||||||
|
|
||||||
Worker restart retains supervisor arguments/environment and rereads the configuration file. Updating a package and observing its new worker version do not refresh the running supervisor code; the launcher owns full-process replacement. See [CLI lifecycle contracts](../public-docs/cli.md#daemon-management).
|
Worker restart retains supervisor arguments/environment and rereads the configuration file. Updating a package and observing its new worker version do not refresh the running supervisor code; the launcher owns full-process replacement. See [CLI lifecycle contracts](../public-docs/cli.md#daemon-management).
|
||||||
|
|
||||||
|
## Outbound networking
|
||||||
|
|
||||||
|
The daemon and its plugin processes honor `HTTPS_PROXY`, `HTTP_PROXY`, and `NO_PROXY`
|
||||||
|
(including lowercase forms, which take precedence). Fetch and relay, Hub, and connected-host WebSockets
|
||||||
|
share this policy. Loopback (`localhost`, `127.0.0.1`, `::1`) always goes direct.
|
||||||
|
A proxy without a scheme uses HTTP. Invalid values and unsupported proxy schemes
|
||||||
|
are treated as unset, with one warning naming the variable in `daemon.log`.
|
||||||
|
Agent and terminal environments are unchanged. System proxy settings and SOCKS-only
|
||||||
|
`ALL_PROXY` configurations are not supported.
|
||||||
|
|
||||||
## Deployment models
|
## Deployment models
|
||||||
|
|
||||||
1. **Local daemon** (default): `paseo daemon start` on `127.0.0.1:6767`
|
1. **Local daemon** (default): `paseo daemon start` on `127.0.0.1:6767`
|
||||||
|
|||||||
@@ -34,9 +34,11 @@ Authoritative terminology. UI label wins. Don't invent synonyms; use what's here
|
|||||||
- **Agent profile** — A named launch bundle: provider, model, mode, thinking option, feature values, and free-text notes. Applying one writes those values into the **Agent controls** and is then forgotten — there is no selected profile, no default profile, and no drift tracking. The notes are written for orchestrating agents and are what the `list_profiles` MCP tool surfaces. Stored host-wide in daemon config as `agentProfiles`. UI: "Agent profiles". Code: `AgentProfile` (`packages/protocol/src/messages.ts:161`). Carries no system prompt, because a per-agent system prompt can only be set at creation. Forbidden: "Favourite", which this replaced.
|
- **Agent profile** — A named launch bundle: provider, model, mode, thinking option, feature values, and free-text notes. Applying one writes those values into the **Agent controls** and is then forgotten — there is no selected profile, no default profile, and no drift tracking. The notes are written for orchestrating agents and are what the `list_profiles` MCP tool surfaces. Stored host-wide in daemon config as `agentProfiles`. UI: "Agent profiles". Code: `AgentProfile` (`packages/protocol/src/messages.ts:161`). Carries no system prompt, because a per-agent system prompt can only be set at creation. Forbidden: "Favourite", which this replaced.
|
||||||
- **Terminal profile** — A named shell command a terminal can launch. Stored host-wide in daemon config as `terminalProfiles`. UI: "Terminal profiles". Code: `TerminalProfile` (`packages/protocol/src/messages.ts:135`), `resolveTerminalProfiles` (`packages/protocol/src/terminal-profiles.ts`). Also selectable as a New Workspace launch target, where the alternative is the chat agent.
|
- **Terminal profile** — A named shell command a terminal can launch. Stored host-wide in daemon config as `terminalProfiles`. UI: "Terminal profiles". Code: `TerminalProfile` (`packages/protocol/src/messages.ts:135`), `resolveTerminalProfiles` (`packages/protocol/src/terminal-profiles.ts`). Also selectable as a New Workspace launch target, where the alternative is the chat agent.
|
||||||
- **Provider** — Agent backend (Claude Code, Codex, Copilot, OpenCode, Pi, Oh My Pi). UI: "Provider". Code: `ProviderSnapshotEntry` (`packages/protocol/src/messages.ts:198`).
|
- **Provider** — Agent backend (Claude Code, Codex, Copilot, OpenCode, Pi, Oh My Pi). UI: "Provider". Code: `ProviderSnapshotEntry` (`packages/protocol/src/messages.ts:198`).
|
||||||
|
- **Hook** — A plugin lifecycle handler registered with `server.addHook`, named `subject.operation.position` with `before` or `after`; each hook declares whether Paseo waits. See [hooks](../public-docs/plugins/hooks.md).
|
||||||
- **Usage source** — Plugin registration that discovers accounts and fetches plan usage. Code: `UsageSourceRegistration` (`packages/plugin/src/server/usage.ts`).
|
- **Usage source** — Plugin registration that discovers accounts and fetches plan usage. Code: `UsageSourceRegistration` (`packages/plugin/src/server/usage.ts`).
|
||||||
- **Report ID** — Stable daemon-composed identity for one source account: `<sourceId>:<accountKey>`. The source owns the account key; clients treat the whole ID as opaque. Code: `UsageReportEntry.id` (`packages/protocol/src/messages.ts`).
|
- **Report ID** — Stable daemon-composed identity for one source account: `<sourceId>:<accountKey>`. The source owns the account key; clients treat the whole ID as opaque. Code: `UsageReportEntry.id` (`packages/protocol/src/messages.ts`).
|
||||||
- **Usage report** — A source's normalized usage for one account, including status and optional windows, balances, and details. Its entry carries the Report ID, account label, and fetch time. Each report renders as one card in the Usage modal, in host Settings, and in an agent's context window details (a hover card on desktop web, a tooltip on native wide screens, a sheet on compact ones), which show only the account that agent runs under, without pins. The hover card and the sheet have Refresh; the native tooltip takes no presses. Code: `UsageReport` (`packages/plugin/src/server/usage.ts`), `UsageCard` (`packages/app/src/usage/card.tsx`), `AgentUsage` (`packages/app/src/usage/agent-usage.tsx`).
|
- **Usage report** — A source's normalized usage for one account, including status and optional windows, balances, and details. Its entry carries the Report ID, account label, and fetch time. Each report renders as one card in the Usage modal, in host Settings, and in an agent's context window details (a hover card on desktop web, a tooltip on native wide screens, a sheet on compact ones), which show only the account that agent runs under, without pins. The hover card and the sheet have Refresh; the native tooltip takes no presses. Code: `UsageReport` (`packages/plugin/src/server/usage.ts`), `UsageCard` (`packages/app/src/usage/card.tsx`), `AgentUsage` (`packages/app/src/usage/agent-usage.tsx`).
|
||||||
|
- **Check usage** — Host-wide switch in Usage Settings, on by default. Turning it off stops login discovery and vendor requests on that host for every device. Usage shows an off state with **Turn on**; the sidebar summary and agent usage sections disappear.
|
||||||
- **Usage (sidebar item)** — The sidebar footer item showing each pinned window's source icon and percent, hidden while no pinned window has data (the footer's Usage icon remains available); both entry points open the Usage modal over the current screen: a dialog on wide layouts, a bottom sheet on compact ones. Usage has no route of its own. Off until the user turns on **Summary in sidebar** (Usage Settings) or the Usage row in Settings > Sidebar; window rows pin only while it is on, and saved pins come back when it is turned on again. A pin is `{ sourceId, windowId }` and shows once per account of that source. Pins and the used/remaining choice are one per-device preference (`AppSettings.usage`) that every usage surface follows. It reads the active workspace's host, else the first connected host with usage sources. Code: `packages/app/src/usage/sidebar-item.tsx`, `usage/usage-modal.tsx`, `usage/pinned.ts`, `usage/preferences.ts`.
|
- **Usage (sidebar item)** — The sidebar footer item showing each pinned window's source icon and percent, hidden while no pinned window has data (the footer's Usage icon remains available); both entry points open the Usage modal over the current screen: a dialog on wide layouts, a bottom sheet on compact ones. Usage has no route of its own. Off until the user turns on **Summary in sidebar** (Usage Settings) or the Usage row in Settings > Sidebar; window rows pin only while it is on, and saved pins come back when it is turned on again. A pin is `{ sourceId, windowId }` and shows once per account of that source. Pins and the used/remaining choice are one per-device preference (`AppSettings.usage`) that every usage surface follows. It reads the active workspace's host, else the first connected host with usage sources. Code: `packages/app/src/usage/sidebar-item.tsx`, `usage/usage-modal.tsx`, `usage/pinned.ts`, `usage/preferences.ts`.
|
||||||
- **Model** — A specific LLM offered by a provider. UI: "Model" / "Select model". Code: `AgentModelDefinition` (`packages/protocol/src/messages.ts:187`).
|
- **Model** — A specific LLM offered by a provider. UI: "Model" / "Select model". Code: `AgentModelDefinition` (`packages/protocol/src/messages.ts:187`).
|
||||||
- **Tab** — UI surface representing one session inside a workspace. Not a conceptual unit; use **Agent session** when talking about the model. Code: `WorkspaceTabDescriptor` (`packages/app/src/screens/workspace/workspace-tabs-types.ts`).
|
- **Tab** — UI surface representing one session inside a workspace. Not a conceptual unit; use **Agent session** when talking about the model. Code: `WorkspaceTabDescriptor` (`packages/app/src/screens/workspace/workspace-tabs-types.ts`).
|
||||||
|
|||||||
+9
-7
@@ -200,13 +200,15 @@ its own.
|
|||||||
|
|
||||||
## Gotchas
|
## Gotchas
|
||||||
|
|
||||||
- **Released height.** Reanimated's web entering animation leaves an inline height snapshot on
|
- **Web enters without Reanimated.** For a custom keyframe, Reanimated's web path snapshots the
|
||||||
the surface. `AnchoredSurface` clears it, and a `revision` prop re-clears it when content
|
surface's rect when the animation ends and writes it back as inline top/left/width/height 750ms
|
||||||
identity changes — a pushed page taller than the one it replaced is clipped without that.
|
after the start. Whatever moved or resized the surface in between was undone: content that
|
||||||
- **Animate only once placed.** The same snapshot carries top/left, and Reanimated writes it back
|
grew once its data arrived left the menu clipped, or hanging over its anchor, until it moved
|
||||||
750ms after mount. `AnchoredSurface` remounts the surface when its position resolves so the
|
again. `AnchoredSurface` plays the same keyframes through the Web Animations API on web, which
|
||||||
entering animation never ends at the off-screen measuring position; on a slow machine that
|
leaves no inline style; native keeps the Reanimated `Keyframe`.
|
||||||
write moved the open menu back off-screen.
|
- **Animate only once placed.** `AnchoredSurface` remounts the surface when its position resolves,
|
||||||
|
so the entering animation runs at the final position rather than ending unseen at the
|
||||||
|
off-screen measuring position.
|
||||||
- **Sheets size to content.** `enableDynamicSizing`, not fixed snap points. A pushed page is
|
- **Sheets size to content.** `enableDynamicSizing`, not fixed snap points. A pushed page is
|
||||||
rarely the height of the page before it. A fill page is the one exception.
|
rarely the height of the page before it. A fill page is the one exception.
|
||||||
- **The sheet's content is teleported out of the menu's subtree**, so `MenuSheetSurface` rebuilds
|
- **The sheet's content is teleported out of the menu's subtree**, so `MenuSheetSurface` rebuilds
|
||||||
|
|||||||
@@ -35,6 +35,20 @@ PASEO_MOBILE_E2E_METRO_PORT=62093 npm run test:e2e:mobile
|
|||||||
|
|
||||||
[native-terminal-basic.ios.ad](../packages/app/e2e/mobile/agent-device/native-terminal-basic.ios.ad) and [native-terminal-basic.android.ad](../packages/app/e2e/mobile/agent-device/native-terminal-basic.android.ad) are the smallest examples. Each opens a fresh terminal, types a command at zero delay, submits it, and asserts its distinct output. The app must be connected to a daemon with an active workspace.
|
[native-terminal-basic.ios.ad](../packages/app/e2e/mobile/agent-device/native-terminal-basic.ios.ad) and [native-terminal-basic.android.ad](../packages/app/e2e/mobile/agent-device/native-terminal-basic.android.ad) are the smallest examples. Each opens a fresh terminal, types a command at zero delay, submits it, and asserts its distinct output. The app must be connected to a daemon with an active workspace.
|
||||||
|
|
||||||
|
For Android background fold recovery, install the release APK on a foldable AVD, open a
|
||||||
|
connected workspace, close the keyboard, and run:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ANDROID_SERIAL=emulator-5574 node packages/app/e2e/mobile/fold/android.mjs
|
||||||
|
```
|
||||||
|
|
||||||
|
The AVD must expose `CLOSED` and `OPENED` device states. The test backgrounds the app,
|
||||||
|
changes posture, resumes immediately, and asserts compact/wide workspace controls without
|
||||||
|
restarting the process. It writes snapshots and native failure state under
|
||||||
|
`.dev/agent-device-artifacts/android-fold`. Set `PASEO_MOBILE_APP_ID=sh.paseo` for a
|
||||||
|
production package. This needs a native rebuild when the Unistyles patch changes; a Metro
|
||||||
|
reload cannot update it.
|
||||||
|
|
||||||
For Android keyboard continuity, run the current checkout in the app, open an idle terminal
|
For Android keyboard continuity, run the current checkout in the app, open an idle terminal
|
||||||
with an empty prompt, hide its keyboard, and run:
|
with an empty prompt, hide its keyboard, and run:
|
||||||
|
|
||||||
|
|||||||
+36
-20
@@ -99,6 +99,10 @@ Built-in plugins ship from `plugins/<id>/`, with `paseo-plugin.json`, `index.ser
|
|||||||
`packages/server/src/server/plugins/builtin/index.ts`; the workspace, build copy, and CI
|
`packages/server/src/server/plugins/builtin/index.ts`; the workspace, build copy, and CI
|
||||||
checks cover that registry. Unlisted directories do not load.
|
checks cover that registry. Unlisted directories do not load.
|
||||||
|
|
||||||
|
The `worktree-include` built-in copies gitignored files selected by
|
||||||
|
[`.worktreeinclude`](../public-docs/worktrees.md#copy-local-files-with-worktreeinclude)
|
||||||
|
before setup and agents, through `worktree.create.after`.
|
||||||
|
|
||||||
Desktop packaging ships the entire built-in plugin directory as an external resource,
|
Desktop packaging ships the entire built-in plugin directory as an external resource,
|
||||||
including declarations. The external esbuild compiler cannot read Electron's `app.asar`
|
including declarations. The external esbuild compiler cannot read Electron's `app.asar`
|
||||||
filesystem, and packaging dependencies excludes `.d.ts` files needed for import validation.
|
filesystem, and packaging dependencies excludes `.d.ts` files needed for import validation.
|
||||||
@@ -333,11 +337,10 @@ export default function contribute(client: PluginClientContext) {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
The contribution function must return cleanup. Server cleanup may be async; Paseo waits for it when
|
The contribution function must return cleanup for resources created by plugin code. Server cleanup
|
||||||
the plugin is reloaded, disabled, removed, disconnected, or shut down. Cleanup is for resources
|
may be async; Paseo waits for it when stopping the server plugin. Cleanup errors are logged and do
|
||||||
created by plugin code. Paseo removes registered contributions, unmounts surfaces, clears query
|
not interrupt host teardown. Client installation retention and disposal follow the public
|
||||||
state, rejects pending RPCs, closes the plugin's daemon session, and stops the subprocess. Cleanup
|
[hosts and lifecycle contract](../public-docs/plugins/reference.md#hosts-and-lifecycle).
|
||||||
errors are logged and do not interrupt host teardown.
|
|
||||||
|
|
||||||
Paseo owns the route, screen header, icon validation, close action, theme DTO, layout facts,
|
Paseo owns the route, screen header, icon validation, close action, theme DTO, layout facts,
|
||||||
and render error boundary. The contributed component owns the complete body below the header.
|
and render error boundary. The contributed component owns the complete body below the header.
|
||||||
@@ -382,6 +385,15 @@ grace. During daemon startup, plugin sessions may connect while application WebS
|
|||||||
paused; the daemon accepts clients only after configured plugins have settled and the initial
|
paused; the daemon accepts clients only after configured plugins have settled and the initial
|
||||||
catalog is complete.
|
catalog is complete.
|
||||||
|
|
||||||
|
The app retains client bundles per host in its file cache (IndexedDB on web), keyed by plugin ID
|
||||||
|
and the daemon's SHA-256. A cold client verifies stored contents before advertising their hashes;
|
||||||
|
missing or corrupt files request full bundles. Only the latest catalog's bundles remain. Hashing
|
||||||
|
uses Expo's native async digest on mobile, avoiding a JavaScript hash loop on Hermes; reading and
|
||||||
|
passing the bundle string still costs memory and time once per client lifetime.
|
||||||
|
Persistence runs after catalog reconstruction without delaying installation. One write runs at a
|
||||||
|
time; while storage is busy, only the newest pending catalog is kept. A failed write leaves the
|
||||||
|
in-memory bundles usable, and a later catalog retries persistence.
|
||||||
|
|
||||||
When the same plugin contribution exists on multiple hosts, Paseo shows it once in the sidebar and
|
When the same plugin contribution exists on multiple hosts, Paseo shows it once in the sidebar and
|
||||||
adds a host picker to the screen header. The selected host supplies the bundle, RPC transport, and
|
adds a host picker to the screen header. The selected host supplies the bundle, RPC transport, and
|
||||||
query cache. Explicit SDK targets follow the [host API contract](../public-docs/plugins/reference.md#discover-hosts-and-target-another-host).
|
query cache. Explicit SDK targets follow the [host API contract](../public-docs/plugins/reference.md#discover-hosts-and-target-another-host).
|
||||||
@@ -428,21 +440,22 @@ The [public reference](../public-docs/plugins/reference.md#icons) owns the autho
|
|||||||
|
|
||||||
## Lifecycle hooks
|
## Lifecycle hooks
|
||||||
|
|
||||||
Server entries register lifecycle observers with `server.on()` and request transforms with
|
Server entries register async handlers with `server.addHook(name, handler)`, returning a cleanup
|
||||||
`server.before()`. The [public reference](../public-docs/plugins/reference.md#lifecycle-hooks)
|
function. Names follow `subject.operation.position`, ending in `before` or `after`. Waiting is a per-hook
|
||||||
owns callback shapes, ordering, and failure behavior. `agent.create` edits the agent's saved
|
registry property, independent of position. The [hooks reference](../public-docs/plugins/hooks.md)
|
||||||
configuration; `agent.session_open` contributes launch-only `env`, `tools`, and `mcpServers`,
|
owns payloads, ordering, failure behavior, and examples. `agent.create.before` edits saved
|
||||||
re-derived on each open and following the plugin's lifecycle. See
|
configuration; `agent.open.before` contributes launch-only `env`, `tools`, and `mcpServers` on
|
||||||
[Inject MCP servers](../public-docs/plugins/reference.md#inject-mcp-servers) for choosing the hook.
|
every open. Executable tool definitions stay in the plugin process; only metadata crosses the boundary.
|
||||||
`plugin-examples/lifecycle-logger` registers all
|
|
||||||
eleven hooks; `plugin-examples/lifecycle-actions` demonstrates common automation callbacks.
|
Worktree placement is resolved before Git source planning, so a hook can change the branch and base
|
||||||
Session-open hooks also [attach tools to individual agents](../public-docs/plugins/reference.md#attach-tools-to-agents),
|
without undoing fetched refs. Restores use the recorded destination and bypass creation hooks.
|
||||||
as shown in `plugin-examples/agent-tools`. The agent manager stamps their metadata per session;
|
Workspace records decide ownership, including explicit non-ownership after recovery. Without a record,
|
||||||
executable definitions stay in the plugin process.
|
ownership checks prefer the marker-verified worktree root over the legacy
|
||||||
|
path shape: a plugin can place a worktree several directories below the default worktrees root.
|
||||||
|
|
||||||
Emit from the operation owner, not a client subscription. Provider history replay must not trigger
|
Emit from the operation owner, not a client subscription. Provider history replay must not trigger
|
||||||
live hooks. Observers must not be awaited inside agent mutations: a callback can send a prompt or
|
live hooks. Notifications must not be awaited inside agent mutations: a handler can send a prompt
|
||||||
answer a permission through its own daemon session. Awaiting it there deadlocks that command.
|
or answer a permission through its own daemon session. Awaiting it there deadlocks that command.
|
||||||
|
|
||||||
## Contribute a provider
|
## Contribute a provider
|
||||||
|
|
||||||
@@ -537,7 +550,7 @@ string is never inline SVG or a URL.
|
|||||||
|
|
||||||
Register a usage source from `index.server.ts` with `server.registerUsageSource()`. Import `UsageSourceRegistration` and normalization helpers from `@getpaseo/plugin/server/usage`. The plugin owns account discovery, harness labels, and credential-store reads; the daemon owns account grouping and the fetch cache. Agent popovers use only the agent's own login. The host-wide Usage modal falls back across an account's logins; any success shows usage only, and all failures show every login's labeled error and remedy. Follow the [usage source discovery contract](../public-docs/plugins/reference.md#usage-sources). The resolved launch environment crosses into the trusted, unsandboxed plugin subprocess for session discovery. Usage queries never run lifecycle hooks. Inputs are validated in the plugin process and remain daemon-side. `icon` uses the same SVG file rules as provider icons.
|
Register a usage source from `index.server.ts` with `server.registerUsageSource()`. Import `UsageSourceRegistration` and normalization helpers from `@getpaseo/plugin/server/usage`. The plugin owns account discovery, harness labels, and credential-store reads; the daemon owns account grouping and the fetch cache. Agent popovers use only the agent's own login. The host-wide Usage modal falls back across an account's logins; any success shows usage only, and all failures show every login's labeled error and remedy. Follow the [usage source discovery contract](../public-docs/plugins/reference.md#usage-sources). The resolved launch environment crosses into the trusted, unsandboxed plugin subprocess for session discovery. Usage queries never run lifecycle hooks. Inputs are validated in the plugin process and remain daemon-side. `icon` uses the same SVG file rules as provider icons.
|
||||||
|
|
||||||
The daemon calls discovery for `usage.list_reports`; the client gates this RPC on `server_info.features.usageSources`. The old `provider.usage.list` RPC maps discovered reports for older clients.
|
When the host’s **Check usage** switch is off, the daemon rejects usage requests before discovery, without reading logins or calling vendors. Otherwise, the daemon calls discovery for `usage.list_reports`; the client gates this RPC on `server_info.features.usageSources`. The old `provider.usage.list` RPC maps discovered reports for older clients.
|
||||||
|
|
||||||
## Contribute sidebar items
|
## Contribute sidebar items
|
||||||
|
|
||||||
@@ -613,7 +626,10 @@ Request observation with `client.paseo.agents.list({ subscribe: {} })` and consu
|
|||||||
demand. Provider and project `subscribe()` calls establish their own demand. On capable daemons, each
|
demand. Provider and project `subscribe()` calls establish their own demand. On capable daemons, each
|
||||||
list-and-subscribe call has its own server ID, even for the same query. Older daemons retain
|
list-and-subscribe call has its own server ID, even for the same query. Older daemons retain
|
||||||
[shared delivery behavior](protocol-compatibility.md#owned-observations). Handle snapshots
|
[shared delivery behavior](protocol-compatibility.md#owned-observations). Handle snapshots
|
||||||
also run after reconnect; replace your view before applying its subsequent updates. The installation
|
also run after reconnect; replace your view before applying its subsequent updates. An installation
|
||||||
|
stays loaded during a dropped connection while the app retains its `DaemonClient` object. An
|
||||||
|
unchanged installation does not rerun setup on reconnect, so refresh state from those snapshots
|
||||||
|
rather than from setup. Switching connections replaces the client object and reinstalls plugins. The installation
|
||||||
owns every observation created through its API and releases them on unload, including setup failure.
|
owns every observation created through its API and releases them on unload, including setup failure.
|
||||||
Mounted surfaces and command invocations have shorter API lifetimes.
|
Mounted surfaces and command invocations have shorter API lifetimes.
|
||||||
|
|
||||||
|
|||||||
+135
-73
@@ -6,10 +6,10 @@ All workspaces share one version and release together.
|
|||||||
|
|
||||||
A release has exactly two steps. The agent does the first, the user authorizes the second.
|
A release has exactly two steps. The agent does the first, the user authorizes the second.
|
||||||
|
|
||||||
**Preparation** (local, reversible — agent does this):
|
**Preparation** (reversible — agent does this):
|
||||||
|
|
||||||
- format, lint, typecheck all green
|
- format, lint, typecheck all green
|
||||||
- resolve the release source to one commit and confirm that commit's existing CI is green
|
- resolve the [release base](#release-base-and-source), get the [release inventory](#release-inventory) approved when one applies, and confirm CI for the resulting release source is green
|
||||||
- classify the diff from the previous stable to the release source as patch or minor, then show the
|
- classify the diff from the previous stable to the release source as patch or minor, then show the
|
||||||
target version and rationale to the user
|
target version and rationale to the user
|
||||||
- draft the changelog, show it to the user, wait for review
|
- draft the changelog, show it to the user, wait for review
|
||||||
@@ -17,9 +17,10 @@ A release has exactly two steps. The agent does the first, the user authorizes t
|
|||||||
|
|
||||||
**Go-ahead** (user says "go ahead"):
|
**Go-ahead** (user says "go ahead"):
|
||||||
|
|
||||||
- commit the approved release inputs locally
|
- commit the approved release inputs locally on the release branch
|
||||||
- run the release, which publishes npm and pushes the prepared branch and tag
|
- run the release, which publishes npm and pushes the release branch and tag
|
||||||
- create the release heartbeat immediately and babysit it to completion
|
- create the release heartbeat immediately and babysit it to completion
|
||||||
|
- [reconcile `main`](#reconcile-main) with what shipped
|
||||||
|
|
||||||
Rules that apply to both steps:
|
Rules that apply to both steps:
|
||||||
|
|
||||||
@@ -27,56 +28,128 @@ Rules that apply to both steps:
|
|||||||
- No code changes bundled into the changelog commit or the release commit. Code shims live in their own commit, reviewed on their own merits.
|
- No code changes bundled into the changelog commit or the release commit. Code shims live in their own commit, reviewed on their own merits.
|
||||||
- A sanity-check finding is information, not a directive. The agent surfaces it; the user decides.
|
- A sanity-check finding is information, not a directive. The agent surfaces it; the user decides.
|
||||||
- Invoking a release skill is intent to start the flow, not blanket authorization to publish.
|
- Invoking a release skill is intent to start the flow, not blanket authorization to publish.
|
||||||
|
- An approval the user already gave covers what it names, such as an explicit PR selection or authorization to release autonomously. Do not ask for it again.
|
||||||
- If the user asks for a release preview, show the prospective changelog/release contents and answer questions, but do not commit, tag, publish, or run release commands until they explicitly authorize the release.
|
- If the user asks for a release preview, show the prospective changelog/release contents and answer questions, but do not commit, tag, publish, or run release commands until they explicitly authorize the release.
|
||||||
|
|
||||||
## Release source and CI
|
## Main stays open
|
||||||
|
|
||||||
The default release source is `origin/main`. Fetch `origin`, then record the
|
Merge normal PRs into `main` at any time, including while a beta soaks or a release is being
|
||||||
resolved commit. The default release checkout is a clean local `main` whose
|
finalized. Each release builds in a short-lived release workspace, and its published tag records
|
||||||
`HEAD` equals `origin/main`.
|
the shipped source.
|
||||||
|
|
||||||
An explicit user instruction can select another ref, such as a hotfix commit or
|
## Choosing a path
|
||||||
tag. Resolve that ref once and apply every source, diff, and CI check to that
|
|
||||||
commit instead of `origin/main`.
|
|
||||||
|
|
||||||
Before making release-preparation commits, confirm the existing CI run for the
|
The user decides when the changes on `main` warrant a release and how much risk it takes:
|
||||||
resolved commit is green. Pending CI is watched to completion. Release
|
|
||||||
preparation then stays local through the changelog, any explicitly requested ACP
|
|
||||||
catalog update, lockfile preparation, and the version commit. After approval,
|
|
||||||
commit the prepared inputs locally and run the release command. Its branch and
|
|
||||||
tag push is the one remote release batch and starts CI for the complete release
|
|
||||||
commit.
|
|
||||||
|
|
||||||
## Release branch discipline
|
1. **Direct stable release** for a low-risk batch of polish and bug fixes. Stable desktop updates
|
||||||
|
already ramp over 36 hours (see [Staged rollout](#staged-rollout-stable-channel)), and store
|
||||||
|
review often takes about a day, with no guaranteed timing.
|
||||||
|
2. **Beta flow**, the default for changes that need testing. Release candidates on the `beta`
|
||||||
|
channel. Each beta folds into the series' single changelog entry, publishes npm only on the
|
||||||
|
explicit `beta` dist-tag, and stays behind the Stable/Beta switch on `/download`.
|
||||||
|
|
||||||
While you finalize a release on `main`, use a temporary `next` branch for work intended for the following
|
A beta follows these defaults, which the user can explicitly override:
|
||||||
release. This applies to both beta and stable releases.
|
|
||||||
|
|
||||||
- Create each new `next` from freshly fetched `origin/main`. Reuse it while active.
|
- Soak a beta at least 24 hours before promotion. Soak longer for risky or breaking changes, or
|
||||||
- "This goes to next" means create the PR against `next` or retarget an existing
|
while feedback is open. Changes added in a later beta get their own soak; earlier soak time does
|
||||||
PR, and keep that destination through delivery.
|
not count for them.
|
||||||
- Keep `next` current by merging `origin/main` into it as release fixes land.
|
- A follow-up beta carries regressions, fixes, and polish for what that beta delivers. Unrelated
|
||||||
Avoid rebasing this shared branch because agents and open PRs depend on its history.
|
work on `main` and pre-existing bugs wait for a later release unless the user explicitly selects
|
||||||
- After the release ships, bring `next` up to date and open a `next` → `main` PR.
|
them.
|
||||||
Pass CI and merge without squashing away the individual PR commits needed for
|
- Promotion ships the tested beta's product content unchanged and does not pull from `main`.
|
||||||
the changelog. Retarget remaining PRs based on `next` to `main` and delete the integrated
|
Adding a product change needs the user's explicit selection and a new beta, which soaks again.
|
||||||
`next`. Create it fresh when needed again.
|
- During a soak, ship urgent stable regressions and compatibility or provider model updates as a
|
||||||
|
[stable hotfix](#release-base-and-source) from the latest stable tag. The beta keeps its own
|
||||||
|
pace.
|
||||||
|
|
||||||
**Setup still needed:** PR checks run for every base branch, but CI, Docker, and Nix
|
npm dist-tags are independent pointers:
|
||||||
push runs target only `main`, and GitHub permits only squash merges. Enable
|
|
||||||
required-check protection for `next`, CI on its pushes, and merge commits for the
|
|
||||||
integration PR. Handle PR
|
|
||||||
base changes (`edited` events) so retargeting runs checks against the new base;
|
|
||||||
GitHub's default PR events do not cover this. Deployment triggers stay unchanged.
|
|
||||||
|
|
||||||
### Hotfix from a release tag
|
- A beta release publishes with `--tag beta` and moves only `beta`; `latest` remains on the
|
||||||
|
newest stable.
|
||||||
|
- A stable release publishes to `latest`. Move `beta` to it as well when the stable version is
|
||||||
|
newer than the version `beta` points to, which covers promotions and direct stable releases, so
|
||||||
|
`@getpaseo/cli@beta` users never sit behind stable. A stable hotfix on an older line leaves
|
||||||
|
`beta` on the active newer beta.
|
||||||
|
|
||||||
If `main` contains changes you do not want to release, branch from the affected
|
## Release base and source
|
||||||
release tag and cherry-pick only the required fixes. Run CI on that branch, then
|
|
||||||
use the normal release flow with it as the explicit source, choosing a new patch
|
The release base is the tag or commit a release workspace starts from. The release source is the
|
||||||
or beta version. Ensure the fixes and changelog also reach `main` and any active
|
base plus any approved cherry-picks, and every source, diff, and CI check uses it.
|
||||||
`next`, preserving newer development and version changes there. This is a
|
|
||||||
short-lived hotfix branch, not another maintained release track.
|
| Release | Base | Changes on top |
|
||||||
|
| -------------------------------------------------------- | ------------------------------------------------------------ | ---------------------------- |
|
||||||
|
| Starting release: first beta of a line, or direct stable | `origin/main`, captured once | None |
|
||||||
|
| Follow-up beta | The selected published beta tag, normally the series' latest | Approved commits from `main` |
|
||||||
|
| Promotion | The beta tag being promoted | None by default |
|
||||||
|
| Stable hotfix | The latest appropriate stable tag | Approved commits from `main` |
|
||||||
|
|
||||||
|
An explicit user instruction can select another base.
|
||||||
|
|
||||||
|
1. Fetch `origin` with tags and resolve the base to one commit.
|
||||||
|
2. Create the release workspace through Paseo MCP on a new branch from the base, named
|
||||||
|
`release/vX.Y.Z` or `release/vX.Y.Z-beta.N` for the version being cut. Run the release from
|
||||||
|
this workspace: `release:push` pushes `HEAD` to the current branch.
|
||||||
|
3. Cherry-pick the approved commits in their `main` order with `git cherry-pick -x`, so each
|
||||||
|
commit records the `main` commit it came from. Include the prerequisites the inventory listed.
|
||||||
|
Resolve conflicts within the approved changes and report how. A resolution that needs new
|
||||||
|
behavior is a scope addition: surface it for selection.
|
||||||
|
4. Confirm CI for the release source. When the source is a commit whose CI already passed (the
|
||||||
|
captured `origin/main`, or the beta tag being promoted), use that run and watch pending CI to
|
||||||
|
completion. Otherwise push the release branch and run `gh workflow run ci.yml --ref <branch>`,
|
||||||
|
because CI push runs target only `main`.
|
||||||
|
5. Keep the changelog, any explicitly requested ACP catalog update, lockfile preparation, and the
|
||||||
|
version commit local until the go-ahead. The release command pushes the release branch and tag
|
||||||
|
as one batch, and the tag push starts the release workflows. Then run
|
||||||
|
`gh workflow run ci.yml --ref <branch>` so CI covers the complete release commit.
|
||||||
|
6. [Reconcile `main`](#reconcile-main).
|
||||||
|
|
||||||
|
A stable hotfix can take the version a patch beta line would promote to, such as `0.13.3`
|
||||||
|
shipping while `0.13.3-beta.2` soaks. Never republish or reuse a shipped version. Continue the line
|
||||||
|
as the next unused patch beta, `0.13.4-beta.1`, from the tested beta tag. No `version:all:*` mode
|
||||||
|
computes that from a prerelease, so follow the [manual steps](#manual-step-by-step) with
|
||||||
|
`npm version 0.13.4-beta.1 --include-workspace-root --message "chore(release): cut %s"` and
|
||||||
|
`npm run release:publish:beta`. Record the tested beta tag as its source so its soak still counts
|
||||||
|
for the unchanged content.
|
||||||
|
|
||||||
|
## Release inventory
|
||||||
|
|
||||||
|
When the user asks for a follow-up beta or a promotion, list what `main` has that the base does
|
||||||
|
not, then get the batch approved. There is no release label or queue.
|
||||||
|
|
||||||
|
1. Find the commits on `origin/main` whose patches are not in the base tag:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git log --cherry-pick --right-only --no-merges --format='%h %s' <base-tag>...origin/main
|
||||||
|
```
|
||||||
|
|
||||||
|
Patch equivalence recognizes commits already cherry-picked into the tag, so trust the tag
|
||||||
|
content over PR state or branch names.
|
||||||
|
|
||||||
|
2. Present a short include/defer list. Link each PR and give one plain reason. List separately the
|
||||||
|
prerequisites an included PR depends on and anything that adds scope beyond what the beta
|
||||||
|
delivers. For each fix that shipped in a stable hotfix after the beta's base, confirm the beta
|
||||||
|
preserves its behavior, directly or through a superseding change. List the missing ones for
|
||||||
|
explicit selection; adding one to a promotion needs a new beta.
|
||||||
|
3. Wait for the user to approve the batch, unless an explicit selection or autonomous
|
||||||
|
authorization they already gave covers it.
|
||||||
|
|
||||||
|
For a promotion, every item defaults to defer.
|
||||||
|
|
||||||
|
## Reconcile main
|
||||||
|
|
||||||
|
After the release push, open a PR into `main` that brings in what shipped and keeps newer
|
||||||
|
development on `main`:
|
||||||
|
|
||||||
|
- The shipped `CHANGELOG.md` and `CHANGELOG.zh-CN.md` entries, exactly as tagged. A beta or
|
||||||
|
promotion entry replaces the series entry on `main`. A stable hotfix on an older line goes
|
||||||
|
below any newer entries.
|
||||||
|
- The shipped version in every `package.json` and `package-lock.json`, unless `main` already
|
||||||
|
carries a newer version, plus the F-Droid changelog files a stable release generates.
|
||||||
|
- No claims about unshipped work: a shipped entry describes only the tagged content, and notes
|
||||||
|
`main` holds for changes that have not shipped stay out of it.
|
||||||
|
|
||||||
|
Delete the release branch once the PR merges. The tag is the record of shipped source; Paseo
|
||||||
|
maintains no release track besides `main`.
|
||||||
|
|
||||||
## ACP catalog updates
|
## ACP catalog updates
|
||||||
|
|
||||||
@@ -91,21 +164,6 @@ ACP catalog work enters a release through an explicit user request:
|
|||||||
The release authorization covers the requested ACP commit. It ships in the same
|
The release authorization covers the requested ACP commit. It ships in the same
|
||||||
release push as the changelog and version commit.
|
release push as the changelog and version commit.
|
||||||
|
|
||||||
## Two paths
|
|
||||||
|
|
||||||
There are two supported release paths:
|
|
||||||
|
|
||||||
1. **Direct stable release**: you are ready to ship the resolved release source to everyone immediately (default `origin/main`).
|
|
||||||
2. **Beta flow**: release candidates on the `beta` channel. Each beta folds into the series' single changelog entry, publishes npm only on the explicit `beta` dist-tag, and stays behind the Stable/Beta switch on `/download`.
|
|
||||||
|
|
||||||
Paseo has one linear release track even though npm dist-tags are independent
|
|
||||||
pointers. The npm invariant is:
|
|
||||||
|
|
||||||
- A beta release moves only `beta`; `latest` remains on the newest stable.
|
|
||||||
- A stable release moves both `latest` and `beta` to that stable version. This
|
|
||||||
keeps users who install `@getpaseo/cli@beta` on the newest Paseo release after
|
|
||||||
a beta is promoted or superseded by a direct stable release.
|
|
||||||
|
|
||||||
## Release version decision
|
## Release version decision
|
||||||
|
|
||||||
Every fresh release starts by classifying the full diff from the previous
|
Every fresh release starts by classifying the full diff from the previous
|
||||||
@@ -133,7 +191,7 @@ as described in **Fixing a failed release build**.
|
|||||||
|
|
||||||
Before running any stable release command:
|
Before running any stable release command:
|
||||||
|
|
||||||
- Make sure the resolved release source passed CI, the approved release inputs are committed locally on the intended branch, and the working tree is clean.
|
- Make sure the release source passed CI, the approved release inputs are committed locally on the release branch, and the working tree is clean.
|
||||||
- **Run `npm run format`, `npm run lint`, and `npm run typecheck` and commit any resulting changes BEFORE you start any `release:*` command.** `release:check` runs `npm install --workspaces --include-workspace-root` as part of `release:prepare`, which can mutate `package-lock.json` (e.g. churning `"dev": true` markers on optional deps). The next step, `version:all:*`, runs `npm version` which aborts when the working tree is dirty. If this happens mid-flight you have to commit the lockfile churn before retrying — and the pre-commit format hook will reject a lockfile-only commit because oxfmt internally skips `package-lock.json` while lefthook's glob still matches it. Avoid the whole mess by running format/lint/typecheck first, then `release:prepare` once on its own to absorb any lockfile churn into a normal commit, then start the release.
|
- **Run `npm run format`, `npm run lint`, and `npm run typecheck` and commit any resulting changes BEFORE you start any `release:*` command.** `release:check` runs `npm install --workspaces --include-workspace-root` as part of `release:prepare`, which can mutate `package-lock.json` (e.g. churning `"dev": true` markers on optional deps). The next step, `version:all:*`, runs `npm version` which aborts when the working tree is dirty. If this happens mid-flight you have to commit the lockfile churn before retrying — and the pre-commit format hook will reject a lockfile-only commit because oxfmt internally skips `package-lock.json` while lefthook's glob still matches it. Avoid the whole mess by running format/lint/typecheck first, then `release:prepare` once on its own to absorb any lockfile churn into a normal commit, then start the release.
|
||||||
- Do not use a release command as a substitute for checking whether the current commit is actually ready.
|
- Do not use a release command as a substitute for checking whether the current commit is actually ready.
|
||||||
|
|
||||||
@@ -145,9 +203,9 @@ npm run release:minor
|
|||||||
|
|
||||||
This bumps the version across all workspaces, runs checks, publishes to npm, and pushes the branch + tag. The tag push triggers `Desktop Release`, `Android APK Release`, `Docker`, and `Release Notes Sync` on GitHub Actions. The workflows create the GitHub Release as a draft while builds and release-note sync run. EAS picks up the same tag via the EAS GitHub app and starts the iOS + Android store builds in parallel (see "Mobile builds (EAS)" below) — there is no mobile-release workflow under `.github/workflows`.
|
This bumps the version across all workspaces, runs checks, publishes to npm, and pushes the branch + tag. The tag push triggers `Desktop Release`, `Android APK Release`, `Docker`, and `Release Notes Sync` on GitHub Actions. The workflows create the GitHub Release as a draft while builds and release-note sync run. EAS picks up the same tag via the EAS GitHub app and starts the iOS + Android store builds in parallel (see "Mobile builds (EAS)" below) — there is no mobile-release workflow under `.github/workflows`.
|
||||||
|
|
||||||
After the stable release succeeds, move npm's `beta` pointer to the new stable
|
After the stable release succeeds, check `npm view @getpaseo/cli dist-tags`. When the new stable
|
||||||
version for every published package. This changes dist-tags only; do not
|
is newer than `beta`, move `beta` to it for every published package. This changes dist-tags only;
|
||||||
republish the packages:
|
do not republish the packages:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
PASEO_VERSION=$(node -p "require('./package.json').version")
|
PASEO_VERSION=$(node -p "require('./package.json').version")
|
||||||
@@ -156,8 +214,8 @@ for package in highlight relay protocol client plugin server cli; do
|
|||||||
done
|
done
|
||||||
```
|
```
|
||||||
|
|
||||||
Verify both npm tags now resolve to `PASEO_VERSION` before considering the
|
Verify `latest` resolves to `PASEO_VERSION`, and `beta` resolves to `PASEO_VERSION` or the
|
||||||
stable release complete.
|
active newer beta, before considering the stable release complete.
|
||||||
|
|
||||||
The Docker workflow builds images from the checked-out source tree on pull requests and on `main` as non-publishing checks. Stable `vX.Y.Z` tag pushes publish `ghcr.io/getpaseo/paseo:X.Y.Z` and `ghcr.io/getpaseo/paseo:latest`; beta `vX.Y.Z-beta.N` tag pushes publish only `ghcr.io/getpaseo/paseo:X.Y.Z-beta.N` and never move `latest`.
|
The Docker workflow builds images from the checked-out source tree on pull requests and on `main` as non-publishing checks. Stable `vX.Y.Z` tag pushes publish `ghcr.io/getpaseo/paseo:X.Y.Z` and `ghcr.io/getpaseo/paseo:latest`; beta `vX.Y.Z-beta.N` tag pushes publish only `ghcr.io/getpaseo/paseo:X.Y.Z-beta.N` and never move `latest`.
|
||||||
|
|
||||||
@@ -175,7 +233,7 @@ npm run version:all:patch
|
|||||||
npm run version:all:minor
|
npm run version:all:minor
|
||||||
npm run release:publish # Publish to npm
|
npm run release:publish # Publish to npm
|
||||||
npm run release:push # Push HEAD + tag (triggers CI workflows)
|
npm run release:push # Push HEAD + tag (triggers CI workflows)
|
||||||
# Then move npm's beta dist-tag to this stable version using the command above.
|
# Then move npm's beta dist-tag to this stable version when it is newer than beta (see above).
|
||||||
```
|
```
|
||||||
|
|
||||||
## Beta flow
|
## Beta flow
|
||||||
@@ -322,7 +380,8 @@ There is no mobile-release workflow under `.github/workflows`. The EAS GitHub ap
|
|||||||
Each stable release publishes the screenshots committed under `assets/store-screenshots/output/` (see [its README](../assets/store-screenshots/README.md) for how they are made). To change the store screenshots, re-render and commit them before you tag.
|
Each stable release publishes the screenshots committed under `assets/store-screenshots/output/` (see [its README](../assets/store-screenshots/README.md) for how they are made). To change the store screenshots, re-render and commit them before you tag.
|
||||||
|
|
||||||
- **App Store:** `submit_review` uploads `output/apple/` and `output/apple-ipad/` to the version it submits, replacing that version's `en-US` screenshots. Apple ties screenshots to an app version, so a version that is already live keeps the ones it shipped with. `Resubmit iOS for App Store review` uploads them again.
|
- **App Store:** `submit_review` uploads `output/apple/` and `output/apple-ipad/` to the version it submits, replacing that version's `en-US` screenshots. Apple ties screenshots to an app version, so a version that is already live keeps the ones it shipped with. `Resubmit iOS for App Store review` uploads them again.
|
||||||
- **Google Play:** `upload_android_screenshots` runs `fastlane android upload_screenshots` after `submit_android`. It replaces only the phone and 10-inch tablet screenshots, never the listing text or changelogs, and skips images whose checksum already matches.
|
- When `submit_review` fails with `appStoreVersions … is not in valid state`, the reason is in the API error's `meta.associatedErrors`, which fastlane does not print. Read it with a `POST /v1/reviewSubmissionItems` against the version. A required age-rating question that Apple added, such as `socialMedia`, fails this way; answer it under App Information > Age Rating in App Store Connect, then resubmit.
|
||||||
|
- **Google Play:** `upload_android_screenshots` runs `fastlane android upload_screenshots` after `submit_android`. It replaces only the `en-US` phone and 10-inch tablet screenshots, never the listing text or changelogs, and skips images whose checksum already matches. The lane stages only `en-US`: supply uploads every locale folder in one edit, and Play rejects F-Droid locales such as `ja`, which fails the whole edit. `Upload Google Play screenshots` reruns the step for the current release without a rebuild.
|
||||||
- **F-Droid:** reads the same files as Google Play. `fastlane/metadata/android/en-US/images/phoneScreenshots/` and `tenInchScreenshots/` hold symlinks to the Google renders. `render.mjs` rewrites them on every render, so added or renamed panels reach Google Play and F-Droid as well.
|
- **F-Droid:** reads the same files as Google Play. `fastlane/metadata/android/en-US/images/phoneScreenshots/` and `tenInchScreenshots/` hold symlinks to the Google renders. `render.mjs` rewrites them on every render, so added or renamed panels reach Google Play and F-Droid as well.
|
||||||
|
|
||||||
Fastlane cannot use the Play key Expo stores for `eas submit`. The Play lane reads its own copy of the same service-account key from the `GOOGLE_PLAY_JSON_KEY` file secret in the EAS `production` environment, and that service account needs the Play Console permission **Manage store presence**.
|
Fastlane cannot use the Play key Expo stores for `eas submit`. The Play lane reads its own copy of the same service-account key from the `GOOGLE_PLAY_JSON_KEY` file secret in the EAS `production` environment, and that service account needs the Play Console permission **Manage store presence**.
|
||||||
@@ -488,7 +547,7 @@ git tag -f android-v0.1.28 HEAD && git push origin android-v0.1.28 --force
|
|||||||
git tag -f v0.1.29-beta.2 HEAD && git push origin v0.1.29-beta.2 --force
|
git tag -f v0.1.29-beta.2 HEAD && git push origin v0.1.29-beta.2 --force
|
||||||
```
|
```
|
||||||
|
|
||||||
This ensures the checkout ref matches the actual code on `main` with the fix included.
|
This ensures the checkout ref matches the code you want built, with the fix included.
|
||||||
|
|
||||||
- `vX.Y.Z` or `vX.Y.Z-beta.N` rebuilds the full tagged release
|
- `vX.Y.Z` or `vX.Y.Z-beta.N` rebuilds the full tagged release
|
||||||
- `desktop-vX.Y.Z` rebuilds desktop for all desktop platforms only
|
- `desktop-vX.Y.Z` rebuilds desktop for all desktop platforms only
|
||||||
@@ -631,7 +690,7 @@ Rules:
|
|||||||
|
|
||||||
This returns every distinct GitHub login that authored or co-authored a commit in the PR. Use those logins for attribution. Fall back to `gh pr view N --json author` only if the commits command returns nothing (which should not happen for merged PRs).
|
This returns every distinct GitHub login that authored or co-authored a commit in the PR. Use those logins for attribution. Fall back to `gh pr view N --json author` only if the commits command returns nothing (which should not happen for merged PRs).
|
||||||
|
|
||||||
When listing PR numbers, `git log --format='%H %s' v<previous>..<release-source-sha> | grep -E '\(#[0-9]+\)$'` pulls the PR number out of squash commit subjects.
|
When listing PR numbers, `git log --cherry-pick --right-only --no-merges --format='%H %s' v<previous>...<release-source-sha> | grep -E '\(#[0-9]+\)$'` pulls the PR number out of squash commit subjects and skips commits the previous stable already shipped as cherry-picks.
|
||||||
|
|
||||||
## Changelog ordering
|
## Changelog ordering
|
||||||
|
|
||||||
@@ -663,11 +722,11 @@ Every entry covers `previous stable release → release source`: first beta, lat
|
|||||||
|
|
||||||
### Beta release
|
### Beta release
|
||||||
|
|
||||||
- [ ] The resolved release source is the intended commit (default `origin/main`) and its existing CI is green
|
- [ ] The release base and changes match the [release base table](#release-base-and-source) and any approved [inventory](#release-inventory), and CI for the release source is green
|
||||||
- [ ] Every PR in the release range has been opened, and its full description and every linked issue have been read before drafting the changelog
|
- [ ] Every PR in the release range has been opened, and its full description and every linked issue have been read before drafting the changelog
|
||||||
- [ ] Fold this beta into the series' single `CHANGELOG.md` entry (heading `## X.Y.Z-beta.N - YYYY-MM-DD`, previous stable → release source), review it against the changelog policy, get approval, and commit it with its [`CHANGELOG.zh-CN.md` translation](#changelog-translations) before cutting the release
|
- [ ] Fold this beta into the series' single `CHANGELOG.md` entry (heading `## X.Y.Z-beta.N - YYYY-MM-DD`, previous stable → release source), review it against the changelog policy, get approval, and commit it with its [`CHANGELOG.zh-CN.md` translation](#changelog-translations) before cutting the release
|
||||||
- [ ] The diff from the previous stable to the resolved release source is classified as patch or minor, with the target version and rationale approved
|
- [ ] The diff from the previous stable to the resolved release source is classified as patch or minor, with the target version and rationale approved
|
||||||
- [ ] Release preparation stayed local until the approved release command pushed the complete branch and tag
|
- [ ] The changelog, ACP, lockfile, and version commits stayed local until the approved release command pushed the release branch and tag
|
||||||
- [ ] `npm run release:beta:patch`, `npm run release:beta:minor`, or `npm run release:beta:next` completes successfully
|
- [ ] `npm run release:beta:patch`, `npm run release:beta:minor`, or `npm run release:beta:next` completes successfully
|
||||||
- [ ] Every GitHub Actions run for the complete release commit and tag is green
|
- [ ] Every GitHub Actions run for the complete release commit and tag is green
|
||||||
- [ ] npm shows the version under the `beta` dist-tag, not `latest`
|
- [ ] npm shows the version under the `beta` dist-tag, not `latest`
|
||||||
@@ -678,22 +737,24 @@ Every entry covers `previous stable release → release source`: first beta, lat
|
|||||||
- [ ] GitHub `Docker` workflow is green and the versioned beta image is published without moving `latest`
|
- [ ] GitHub `Docker` workflow is green and the versioned beta image is published without moving `latest`
|
||||||
- [ ] GitHub `Release Notes Sync` mirrored the beta entry into the prerelease body
|
- [ ] GitHub `Release Notes Sync` mirrored the beta entry into the prerelease body
|
||||||
- [ ] EAS `Release iOS Beta` completed its build, TestFlight distribution, external beta group, and Beta App Review path
|
- [ ] EAS `Release iOS Beta` completed its build, TestFlight distribution, external beta group, and Beta App Review path
|
||||||
|
- [ ] The [reconcile PR](#reconcile-main) brought the shipped changelog entries and version into `main`
|
||||||
- [ ] The release heartbeat was created after the tag push and deleted only after every item above passed
|
- [ ] The release heartbeat was created after the tag push and deleted only after every item above passed
|
||||||
|
|
||||||
### Stable release (or promotion)
|
### Stable release (or promotion)
|
||||||
|
|
||||||
- [ ] Run the pre-release sanity check (see above) and address any findings
|
- [ ] Run the pre-release sanity check (see above) and address any findings
|
||||||
- [ ] The diff from the previous stable to the resolved release source is classified as patch or minor, with the target version and rationale approved
|
- [ ] The diff from the previous stable to the resolved release source is classified as patch or minor, with the target version and rationale approved
|
||||||
- [ ] The resolved release source is the intended commit (default `origin/main`) and its existing CI is green
|
- [ ] The release base and changes match the [release base table](#release-base-and-source) and any approved [inventory](#release-inventory), and CI for the release source is green
|
||||||
|
- [ ] A promotion ships the tested beta's product content after its soak, unless the user explicitly overrode either default
|
||||||
- [ ] Every PR in the release range has been opened, and its full description and every linked issue have been read before drafting the changelog
|
- [ ] Every PR in the release range has been opened, and its full description and every linked issue have been read before drafting the changelog
|
||||||
- [ ] Ensure the approved release inputs are committed locally and the git worktree is clean before running any release command
|
- [ ] Ensure the approved release inputs are committed locally and the git worktree is clean before running any release command
|
||||||
- [ ] Ensure local `npm run typecheck` passes on that exact commit before running any release command
|
- [ ] Ensure local `npm run typecheck` passes on that exact commit before running any release command
|
||||||
- [ ] Update `CHANGELOG.md` with user-facing release notes (features, fixes — not refactors). Promotion renames the series' `## X.Y.Z-beta.N` entry to `## X.Y.Z - YYYY-MM-DD` and re-checks it covers the full release. Commit the matching [`CHANGELOG.zh-CN.md` entry](#changelog-translations) with it
|
- [ ] Update `CHANGELOG.md` with user-facing release notes (features, fixes — not refactors). Promotion renames the series' `## X.Y.Z-beta.N` entry to `## X.Y.Z - YYYY-MM-DD` and re-checks it covers the full release. Commit the matching [`CHANGELOG.zh-CN.md` entry](#changelog-translations) with it
|
||||||
- [ ] Verify the changelog heading follows strict `## X.Y.Z - YYYY-MM-DD` format
|
- [ ] Verify the changelog heading follows strict `## X.Y.Z - YYYY-MM-DD` format
|
||||||
- [ ] Release preparation stayed local until the approved release command pushed the complete branch and tag
|
- [ ] The changelog, ACP, lockfile, and version commits stayed local until the approved release command pushed the release branch and tag
|
||||||
- [ ] `npm run release:patch`, `npm run release:minor`, or `npm run release:promote` completes successfully
|
- [ ] `npm run release:patch`, `npm run release:minor`, or `npm run release:promote` completes successfully
|
||||||
- [ ] Every GitHub Actions run for the complete release commit and tag is green
|
- [ ] Every GitHub Actions run for the complete release commit and tag is green
|
||||||
- [ ] Move npm's `beta` dist-tag to the new stable version for every published package and verify both `latest` and `beta` resolve to it
|
- [ ] `latest` resolves to the new stable, and `beta` resolves to it too unless an active newer beta holds `beta`
|
||||||
- [ ] The GitHub Release was published only after the three stable manifests were uploaded, and it has the changelog body and every expected macOS, Linux, Windows, and Android APK asset
|
- [ ] The GitHub Release was published only after the three stable manifests were uploaded, and it has the changelog body and every expected macOS, Linux, Windows, and Android APK asset
|
||||||
- [ ] GitHub `Desktop Release` workflow for the `v*` tag is green
|
- [ ] GitHub `Desktop Release` workflow for the `v*` tag is green
|
||||||
- [ ] The GitHub Release contains `latest-mac.yml`, `latest-linux.yml`, and `latest.yml`
|
- [ ] The GitHub Release contains `latest-mac.yml`, `latest-linux.yml`, and `latest.yml`
|
||||||
@@ -707,4 +768,5 @@ Every entry covers `previous stable release → release source`: first beta, lat
|
|||||||
- [ ] EAS iOS `submit_ios_for_review` succeeds, putting the build into App Store review
|
- [ ] EAS iOS `submit_ios_for_review` succeeds, putting the build into App Store review
|
||||||
- [ ] EAS Android `build_android` completes for the same tag
|
- [ ] EAS Android `build_android` completes for the same tag
|
||||||
- [ ] EAS Android `submit_android` succeeds, putting the build on its Play Store track
|
- [ ] EAS Android `submit_android` succeeds, putting the build on its Play Store track
|
||||||
|
- [ ] The [reconcile PR](#reconcile-main) brought the shipped changelog entries and version into `main`
|
||||||
- [ ] The release heartbeat was created after the tag push and deleted only after every item above passed
|
- [ ] The release heartbeat was created after the tag push and deleted only after every item above passed
|
||||||
|
|||||||
@@ -0,0 +1,69 @@
|
|||||||
|
# Terminal worker
|
||||||
|
|
||||||
|
Every terminal's PTY lives in the terminal worker, a process separate from the daemon. The worker outlives the daemon, so restarts, crashes and upgrades keep terminals running. This doc covers what the code can't tell you: why the process model is shaped this way, the rules nothing enforces, and the known limits.
|
||||||
|
|
||||||
|
## Process model
|
||||||
|
|
||||||
|
```
|
||||||
|
supervisor (paseo.pid) ──► daemon worker ──► launcher ──► terminal worker ──► PTY programs
|
||||||
|
exits (re-parented to init)
|
||||||
|
```
|
||||||
|
|
||||||
|
- The daemon starts the worker through a launcher (`terminal-worker-process.ts --launch`). The launcher spawns the worker `detached`, waits for `ready` on fd 3, prints the pid and exits, so the worker is re-parented and leaves the daemon's process tree. The supervisor's forced kill uses `tree-kill`, which walks parent pids: a worker that stayed a child, even detached, would die with a hung daemon.
|
||||||
|
- The worker talks to one daemon at a time over a local socket (named pipe on Windows). Losing the daemon means "no controller", not exit: PTYs keep running, events are dropped, and the headless terminal keeps the screen for the next daemon's `listTerminals`.
|
||||||
|
- A socket disconnect triggers reconnection to the same worker and a screen replay. Only confirmed process death retires its sessions; the next terminal creation shares one replacement launch. Dead-worker cleanup stays scoped to that worker, so a healthy draining peer keeps running. Shutdown and detach suppress recovery.
|
||||||
|
- The worker exits on its own when it has no controller and no terminals, on `shutdown`, on SIGTERM (killing its terminals), and when its record disappears (a deleted `$PASEO_HOME`: nobody can ever reach it again).
|
||||||
|
- Its stderr goes to `$PASEO_HOME/terminal-worker.log`. No pipe to the daemon survives the daemon.
|
||||||
|
|
||||||
|
Which triggers keep terminals and which close them is owned by the stop reason (`keepTerminals`) that flows from the request through the supervisor to `stop()`. The kill side always ends in the reaper (`terminal-worker-reaper.ts`), the only path that signals terminal processes outside a connected daemon.
|
||||||
|
|
||||||
|
## Record, socket and secret
|
||||||
|
|
||||||
|
The worker writes `$PASEO_HOME/terminal-worker/<pid>.json` (owner-only) with its identity (birth time + command line carrying `--paseo-terminal-worker <recordId>`), protocol version, socket path, a random secret, the copy it runs from, and each terminal program's pid and birth time.
|
||||||
|
|
||||||
|
- The first frame on the socket must be `hello` with the secret; anything else closes the connection. Anyone who connects can type into every shell, so the record is `0600`, the unix socket `0600` in a `0700` directory.
|
||||||
|
- Unix socket paths have a byte budget (103 on macOS, 107 on Linux). Dev homes under worktrees blow it, so `terminal-worker-socket-path.ts` tries `$PASEO_HOME/terminal-worker/sock/`, then `$TMPDIR/paseo-<uid>/`, then `/tmp/paseo-<uid>/`, and accepts an existing directory only if it is a real `0700` directory owned by you. It never chmods a shared root.
|
||||||
|
- Cleanup signals a process only when its birth time matches the record. Birth times come from `ps -o lstart` with `LC_ALL=C` (it follows `LC_TIME` otherwise) and from `Win32_Process.CreationDate`. A missing birth time is "unknown", never matched by command text: a shell that ran `exec` keeps its pid and birth time but not its argv.
|
||||||
|
- A kill cleanup that cannot confirm every process gone writes `closing-<recordId>.json` beside the worker record. The worker rewrites its own record whenever a terminal starts or exits, so the kill intent has to live in a file it never writes. A closing record is never adopted; the next stop or start retries it.
|
||||||
|
- An unreadable record of either kind makes `daemon status` and a kill restart fail with its path: a kill cleanup that met it could not check what it names, and leaves nothing else behind. A read that fails with `EPERM`, `EBUSY` or `EACCES` is retried for 250ms first: on Windows, opening a record while the worker renames its new copy over it fails that way for a moment.
|
||||||
|
|
||||||
|
## Protocol versions
|
||||||
|
|
||||||
|
`TERMINAL_WORKER_PROTOCOL_VERSION` (`terminal-worker-protocol.ts`) is bumped whenever a request, response or event changes shape. A daemon classifies each live worker at start:
|
||||||
|
|
||||||
|
| Worker reports | Daemon does |
|
||||||
|
| ---------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||||
|
| its own version | adopts it |
|
||||||
|
| one version older | adopts it to drain: it keeps its terminals, takes no new ones, and is let go after its last terminal exits |
|
||||||
|
| two or more older | shuts it down; its terminals close (logged) |
|
||||||
|
| newer, or a version it cannot read | leaves it running, undriven; `list_terminals` and `create_terminal` answer `rpc_error` `terminal_worker_incompatible`, and `paseo daemon status` prints why |
|
||||||
|
|
||||||
|
Never more than two workers run. A new worker launches only when none is current, none is incompatible and fewer than two run. The count comes from the records, so an unreachable or unidentified worker counts, and so does one a cleanup could not confirm gone. When two run, the daemon starts with no current worker, and the first terminal created after one of them exits launches it.
|
||||||
|
|
||||||
|
**The frozen envelope never changes across versions:** the frame format (4-byte length + `v8.serialize`), `hello`/`helloAck`, the `listTerminals` info fields and `shutdown`. That is what lets any daemon close any worker: a kill stop sends `shutdown` to a newer worker it cannot otherwise drive. When you bump the version, keep a previous-version adapter so the draining worker can still be driven, and drop the adapter for the version before that.
|
||||||
|
|
||||||
|
Tests stand up other versions with `PASEO_TERMINAL_WORKER_PROTOCOL_OVERRIDE`, read by the worker. It is test-only.
|
||||||
|
|
||||||
|
## Running from its own copy
|
||||||
|
|
||||||
|
A worker outlives the installation that started it. An npm or desktop update replaces that installation's files, and the next terminal the old worker creates would load node-pty's `spawn-helper` and the zsh integration from paths that no longer exist. So a built daemon does not launch the worker from its install:
|
||||||
|
|
||||||
|
- `npm run build` bundles the worker with esbuild (`packages/server/scripts/build-terminal-worker.mjs`) into `dist/server/terminal-worker/` with its `shell-integration/` beside it. Only node-pty stays external. A package loaded through a module-local `createRequire` is invisible to esbuild and would be missing at run time; `terminal-worker-runtime.test.ts` fails if the bundle loads anything but built-ins and node-pty.
|
||||||
|
- Before launching, the daemon copies the bundle, the shell integration and node-pty (this platform's native build only) into `$PASEO_HOME/terminal-worker/<paseoVersion>-<hash>/` and launches from there. The hash covers the bundle and node-pty, so a local rebuild of the same version gets its own copy.
|
||||||
|
- A copy is deleted once no record names it: after a draining worker exits, after a kill cleanup, and at daemon start. The daemon and the reaper delete copies, never the worker itself, so a worker exiting cannot remove a copy a new worker is about to launch from.
|
||||||
|
- Dev (`.ts` source) launches from source and copies nothing.
|
||||||
|
|
||||||
|
Each create carries the controlling daemon's environment and Paseo CLI path (`baseEnv`, `paseoCliPath`), so a terminal opened after an upgrade gets the new installation's `PASEO_CLI` while older terminals keep theirs.
|
||||||
|
|
||||||
|
## Desktop
|
||||||
|
|
||||||
|
Desktop app updates and version-mismatch restarts stop the daemon with "keep terminals" on macOS and Linux, through `daemon stop --keep-terminals` (the shutdown RPC; SIGTERM always means "stop and close"). A daemon that predates the feature cannot keep terminals: the CLI refuses before sending anything, and desktop logs that and stops it with its terminals closed.
|
||||||
|
|
||||||
|
On Windows every desktop stop closes terminals. In the desktop app the worker runs as `Paseo.exe` with `ELECTRON_RUN_AS_NODE`, and a surviving one would lock the install folder the NSIS update replaces. Restarts, crashes and npm self-updates keep terminals on Windows too.
|
||||||
|
|
||||||
|
## Known limits
|
||||||
|
|
||||||
|
- On macOS `ps` has no session id, so a HUP-ignoring child of a shell that had already exited before cleanup started (re-parented to launchd) is not found. Linux reaches it through the session; a program that `exec`s keeps its entry on every OS.
|
||||||
|
- On Linux, a member of a gone shell's session is signaled only if its environment carries that terminal's `PASEO_TERMINAL_ID`. A job that scrubbed its environment (`env -i`) is reported as unconfirmed, with its pid, and never signaled.
|
||||||
|
- The agent-hook activity URL is baked into each shell when it starts. If the daemon's listen address changes across a restart, older shells report to the old address.
|
||||||
|
- Restoring terminals after a reboot is out of scope: records from an earlier boot are retired without signaling anything.
|
||||||
@@ -10,6 +10,11 @@ then replaces the previous tool state or merges into the current text item. Inte
|
|||||||
are never retained for history or catch-up. Provider history is the durable transcript authority
|
are never retained for history or catch-up. Provider history is the durable transcript authority
|
||||||
and rebuilds the projection when an agent resumes.
|
and rebuilds the projection when an agent resumes.
|
||||||
|
|
||||||
|
Pagination bounds each read, not total resident history. Active and idle agents retain their
|
||||||
|
projected transcript; archive releases it and later history reads rebuild it from the provider.
|
||||||
|
Streaming overhead must remain proportional to the retained transcript. Cumulative text snapshots
|
||||||
|
must be released after their deltas have been consumed.
|
||||||
|
|
||||||
The invariants are:
|
The invariants are:
|
||||||
|
|
||||||
> A continuously subscribed client applies every committed row in order. Opening or resuming an
|
> A continuously subscribed client applies every committed row in order. Opening or resuming an
|
||||||
|
|||||||
@@ -358,6 +358,14 @@ export to `src`, but browser and Electron Metro resolve its `browser` export to
|
|||||||
`lib/module`; CommonJS consumers use `lib/commonjs`. A source-only patch leaves
|
`lib/module`; CommonJS consumers use `lib/commonjs`. A source-only patch leaves
|
||||||
Electron running the old code.
|
Electron running the old code.
|
||||||
|
|
||||||
|
The adaptive-theme patch keeps `colorScheme` reads off the media-query lists
|
||||||
|
owned by Unistyles' change listeners. Chromium defers their events while a window
|
||||||
|
is hidden; reading `matches` on those same lists can consume the pending change.
|
||||||
|
CSS variables then follow the OS theme while `withUnistyles` props retain the old
|
||||||
|
colors. Keep this patch until upstream reads the scheme through separate lists.
|
||||||
|
The desktop browser E2E checks both transition directions in an isolated Electron
|
||||||
|
process, because Playwright's focus emulation prevents real hidden-page behavior.
|
||||||
|
|
||||||
Register every dependency patch in `scripts/postinstall-patches.mjs`. A file in
|
Register every dependency patch in `scripts/postinstall-patches.mjs`. A file in
|
||||||
`patches/` is inert unless that script knows which installed package activates
|
`patches/` is inert unless that script knows which installed package activates
|
||||||
it.
|
it.
|
||||||
|
|||||||
+1
-1
@@ -1 +1 @@
|
|||||||
sha256-5/wat91m8GWxkGVk211lu9KFLhDQNEF/dlMhHMGf8Q0=
|
sha256-8NOrrCAxraQ74lP3Vy59MRhloBfzStTc4rW+ltc42Fg=
|
||||||
|
|||||||
Generated
+24
@@ -40690,6 +40690,7 @@
|
|||||||
"esbuild": "^0.25.12",
|
"esbuild": "^0.25.12",
|
||||||
"express": "^4.18.2",
|
"express": "^4.18.2",
|
||||||
"fast-deep-equal": "^3.1.3",
|
"fast-deep-equal": "^3.1.3",
|
||||||
|
"https-proxy-agent": "^7.0.6",
|
||||||
"lru-cache": "^11.5.1",
|
"lru-cache": "^11.5.1",
|
||||||
"markdown-it": "^10.0.0",
|
"markdown-it": "^10.0.0",
|
||||||
"mnemonic-id": "^3.2.7",
|
"mnemonic-id": "^3.2.7",
|
||||||
@@ -40707,6 +40708,7 @@
|
|||||||
"strip-ansi": "^7.1.2",
|
"strip-ansi": "^7.1.2",
|
||||||
"tree-kill": "^1.2.2",
|
"tree-kill": "^1.2.2",
|
||||||
"typescript": "^5.9.3",
|
"typescript": "^5.9.3",
|
||||||
|
"undici": "^7.24.8",
|
||||||
"uuid": "^9.0.1",
|
"uuid": "^9.0.1",
|
||||||
"which": "^5.0.0",
|
"which": "^5.0.0",
|
||||||
"ws": "^8.14.2",
|
"ws": "^8.14.2",
|
||||||
@@ -41280,6 +41282,15 @@
|
|||||||
"url": "https://opencollective.com/vitest"
|
"url": "https://opencollective.com/vitest"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"packages/server/node_modules/agent-base": {
|
||||||
|
"version": "7.1.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz",
|
||||||
|
"integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 14"
|
||||||
|
}
|
||||||
|
},
|
||||||
"packages/server/node_modules/ajv": {
|
"packages/server/node_modules/ajv": {
|
||||||
"version": "8.20.0",
|
"version": "8.20.0",
|
||||||
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz",
|
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz",
|
||||||
@@ -41349,6 +41360,19 @@
|
|||||||
"@esbuild/win32-x64": "0.25.12"
|
"@esbuild/win32-x64": "0.25.12"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"packages/server/node_modules/https-proxy-agent": {
|
||||||
|
"version": "7.0.6",
|
||||||
|
"resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz",
|
||||||
|
"integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"agent-base": "^7.1.2",
|
||||||
|
"debug": "4"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 14"
|
||||||
|
}
|
||||||
|
},
|
||||||
"packages/server/node_modules/isexe": {
|
"packages/server/node_modules/isexe": {
|
||||||
"version": "3.1.5",
|
"version": "3.1.5",
|
||||||
"resolved": "https://registry.npmjs.org/isexe/-/isexe-3.1.5.tgz",
|
"resolved": "https://registry.npmjs.org/isexe/-/isexe-3.1.5.tgz",
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
name: Upload Google Play screenshots
|
||||||
|
|
||||||
|
# Standalone re-trigger for the release workflow's Google Play screenshot step.
|
||||||
|
# Replaces the en-US phone and tablet screenshots with the committed renders,
|
||||||
|
# without rebuilding or resubmitting the app.
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
android_version_code:
|
||||||
|
type: string
|
||||||
|
required: false
|
||||||
|
description: "versionCode of the production release to attach the change to, e.g. 14000. Leave empty when the production track has a single release."
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
upload_android_screenshots:
|
||||||
|
name: Upload Google Play screenshots
|
||||||
|
environment: production
|
||||||
|
runs_on: macos-medium
|
||||||
|
steps:
|
||||||
|
- uses: eas/checkout
|
||||||
|
- name: Install fastlane
|
||||||
|
run: bundle install
|
||||||
|
- name: Upload screenshots
|
||||||
|
run: |
|
||||||
|
export ANDROID_VERSION_CODE="${{ inputs.android_version_code }}"
|
||||||
|
bundle exec fastlane android upload_screenshots
|
||||||
@@ -102,7 +102,7 @@ export default {
|
|||||||
name: variant.name,
|
name: variant.name,
|
||||||
slug: "voice-mobile",
|
slug: "voice-mobile",
|
||||||
version: nativeReleaseVersion.appVersion,
|
version: nativeReleaseVersion.appVersion,
|
||||||
orientation: "portrait",
|
orientation: "default",
|
||||||
icon: "./assets/images/icon.png",
|
icon: "./assets/images/icon.png",
|
||||||
scheme: "paseo",
|
scheme: "paseo",
|
||||||
userInterfaceStyle: "automatic",
|
userInterfaceStyle: "automatic",
|
||||||
|
|||||||
@@ -59,3 +59,38 @@ describe("Android app config", () => {
|
|||||||
30_000,
|
30_000,
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("follows system rotation on Android", async () => {
|
||||||
|
const manifest = await resolveAndroidManifest();
|
||||||
|
const activity = manifest.application[0].activity.find(
|
||||||
|
(entry: ManifestEntry) => entry.$["android:name"] === ".MainActivity",
|
||||||
|
);
|
||||||
|
expect(activity.$["android:screenOrientation"]).toBe("unspecified");
|
||||||
|
}, 30_000);
|
||||||
|
|
||||||
|
it("allows all orientations on iPhone and iPad", async () => {
|
||||||
|
const { mkdtemp, rm } = await import("node:fs/promises");
|
||||||
|
const { tmpdir } = await import("node:os");
|
||||||
|
const { join } = await import("node:path");
|
||||||
|
const root = await mkdtemp(join(tmpdir(), "paseo-ios-config-"));
|
||||||
|
try {
|
||||||
|
const { exp } = await getPrebuildConfigAsync(__dirname, { platforms: ["ios"] });
|
||||||
|
await compileModsAsync(exp, {
|
||||||
|
projectRoot: root,
|
||||||
|
introspect: true,
|
||||||
|
platforms: ["ios"],
|
||||||
|
assertMissingModProviders: false,
|
||||||
|
});
|
||||||
|
const plist = exp._internal.modResults.ios.infoPlist;
|
||||||
|
const orientations = [
|
||||||
|
"UIInterfaceOrientationPortrait",
|
||||||
|
"UIInterfaceOrientationPortraitUpsideDown",
|
||||||
|
"UIInterfaceOrientationLandscapeLeft",
|
||||||
|
"UIInterfaceOrientationLandscapeRight",
|
||||||
|
];
|
||||||
|
expect(plist.UISupportedInterfaceOrientations).toEqual(orientations);
|
||||||
|
expect(plist["UISupportedInterfaceOrientations~ipad"]).toEqual(orientations);
|
||||||
|
} finally {
|
||||||
|
await rm(root, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
}, 30_000);
|
||||||
|
|||||||
@@ -8,7 +8,11 @@ import {
|
|||||||
openDaemonOverview,
|
openDaemonOverview,
|
||||||
restartDaemonInSettings,
|
restartDaemonInSettings,
|
||||||
expectDaemonRestartComplete,
|
expectDaemonRestartComplete,
|
||||||
|
expectDaemonRestartFailed,
|
||||||
|
plantUnclosableTerminalProgram,
|
||||||
readWorkerPid,
|
readWorkerPid,
|
||||||
|
openLongLivedTerminal,
|
||||||
|
listTerminalIds,
|
||||||
} from "../support/helpers/daemon-lifecycle";
|
} from "../support/helpers/daemon-lifecycle";
|
||||||
|
|
||||||
test("settings restart waits for a replacement worker while retaining the supervisor", async ({
|
test("settings restart waits for a replacement worker while retaining the supervisor", async ({
|
||||||
@@ -29,6 +33,57 @@ test("settings restart waits for a replacement worker while retaining the superv
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("settings restart keeps a terminal", async ({ page }) => {
|
||||||
|
const daemon = await startIsolatedHostDaemon(randomUUID());
|
||||||
|
try {
|
||||||
|
const terminalId = await openLongLivedTerminal(daemon);
|
||||||
|
const previousWorker = await readWorkerPid(daemon);
|
||||||
|
await openDaemonOverview(page, daemon);
|
||||||
|
await restartDaemonInSettings(page);
|
||||||
|
await expectDaemonRestartComplete(page);
|
||||||
|
expect(await readWorkerPid(daemon)).not.toBe(previousWorker);
|
||||||
|
expect(await listTerminalIds(daemon)).toContain(terminalId);
|
||||||
|
} finally {
|
||||||
|
await daemon.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("settings restart and close terminals closes the terminal", async ({ page }) => {
|
||||||
|
const daemon = await startIsolatedHostDaemon(randomUUID());
|
||||||
|
try {
|
||||||
|
await openLongLivedTerminal(daemon);
|
||||||
|
const previousWorker = await readWorkerPid(daemon);
|
||||||
|
await openDaemonOverview(page, daemon);
|
||||||
|
await restartDaemonInSettings(page, { closeTerminals: true });
|
||||||
|
await expectDaemonRestartComplete(page);
|
||||||
|
expect(await readWorkerPid(daemon)).not.toBe(previousWorker);
|
||||||
|
expect(await listTerminalIds(daemon)).toEqual([]);
|
||||||
|
} finally {
|
||||||
|
await daemon.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("settings restart and close terminals shows the processes it could not close", async ({
|
||||||
|
page,
|
||||||
|
}, testInfo) => {
|
||||||
|
test.skip(process.platform === "win32", "The unclosable program is a POSIX zombie");
|
||||||
|
const daemon = await startIsolatedHostDaemon(randomUUID());
|
||||||
|
let program: Awaited<ReturnType<typeof plantUnclosableTerminalProgram>> | null = null;
|
||||||
|
try {
|
||||||
|
program = await plantUnclosableTerminalProgram(daemon);
|
||||||
|
await openDaemonOverview(page, daemon);
|
||||||
|
await restartDaemonInSettings(page, { closeTerminals: true });
|
||||||
|
await expectDaemonRestartFailed(page, `pid ${program.pid}`);
|
||||||
|
await page.screenshot({
|
||||||
|
path: testInfo.outputPath("restart-cleanup-failed.png"),
|
||||||
|
fullPage: true,
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
program?.release();
|
||||||
|
await daemon.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
test("settings restart replaces the worker when a provider CLI answers --version slowly", async ({
|
test("settings restart replaces the worker when a provider CLI answers --version slowly", async ({
|
||||||
page,
|
page,
|
||||||
}) => {
|
}) => {
|
||||||
|
|||||||
@@ -1,3 +1,13 @@
|
|||||||
|
import {
|
||||||
|
withRetainedPlugin,
|
||||||
|
editRetainedDraft,
|
||||||
|
expectRetainedDraft,
|
||||||
|
expectStoredPluginTitle,
|
||||||
|
hideRetainedPreferences,
|
||||||
|
showRetainedPreferences,
|
||||||
|
expectChangedPlugin,
|
||||||
|
expectRemovedPlugin,
|
||||||
|
} from "../support/helpers/plugin-reconnect";
|
||||||
import { verifyPluginTranslations } from "../support/helpers/plugin-translations";
|
import { verifyPluginTranslations } from "../support/helpers/plugin-translations";
|
||||||
import { pluginRequirements } from "../support/helpers/plugin-fixture";
|
import { pluginRequirements } from "../support/helpers/plugin-fixture";
|
||||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||||
@@ -188,3 +198,51 @@ test("plugin content and host labels follow app language without losing an open
|
|||||||
test.setTimeout(180_000);
|
test.setTimeout(180_000);
|
||||||
await verifyPluginTranslations(page, info);
|
await verifyPluginTranslations(page, info);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("retains plugin state offline and reconciles settings, changed code and removal", async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
test.setTimeout(180_000);
|
||||||
|
await withRetainedPlugin(page, async (probe) => {
|
||||||
|
await probe.open();
|
||||||
|
await editRetainedDraft(page, "Connected draft", 0);
|
||||||
|
|
||||||
|
await test.step("local plugin UI remains mounted and usable while disconnected", async () => {
|
||||||
|
await probe.disconnect();
|
||||||
|
await expectRetainedDraft(page, "Connected draft", 1);
|
||||||
|
await editRetainedDraft(page, "Offline draft", 1);
|
||||||
|
await probe.changeStoredTitle("Saved by another client");
|
||||||
|
await expectStoredPluginTitle(page, "Agent monitor");
|
||||||
|
await probe.reconnect();
|
||||||
|
await expectStoredPluginTitle(page, "Saved by another client");
|
||||||
|
await expectRetainedDraft(page, "Offline draft", 2);
|
||||||
|
});
|
||||||
|
|
||||||
|
await test.step("inactive settings refresh without replacing the installation", async () => {
|
||||||
|
await hideRetainedPreferences(page);
|
||||||
|
await probe.disconnect();
|
||||||
|
await probe.changeStoredTitle("Saved while preferences hidden");
|
||||||
|
await probe.reconnect();
|
||||||
|
await showRetainedPreferences(page);
|
||||||
|
await expectStoredPluginTitle(page, "Saved while preferences hidden");
|
||||||
|
await expectRetainedDraft(page, "Offline draft", 2);
|
||||||
|
});
|
||||||
|
|
||||||
|
await test.step("changed code replaces the retained installation after reconnect", async () => {
|
||||||
|
await probe.disconnect();
|
||||||
|
await probe.changeCode();
|
||||||
|
await expectRetainedDraft(page, "Offline draft", 2);
|
||||||
|
await probe.reconnect();
|
||||||
|
await expectChangedPlugin(page);
|
||||||
|
await editRetainedDraft(page, "New code draft", 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
await test.step("removal is reconciled after reconnect", async () => {
|
||||||
|
await probe.disconnect();
|
||||||
|
await probe.remove();
|
||||||
|
await expectRetainedDraft(page, "New code draft", 1);
|
||||||
|
await probe.reconnect();
|
||||||
|
await expectRemovedPlugin(page);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { test } from "../support/fixtures";
|
import { test } from "../support/fixtures";
|
||||||
|
import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate";
|
||||||
import {
|
import {
|
||||||
withTimelinePlugin,
|
withTimelinePlugin,
|
||||||
viewInlineThinkingExample,
|
viewInlineThinkingExample,
|
||||||
@@ -6,6 +7,8 @@ import {
|
|||||||
interactWithStreamingCard,
|
interactWithStreamingCard,
|
||||||
expectWholeCompletedCard,
|
expectWholeCompletedCard,
|
||||||
expectBothConsecutiveTools,
|
expectBothConsecutiveTools,
|
||||||
|
trackPluginChatRecovery,
|
||||||
|
reconnectPluginChat,
|
||||||
} from "../support/helpers/plugin-timeline";
|
} from "../support/helpers/plugin-timeline";
|
||||||
|
|
||||||
for (const width of [1100, 390]) {
|
for (const width of [1100, 390]) {
|
||||||
@@ -13,13 +16,24 @@ for (const width of [1100, 390]) {
|
|||||||
page,
|
page,
|
||||||
}, info) => {
|
}, info) => {
|
||||||
await page.setViewportSize({ width, height: 900 });
|
await page.setViewportSize({ width, height: 900 });
|
||||||
|
const gate = await installDaemonWebSocketGate(page);
|
||||||
await withTimelinePlugin(page, info, "assistant", async (agent) => {
|
await withTimelinePlugin(page, info, "assistant", async (agent) => {
|
||||||
await requestPluginTimeline(agent);
|
await requestPluginTimeline(agent);
|
||||||
await interactWithStreamingCard(page);
|
await interactWithStreamingCard(page);
|
||||||
await agent.client.waitForFinish(agent.agentId, 30_000);
|
await agent.client.waitForFinish(agent.agentId, 30_000);
|
||||||
await expectWholeCompletedCard(page);
|
await expectWholeCompletedCard(page);
|
||||||
// Local state is checked during growth; the viewport remounts on the history handoff.
|
// Local state is checked during growth; the viewport remounts on the history handoff.
|
||||||
|
const recovery = trackPluginChatRecovery(page);
|
||||||
|
gate.holdTimelineResponses(agent.agentId);
|
||||||
await page.reload({ waitUntil: "domcontentloaded" });
|
await page.reload({ waitUntil: "domcontentloaded" });
|
||||||
|
await gate.waitForHeldTimelineResponse();
|
||||||
|
await recovery.expectCatalogWithoutRetransmission();
|
||||||
|
gate.releaseHeldTimelineResponses();
|
||||||
|
await expectWholeCompletedCard(page);
|
||||||
|
await recovery.expectRecoveredWithoutRetransmission();
|
||||||
|
recovery.reset();
|
||||||
|
await reconnectPluginChat(page, gate);
|
||||||
|
await recovery.expectRecoveredWithoutRetransmission();
|
||||||
await expectWholeCompletedCard(page);
|
await expectWholeCompletedCard(page);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -204,19 +204,26 @@ test.describe("Projects settings", () => {
|
|||||||
}) => {
|
}) => {
|
||||||
const repo = await createTempGitRepo("projects-settings-empty-");
|
const repo = await createTempGitRepo("projects-settings-empty-");
|
||||||
const client = await connectSeedClient();
|
const client = await connectSeedClient();
|
||||||
let projectId: string | null = null;
|
let projectViewKey: string | null = null;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await gotoAppShell(page);
|
await gotoAppShell(page);
|
||||||
|
|
||||||
projectId = await addProjectFromSidebar(page, repo.path);
|
projectViewKey = await addProjectFromSidebar(page, repo.path);
|
||||||
await openProjectSettingsFromSidebar(page, projectId);
|
await openProjectSettingsFromSidebar(page, projectViewKey);
|
||||||
|
|
||||||
await expectProjectSettingsFormVisible(page);
|
await expectProjectSettingsFormVisible(page);
|
||||||
await expect(page.getByTestId("project-settings-back-button")).not.toBeVisible();
|
await expect(page.getByTestId("project-settings-back-button")).not.toBeVisible();
|
||||||
} finally {
|
} finally {
|
||||||
if (projectId) {
|
if (projectViewKey) {
|
||||||
await client.removeProject(projectId).catch(() => undefined);
|
const project = (await client.listProjects()).projects.find(
|
||||||
|
(entry) => entry.projectKey === projectViewKey,
|
||||||
|
);
|
||||||
|
expect(project).toBeDefined();
|
||||||
|
await client.removeProject(project!.projectId);
|
||||||
|
expect(
|
||||||
|
(await client.listProjects()).projects.map((entry) => entry.projectKey),
|
||||||
|
).not.toContain(projectViewKey);
|
||||||
}
|
}
|
||||||
await client.close().catch(() => undefined);
|
await client.close().catch(() => undefined);
|
||||||
await repo.cleanup().catch(() => undefined);
|
await repo.cleanup().catch(() => undefined);
|
||||||
|
|||||||
@@ -30,6 +30,10 @@ import {
|
|||||||
addDirectHostFromSettings,
|
addDirectHostFromSettings,
|
||||||
expectHostOnlineWithoutError,
|
expectHostOnlineWithoutError,
|
||||||
expectIdleAgentRelease,
|
expectIdleAgentRelease,
|
||||||
|
editRestartRecoveryPrompt,
|
||||||
|
expectRestartRecoveryEnabled,
|
||||||
|
expectRestartRecoveryPrompt,
|
||||||
|
setRestartRecoveryEnabled,
|
||||||
setIdleAgentRelease,
|
setIdleAgentRelease,
|
||||||
} from "../support/helpers/settings";
|
} from "../support/helpers/settings";
|
||||||
|
|
||||||
@@ -252,3 +256,20 @@ test.describe("Settings host page", () => {
|
|||||||
await expectHostActionCards(page, serverId);
|
await expectHostActionCards(page, serverId);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("restart recovery host controls persist the opt-out and custom prompt", async ({ page }) => {
|
||||||
|
const serverId = getServerId();
|
||||||
|
await gotoAppShell(page);
|
||||||
|
await openSettings(page);
|
||||||
|
await openSettingsHost(page, serverId);
|
||||||
|
await openHostSection(page, serverId, "agents");
|
||||||
|
await expectRestartRecoveryEnabled(page, true);
|
||||||
|
await expectRestartRecoveryPrompt(page, "Resume working.");
|
||||||
|
await editRestartRecoveryPrompt(page, "Continue the interrupted work.");
|
||||||
|
await setRestartRecoveryEnabled(page, false);
|
||||||
|
await page.reload();
|
||||||
|
await expectRestartRecoveryEnabled(page, false);
|
||||||
|
await setRestartRecoveryEnabled(page, true);
|
||||||
|
await expectRestartRecoveryPrompt(page, "Continue the interrupted work.");
|
||||||
|
await editRestartRecoveryPrompt(page, "Resume working.");
|
||||||
|
});
|
||||||
|
|||||||
@@ -53,11 +53,18 @@ async function quickDragFirstRowAfterSecond(
|
|||||||
await page.mouse.move(source.x, source.y + 7);
|
await page.mouse.move(source.x, source.y + 7);
|
||||||
await expect(trailingScrim).toHaveCount(0);
|
await expect(trailingScrim).toHaveCount(0);
|
||||||
await page.mouse.move(target.x, target.y, { steps: 4 });
|
await page.mouse.move(target.x, target.y, { steps: 4 });
|
||||||
await page.mouse.up();
|
await finishSidebarDrag(page);
|
||||||
|
|
||||||
await expect.poll(() => rowTestIds(rows)).toEqual([before[1], before[0]]);
|
await expect.poll(() => rowTestIds(rows)).toEqual([before[1], before[0]]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function finishSidebarDrag(page: Page): Promise<void> {
|
||||||
|
await page.mouse.up();
|
||||||
|
// dnd-kit's pointer sensor keeps its document click blocker for 50 ms after drop.
|
||||||
|
// Row order updates before that blocker is removed; wait before the next user action.
|
||||||
|
await page.waitForTimeout(60);
|
||||||
|
}
|
||||||
|
|
||||||
async function dragWithoutReordering(rows: Locator): Promise<void> {
|
async function dragWithoutReordering(rows: Locator): Promise<void> {
|
||||||
const before = await rowTestIds(rows);
|
const before = await rowTestIds(rows);
|
||||||
const source = await visibleBoundingBox(rows.nth(0));
|
const source = await visibleBoundingBox(rows.nth(0));
|
||||||
@@ -66,7 +73,7 @@ async function dragWithoutReordering(rows: Locator): Promise<void> {
|
|||||||
await page.mouse.move(source.x + source.width / 2, source.y + source.height / 2);
|
await page.mouse.move(source.x + source.width / 2, source.y + source.height / 2);
|
||||||
await page.mouse.down();
|
await page.mouse.down();
|
||||||
await page.mouse.move(target.x + target.width / 2, target.y + target.height / 2, { steps: 5 });
|
await page.mouse.move(target.x + target.width / 2, target.y + target.height / 2, { steps: 5 });
|
||||||
await page.mouse.up();
|
await finishSidebarDrag(page);
|
||||||
await expect.poll(() => rowTestIds(rows)).toEqual(before);
|
await expect.poll(() => rowTestIds(rows)).toEqual(before);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,134 @@
|
|||||||
|
import { expect, type Locator, type Page } from "@playwright/test";
|
||||||
|
import { test } from "../support/fixtures";
|
||||||
|
import { runWorkspaceActionFromCommandCenter } from "../support/helpers/command-center-workspace-actions";
|
||||||
|
import { createCreationScenario } from "../support/helpers/creation";
|
||||||
|
import { clickNewChat, gotoWorkspace } from "../support/helpers/launcher";
|
||||||
|
import { seedWorkspace } from "../support/helpers/seed-client";
|
||||||
|
import { waitForWorkspaceTabsVisible } from "../support/helpers/workspace-tabs";
|
||||||
|
|
||||||
|
const DRAG_DISTANCE = -40;
|
||||||
|
const TOLERANCE_PX = 2;
|
||||||
|
|
||||||
|
function splitDividers(page: Page): Locator {
|
||||||
|
return page.getByTestId("workspace-split-resize-handle").filter({ visible: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function dividerX(divider: Locator): Promise<number> {
|
||||||
|
const box = await divider.boundingBox();
|
||||||
|
if (!box) throw new Error("Divider has no bounding box");
|
||||||
|
return box.x;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function dragDivider(divider: Locator, deltaX: number): Promise<void> {
|
||||||
|
const page = divider.page();
|
||||||
|
const box = await divider.boundingBox();
|
||||||
|
if (!box) throw new Error("Divider has no bounding box");
|
||||||
|
const x = box.x + box.width / 2;
|
||||||
|
const y = box.y + box.height / 2;
|
||||||
|
await page.mouse.move(x, y);
|
||||||
|
await page.mouse.down();
|
||||||
|
await page.mouse.move(x + deltaX, y, { steps: 8 });
|
||||||
|
await page.mouse.up();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function dragDividerWithTouch(divider: Locator, deltaX: number): Promise<void> {
|
||||||
|
const page = divider.page();
|
||||||
|
const box = await divider.boundingBox();
|
||||||
|
if (!box) throw new Error("Divider has no bounding box");
|
||||||
|
const x = box.x + box.width / 2;
|
||||||
|
const y = box.y + box.height / 2;
|
||||||
|
const input = await page.context().newCDPSession(page);
|
||||||
|
try {
|
||||||
|
await input.send("Input.dispatchTouchEvent", { type: "touchStart", touchPoints: [{ x, y }] });
|
||||||
|
for (let step = 1; step <= 8; step++) {
|
||||||
|
await input.send("Input.dispatchTouchEvent", {
|
||||||
|
type: "touchMove",
|
||||||
|
touchPoints: [{ x: x + (deltaX * step) / 8, y }],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
await input.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] });
|
||||||
|
} finally {
|
||||||
|
await input.detach();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function splitIntoFourPanes(page: Page): Promise<void> {
|
||||||
|
for (const expectedDividers of [1, 2, 3]) {
|
||||||
|
await runWorkspaceActionFromCommandCenter(page, "Split pane right");
|
||||||
|
await expect(splitDividers(page)).toHaveCount(expectedDividers);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function expectDividersTrackPointer(
|
||||||
|
page: Page,
|
||||||
|
distance = DRAG_DISTANCE,
|
||||||
|
drag = dragDivider,
|
||||||
|
): Promise<void> {
|
||||||
|
for (const index of [0, 1, 2]) {
|
||||||
|
const divider = splitDividers(page).nth(index);
|
||||||
|
const before = await dividerX(divider);
|
||||||
|
await drag(divider, distance);
|
||||||
|
await expect
|
||||||
|
.poll(async () => Math.abs((await dividerX(divider)) - before - distance), {
|
||||||
|
message: `divider ${index + 1} should stay under the pointer`,
|
||||||
|
})
|
||||||
|
.toBeLessThanOrEqual(TOLERANCE_PX);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const hasTouch of [false, true]) {
|
||||||
|
test.describe(`Split pane drag tracking (${hasTouch ? "coarse" : "fine"} pointer)`, () => {
|
||||||
|
test.use({ hasTouch });
|
||||||
|
|
||||||
|
test("a divider moves as far as the pointer in the main row", async ({ page }) => {
|
||||||
|
await page.setViewportSize({ width: 1600, height: 900 });
|
||||||
|
const workspace = await seedWorkspace({ repoPrefix: "split-drag-tracking-" });
|
||||||
|
try {
|
||||||
|
await gotoWorkspace(page, workspace.workspaceId);
|
||||||
|
await waitForWorkspaceTabsVisible(page);
|
||||||
|
await clickNewChat(page);
|
||||||
|
await splitIntoFourPanes(page);
|
||||||
|
await expectDividersTrackPointer(
|
||||||
|
page,
|
||||||
|
DRAG_DISTANCE,
|
||||||
|
hasTouch ? dragDividerWithTouch : dragDivider,
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
await workspace.cleanup();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("dividers track the pointer after app creation, Explorer changes and reload", async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
await page.setViewportSize({ width: 1600, height: 900 });
|
||||||
|
const creation = await createCreationScenario(page);
|
||||||
|
try {
|
||||||
|
await creation.openWorkspaceForm("local");
|
||||||
|
await creation.submitPrompt("Reply briefly.", "Create");
|
||||||
|
await creation.expectAssistantReply();
|
||||||
|
await waitForWorkspaceTabsVisible(page);
|
||||||
|
await splitIntoFourPanes(page);
|
||||||
|
await expectDividersTrackPointer(page);
|
||||||
|
await page
|
||||||
|
.getByTestId("workspace-explorer-toggle")
|
||||||
|
.filter({ visible: true })
|
||||||
|
.first()
|
||||||
|
.click();
|
||||||
|
await expect(page.getByTestId("workspace-explorer-sidebar")).toBeVisible();
|
||||||
|
await expectDividersTrackPointer(page, -DRAG_DISTANCE);
|
||||||
|
await page
|
||||||
|
.getByTestId("workspace-explorer-toggle")
|
||||||
|
.filter({ visible: true })
|
||||||
|
.first()
|
||||||
|
.click();
|
||||||
|
await expect(page.getByTestId("workspace-explorer-sidebar")).not.toBeVisible();
|
||||||
|
await page.reload();
|
||||||
|
await expect(splitDividers(page)).toHaveCount(3);
|
||||||
|
await expectDividersTrackPointer(page);
|
||||||
|
} finally {
|
||||||
|
await creation.cleanup();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -717,15 +717,15 @@ test("open usage clocks advance without refreshing or reopening", async ({ page
|
|||||||
await openCompactUsageWithClock(page, now);
|
await openCompactUsageWithClock(page, now);
|
||||||
const card = page.getByTestId("usage-report-login-journey:account");
|
const card = page.getByTestId("usage-report-login-journey:account");
|
||||||
await expect(card.getByTestId("usage-freshness")).toHaveText("Updated just now");
|
await expect(card.getByTestId("usage-freshness")).toHaveText("Updated just now");
|
||||||
await expect(card.getByText("resets 30m", { exact: false }).first()).toBeVisible();
|
await expect(card.getByText("resets in 30m", { exact: false }).first()).toBeVisible();
|
||||||
// The shared minute clock is wall-aligned, and the daemon timestamps use real time.
|
// The shared minute clock is wall-aligned, and the daemon timestamps use real time.
|
||||||
// After two browser minutes the latest displayed tick is one or two minutes old.
|
// After two browser minutes the latest displayed tick is one or two minutes old.
|
||||||
await advanceUsageClock(page, 120_000);
|
await advanceUsageClock(page, 120_000);
|
||||||
await expect(card.getByTestId("usage-freshness")).toHaveText(/^Updated [12]m ago$/);
|
await expect(card.getByTestId("usage-freshness")).toHaveText(/^Updated [12]m ago$/);
|
||||||
await expect(card.getByText(/resets (28|29)m/).first()).toBeVisible();
|
await expect(card.getByText(/resets in (28|29)m/).first()).toBeVisible();
|
||||||
await expect(card.getByText(/runs out (28|29)m/)).toBeVisible();
|
await expect(card.getByText(/runs out in (28|29)m/)).toBeVisible();
|
||||||
await expect(card.getByTestId("provider-usage-balance-credits-reset")).toHaveText(
|
await expect(card.getByTestId("provider-usage-balance-credits-reset")).toHaveText(
|
||||||
/^resets (28|29)m$/,
|
/^resets in (28|29)m\s·\s/,
|
||||||
);
|
);
|
||||||
} finally {
|
} finally {
|
||||||
await login.cleanup();
|
await login.cleanup();
|
||||||
|
|||||||
@@ -0,0 +1,69 @@
|
|||||||
|
import { expect, test } from "../support/fixtures";
|
||||||
|
import { gotoAppShell } from "../support/helpers/app";
|
||||||
|
import { seedSidebarFooterPreferences } from "../support/helpers/sidebar-nav-settings";
|
||||||
|
import { installUsageReportsFixture } from "../support/helpers/usage-reports";
|
||||||
|
import {
|
||||||
|
claudeAndCodexReports,
|
||||||
|
openUsageFromIcon,
|
||||||
|
openUsageOptions,
|
||||||
|
closeUsageOptions,
|
||||||
|
closeUsage,
|
||||||
|
expectNoUsageItem,
|
||||||
|
expectPinnedUsage,
|
||||||
|
} from "../support/helpers/usage-sidebar-item";
|
||||||
|
|
||||||
|
test("Check usage applies to the host and Turn on restores cards", async ({
|
||||||
|
page,
|
||||||
|
e2eWorkerClient,
|
||||||
|
}) => {
|
||||||
|
test.setTimeout(180_000);
|
||||||
|
const previous = (await e2eWorkerClient.getDaemonConfig()).config.usage ?? { enabled: true };
|
||||||
|
try {
|
||||||
|
const usage = await installUsageReportsFixture(page, {
|
||||||
|
lists: [() => claudeAndCodexReports()],
|
||||||
|
});
|
||||||
|
await page.setViewportSize({ width: 1440, height: 1000 });
|
||||||
|
await seedSidebarFooterPreferences(page, [{ key: "usage", visible: true }]);
|
||||||
|
await gotoAppShell(page);
|
||||||
|
await expectPinnedUsage(page, ["31% 5h", "54% wk", "7% 5h", "12% wk"]);
|
||||||
|
await openUsageFromIcon(page);
|
||||||
|
await usage.waitForListRequests(1);
|
||||||
|
await openUsageOptions(page);
|
||||||
|
await page.getByRole("switch", { name: "Check usage", exact: true }).click();
|
||||||
|
await closeUsageOptions(page);
|
||||||
|
await expect(page.getByRole("button", { name: "Turn on", exact: true })).toBeVisible();
|
||||||
|
await expect(page.getByRole("button", { name: "Refresh all", exact: true })).toHaveCount(0);
|
||||||
|
expect((await e2eWorkerClient.getDaemonConfig()).config.usage).toEqual({ enabled: false });
|
||||||
|
await expectNoUsageItem(page);
|
||||||
|
const before = usage.listRequests().length;
|
||||||
|
await closeUsage(page);
|
||||||
|
await page.reload();
|
||||||
|
await openUsageFromIcon(page);
|
||||||
|
await expect(page.getByRole("button", { name: "Turn on", exact: true })).toBeVisible();
|
||||||
|
expect(usage.listRequests()).toHaveLength(before);
|
||||||
|
await page.getByRole("button", { name: "Turn on", exact: true }).click();
|
||||||
|
await expect(page.getByText("Claude", { exact: true })).toBeVisible();
|
||||||
|
expect((await e2eWorkerClient.getDaemonConfig()).config.usage).toEqual({ enabled: true });
|
||||||
|
// A separate client changes the policy, as another device would.
|
||||||
|
await e2eWorkerClient.patchDaemonConfig({ usage: { enabled: false } });
|
||||||
|
await expect(page.getByRole("button", { name: "Turn on", exact: true })).toBeVisible();
|
||||||
|
await e2eWorkerClient.patchDaemonConfig({ usage: { enabled: true } });
|
||||||
|
await expect(page.getByText("Claude", { exact: true })).toBeVisible();
|
||||||
|
} finally {
|
||||||
|
await e2eWorkerClient.patchDaemonConfig({ usage: previous });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("older hosts keep usage without a Check usage switch", async ({ page }) => {
|
||||||
|
test.setTimeout(180_000);
|
||||||
|
await installUsageReportsFixture(page, {
|
||||||
|
usageSettingSupported: false,
|
||||||
|
lists: [() => claudeAndCodexReports()],
|
||||||
|
});
|
||||||
|
await page.setViewportSize({ width: 1440, height: 1000 });
|
||||||
|
await gotoAppShell(page);
|
||||||
|
await openUsageFromIcon(page);
|
||||||
|
await expect(page.getByText("Claude", { exact: true })).toBeVisible();
|
||||||
|
await openUsageOptions(page);
|
||||||
|
await expect(page.getByRole("switch", { name: "Check usage", exact: true })).toHaveCount(0);
|
||||||
|
});
|
||||||
@@ -441,3 +441,31 @@ test("released hosts supply source logos through the client conversion", async (
|
|||||||
).toHaveAttribute("d", codexPath);
|
).toHaveAttribute("d", codexPath);
|
||||||
await qaScreenshot(page, "released-host-usage-modal");
|
await qaScreenshot(page, "released-host-usage-modal");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("hidden usage sends no requests until opened", async ({ page }) => {
|
||||||
|
test.setTimeout(180_000);
|
||||||
|
const usage = await installUsageReportsFixture(page, { lists: [() => claudeAndCodexReports()] });
|
||||||
|
await page.setViewportSize(WIDE);
|
||||||
|
await gotoAppShell(page);
|
||||||
|
await expectNoUsageItem(page);
|
||||||
|
await expect(page.getByRole("button", { name: "Usage", exact: true })).toBeVisible({
|
||||||
|
timeout: 90_000,
|
||||||
|
});
|
||||||
|
await openSidebarNavSettings(page);
|
||||||
|
await expectFooterItemSetting(page, "usage", false);
|
||||||
|
await leaveSettings(page);
|
||||||
|
expect(usage.listRequests()).toHaveLength(0);
|
||||||
|
await openUsageFromIcon(page);
|
||||||
|
await usage.waitForListRequests(1);
|
||||||
|
expect(usage.listRequests()).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("visible usage summary requests reports on load", async ({ page }) => {
|
||||||
|
test.setTimeout(180_000);
|
||||||
|
const usage = await installUsageReportsFixture(page, { lists: [() => claudeAndCodexReports()] });
|
||||||
|
await seedSidebarFooterPreferences(page, [{ key: "usage", visible: true }]);
|
||||||
|
await page.setViewportSize(WIDE);
|
||||||
|
await gotoAppShell(page);
|
||||||
|
await expectPinnedUsage(page, ["31% 5h", "54% wk", "7% 5h", "12% wk"]);
|
||||||
|
expect(usage.listRequests()).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|||||||
@@ -0,0 +1,104 @@
|
|||||||
|
// Run a release build with a connected workspace open and the keyboard hidden.
|
||||||
|
// ANDROID_SERIAL=emulator-5574 node packages/app/e2e/mobile/fold/android.mjs
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { execFileSync } from "node:child_process";
|
||||||
|
import { mkdirSync, writeFileSync } from "node:fs";
|
||||||
|
import { resolve } from "node:path";
|
||||||
|
import { setTimeout as delay } from "node:timers/promises";
|
||||||
|
|
||||||
|
const serial = process.env.ANDROID_SERIAL;
|
||||||
|
assert(serial, "Set ANDROID_SERIAL to a booted Android foldable emulator");
|
||||||
|
const appId = process.env.PASEO_MOBILE_APP_ID ?? "sh.paseo.debug";
|
||||||
|
const session = "android-fold";
|
||||||
|
const artifacts = resolve(".dev/agent-device-artifacts/android-fold");
|
||||||
|
const env = {
|
||||||
|
...process.env,
|
||||||
|
AGENT_DEVICE_STATE_DIR: resolve(".dev/agent-device-android-fold"),
|
||||||
|
};
|
||||||
|
mkdirSync(artifacts, { recursive: true });
|
||||||
|
|
||||||
|
function run(binary, args) {
|
||||||
|
return execFileSync(binary, args, { env, encoding: "utf8", timeout: 60_000 });
|
||||||
|
}
|
||||||
|
function adb(...args) {
|
||||||
|
return run("adb", ["-s", serial, ...args]);
|
||||||
|
}
|
||||||
|
function ad(...args) {
|
||||||
|
return run("agent-device", [...args, "--session", session]);
|
||||||
|
}
|
||||||
|
function pid() {
|
||||||
|
return adb("shell", "pidof", appId).trim();
|
||||||
|
}
|
||||||
|
function open() {
|
||||||
|
ad("open", appId, "--platform", "android", "--serial", serial, "--no-test-ime");
|
||||||
|
}
|
||||||
|
function stateId(name) {
|
||||||
|
const states = adb("shell", "cmd", "device_state", "print-states");
|
||||||
|
const match = states.match(new RegExp(`identifier=(\\d+), name='${name}'`));
|
||||||
|
assert(match, `Emulator must expose the ${name} posture: ${states}`);
|
||||||
|
return match[1];
|
||||||
|
}
|
||||||
|
|
||||||
|
async function expectLayout(posture) {
|
||||||
|
const compact = posture === "CLOSED";
|
||||||
|
const expectedId = compact ? "workspace-tab-switcher-trigger" : "workspace-tabs-scroll";
|
||||||
|
const unexpectedId = compact ? "workspace-tabs-scroll" : "workspace-tab-switcher-trigger";
|
||||||
|
const deadline = Date.now() + 15_000;
|
||||||
|
let nodes = [];
|
||||||
|
do {
|
||||||
|
let data;
|
||||||
|
try {
|
||||||
|
({ data } = JSON.parse(ad("snapshot", "-i", "--json")));
|
||||||
|
} catch (error) {
|
||||||
|
// During display handoff Android briefly has no capturable app window.
|
||||||
|
if (!error.stdout?.includes("insufficient foreground app content")) throw error;
|
||||||
|
await delay(200);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
assert.equal(data.appBundleId, appId, "Snapshot must belong to Paseo");
|
||||||
|
nodes = data.nodes;
|
||||||
|
if (
|
||||||
|
nodes.some((node) => node.identifier === expectedId) &&
|
||||||
|
!nodes.some((node) => node.identifier === unexpectedId)
|
||||||
|
) {
|
||||||
|
writeFileSync(resolve(artifacts, `${posture}.json`), JSON.stringify(data, null, 2));
|
||||||
|
console.log(`PASS: ${posture} uses ${compact ? "compact" : "wide"} workspace controls`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await delay(200);
|
||||||
|
} while (Date.now() < deadline);
|
||||||
|
writeFileSync(resolve(artifacts, `${posture}-failure.json`), JSON.stringify(nodes, null, 2));
|
||||||
|
writeFileSync(
|
||||||
|
resolve(artifacts, "native-failure.txt"),
|
||||||
|
adb("shell", "dumpsys", "activity", "top"),
|
||||||
|
);
|
||||||
|
assert.fail(`${posture}: expected ${expectedId}, without ${unexpectedId}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const closed = stateId("CLOSED");
|
||||||
|
const opened = stateId("OPENED");
|
||||||
|
const initialState = adb("shell", "cmd", "device_state", "state").match(
|
||||||
|
/Committed state: DeviceState\{identifier=(\d+)/,
|
||||||
|
)?.[1];
|
||||||
|
assert(initialState, "Could not read the initial fold state");
|
||||||
|
|
||||||
|
try {
|
||||||
|
adb("shell", "cmd", "device_state", "state", opened);
|
||||||
|
open();
|
||||||
|
await expectLayout("OPENED");
|
||||||
|
const initialPid = pid();
|
||||||
|
for (const [posture, id] of [
|
||||||
|
["CLOSED", closed],
|
||||||
|
["OPENED", opened],
|
||||||
|
]) {
|
||||||
|
adb("shell", "input", "keyevent", "KEYCODE_HOME");
|
||||||
|
adb("shell", "cmd", "device_state", "state", id);
|
||||||
|
// Resume immediately: waiting for configuration delivery hides the regression.
|
||||||
|
open();
|
||||||
|
await expectLayout(posture);
|
||||||
|
assert.equal(pid(), initialPid, "Fold/resume must preserve the app process");
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
adb("shell", "cmd", "device_state", "state", initialState);
|
||||||
|
ad("close");
|
||||||
|
}
|
||||||
@@ -1,3 +1,7 @@
|
|||||||
|
import { execFile, spawn } from "node:child_process";
|
||||||
|
import { writeFile } from "node:fs/promises";
|
||||||
|
import path from "node:path";
|
||||||
|
import { promisify } from "node:util";
|
||||||
import { expect, type Page } from "@playwright/test";
|
import { expect, type Page } from "@playwright/test";
|
||||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||||
import { connectDaemonClient } from "./daemon-client-loader";
|
import { connectDaemonClient } from "./daemon-client-loader";
|
||||||
@@ -15,14 +19,27 @@ export async function openDaemonOverview(page: Page, daemon: IsolatedHostDaemon)
|
|||||||
await openHostSection(page, daemon.serverId, "host");
|
await openHostSection(page, daemon.serverId, "host");
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function restartDaemonInSettings(page: Page) {
|
export async function restartDaemonInSettings(
|
||||||
const button = page.getByRole("button", { name: "Restart", exact: true });
|
page: Page,
|
||||||
|
options: { closeTerminals?: boolean } = {},
|
||||||
|
) {
|
||||||
|
const button = page.getByRole("button", {
|
||||||
|
name: options.closeTerminals ? "Restart and close terminals" : "Restart",
|
||||||
|
exact: true,
|
||||||
|
});
|
||||||
await expect(button).toBeEnabled();
|
await expect(button).toBeEnabled();
|
||||||
page.once("dialog", (dialog) => dialog.accept());
|
page.once("dialog", (dialog) => dialog.accept());
|
||||||
await button.click();
|
await button.click();
|
||||||
await expect(page.getByRole("button", { name: "Restarting...", exact: true })).toBeDisabled();
|
await expect(page.getByRole("button", { name: "Restarting...", exact: true })).toBeDisabled();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function expectDaemonRestartFailed(page: Page, text: string) {
|
||||||
|
const error = page.getByTestId("host-page-restart-error");
|
||||||
|
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) {
|
export async function expectDaemonRestartComplete(page: Page) {
|
||||||
await expect(page.getByRole("button", { name: "Restart", exact: true })).toBeEnabled({
|
await expect(page.getByRole("button", { name: "Restart", exact: true })).toBeEnabled({
|
||||||
timeout: 30_000,
|
timeout: 30_000,
|
||||||
@@ -40,3 +57,100 @@ export async function readWorkerPid(daemon: IsolatedHostDaemon): Promise<number>
|
|||||||
await client.close();
|
await client.close();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Opens a terminal on the isolated daemon that runs a long-lived program. */
|
||||||
|
export async function openLongLivedTerminal(daemon: IsolatedHostDaemon): Promise<string> {
|
||||||
|
const client = await connectDaemonClient<DaemonClient>({
|
||||||
|
port: daemon.port,
|
||||||
|
clientIdPrefix: "lifecycle-terminal",
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
const workspace = await client.createWorkspace({
|
||||||
|
source: { kind: "directory", path: daemon.paseoHome },
|
||||||
|
title: "lifecycle",
|
||||||
|
});
|
||||||
|
if (!workspace.workspace) throw new Error(workspace.error ?? "Workspace creation failed");
|
||||||
|
const created = await client.createTerminal(daemon.paseoHome, "lifecycle", undefined, {
|
||||||
|
workspaceId: workspace.workspace.id,
|
||||||
|
command: process.execPath,
|
||||||
|
args: ["-e", "setInterval(() => {}, 1e9)"],
|
||||||
|
});
|
||||||
|
if (!created.terminal) throw new Error(created.error ?? "Terminal creation failed");
|
||||||
|
return created.terminal.id;
|
||||||
|
} finally {
|
||||||
|
await client.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listTerminalIds(daemon: IsolatedHostDaemon): Promise<string[]> {
|
||||||
|
const client = await connectDaemonClient<DaemonClient>({
|
||||||
|
port: daemon.port,
|
||||||
|
clientIdPrefix: "lifecycle-terminals",
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
return (await client.listTerminals()).terminals.map((terminal) => terminal.id);
|
||||||
|
} finally {
|
||||||
|
await client.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const execFileAsync = promisify(execFile);
|
||||||
|
|
||||||
|
async function psField(pid: number, field: "stat" | "lstart"): Promise<string> {
|
||||||
|
const { stdout } = await execFileAsync("ps", ["-o", `${field}=`, "-p", String(pid)], {
|
||||||
|
env: { ...process.env, LC_ALL: "C" },
|
||||||
|
});
|
||||||
|
return stdout.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UnclosableTerminalProgram {
|
||||||
|
pid: number;
|
||||||
|
/** Ends the program's parent, which lets the system reap the program. */
|
||||||
|
release(): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Leaves in the daemon's home the record a dead terminal worker leaves, naming one terminal
|
||||||
|
* program that SIGKILL cannot remove: a zombie whose parent (an exec'd `sleep`) never waits for
|
||||||
|
* it. A kill cleanup can only report it as still running. POSIX only.
|
||||||
|
*/
|
||||||
|
export async function plantUnclosableTerminalProgram(
|
||||||
|
daemon: IsolatedHostDaemon,
|
||||||
|
): Promise<UnclosableTerminalProgram> {
|
||||||
|
const parent = spawn("/bin/sh", ["-c", "sleep 0 & echo $!; exec sleep 600"], {
|
||||||
|
stdio: ["ignore", "pipe", "ignore"],
|
||||||
|
});
|
||||||
|
parent.unref();
|
||||||
|
const release = () => {
|
||||||
|
if (parent.exitCode === null && parent.signalCode === null) parent.kill("SIGKILL");
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
const pid = await new Promise<number>((resolve) => {
|
||||||
|
parent.stdout!.once("data", (chunk: Buffer) => resolve(Number(chunk.toString().trim())));
|
||||||
|
});
|
||||||
|
await expect.poll(async () => (await psField(pid, "stat")).startsWith("Z")).toBe(true);
|
||||||
|
const gone = spawn(process.execPath, ["-e", ""], { stdio: "ignore" });
|
||||||
|
await new Promise((resolve) => gone.once("exit", resolve));
|
||||||
|
const record = {
|
||||||
|
recordId: "planted-record",
|
||||||
|
pid: gone.pid,
|
||||||
|
bootId: null,
|
||||||
|
createdAt: new Date().toISOString(),
|
||||||
|
identity: { startedAt: "Thu Jan 1 00:00:00 1970", commandLine: "planted-worker" },
|
||||||
|
protocolVersion: 1,
|
||||||
|
paseoVersion: "0.0.0-test",
|
||||||
|
socketPath: path.join(daemon.paseoHome, "planted-worker.sock"),
|
||||||
|
secret: "planted-secret",
|
||||||
|
terminals: [{ id: "planted-terminal", pid, startedAt: await psField(pid, "lstart") }],
|
||||||
|
};
|
||||||
|
await writeFile(
|
||||||
|
path.join(daemon.paseoHome, "terminal-worker", `${gone.pid}.json`),
|
||||||
|
`${JSON.stringify(record, null, 2)}\n`,
|
||||||
|
{ mode: 0o600 },
|
||||||
|
);
|
||||||
|
return { pid, release };
|
||||||
|
} catch (error) {
|
||||||
|
release();
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,159 @@
|
|||||||
|
import { writeFile } from "node:fs/promises";
|
||||||
|
import path from "node:path";
|
||||||
|
import { settingsRpc } from "@getpaseo/plugin";
|
||||||
|
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { expect, type Page } from "../fixtures";
|
||||||
|
import { gotoAppShell } from "./app";
|
||||||
|
import { installDaemonWebSocketGate } from "./daemon-websocket-gate";
|
||||||
|
import { connectDaemonClient } from "./daemon-client-loader";
|
||||||
|
import { copyPluginExample, pluginRequirements } from "./plugin-fixture";
|
||||||
|
|
||||||
|
const PLUGIN_ID = "retained-plugin-e2e";
|
||||||
|
|
||||||
|
export function retainedPluginSource(version: string) {
|
||||||
|
return `import { useState } from "react";
|
||||||
|
import { Text, View, TextInput, Pressable } from "react-native";
|
||||||
|
import { useSettings } from "@getpaseo/plugin/client";
|
||||||
|
import { preferences } from "./shared/preferences";
|
||||||
|
function Preferences({ color }) {
|
||||||
|
const settings = useSettings(preferences);
|
||||||
|
return <Text style={{ color }}>{settings.status === "ready" ? "Stored title: " + settings.values.title : "Preferences " + settings.status}</Text>;
|
||||||
|
}
|
||||||
|
function Surface({ theme }) {
|
||||||
|
const [draft, setDraft] = useState("");
|
||||||
|
const [clicks, setClicks] = useState(0);
|
||||||
|
const [showPreferences, setShowPreferences] = useState(true);
|
||||||
|
const color = theme.colors.foreground;
|
||||||
|
return <View>
|
||||||
|
<Text style={{ color }}>Plugin version ${version}</Text>
|
||||||
|
<TextInput accessibilityLabel="Plugin draft" value={draft} onChangeText={setDraft} style={{ color }} />
|
||||||
|
<Pressable accessibilityRole="button" onPress={() => setClicks(value => value + 1)}><Text style={{ color }}>{"Local clicks " + clicks}</Text></Pressable>
|
||||||
|
<Pressable accessibilityRole="button" onPress={() => setShowPreferences(value => !value)}><Text style={{ color }}>{showPreferences ? "Hide preferences" : "Show preferences"}</Text></Pressable>
|
||||||
|
{showPreferences ? <Preferences color={color} /> : null}
|
||||||
|
</View>;
|
||||||
|
}
|
||||||
|
export default function contribute(plugin) {
|
||||||
|
plugin.addSurface("main", Surface);
|
||||||
|
plugin.addSidebarItem({ id: "main", title: "Reconnect probe", icon: "PanelsTopLeft", surface: "main" });
|
||||||
|
return () => {};
|
||||||
|
}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function withRetainedPlugin(
|
||||||
|
page: Page,
|
||||||
|
run: (probe: Awaited<ReturnType<typeof createProbe>>) => Promise<void>,
|
||||||
|
) {
|
||||||
|
const probe = await createProbe(page);
|
||||||
|
try {
|
||||||
|
await run(probe);
|
||||||
|
} finally {
|
||||||
|
await probe.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function createProbe(page: Page) {
|
||||||
|
const example = await copyPluginExample("settings");
|
||||||
|
const peer = await connectDaemonClient<DaemonClient>({ clientIdPrefix: "plugin-reconnect" });
|
||||||
|
const previous = await peer.getDaemonConfig();
|
||||||
|
const gate = await installDaemonWebSocketGate(page);
|
||||||
|
const clientEntry = path.join(example.directory, "index.client.tsx");
|
||||||
|
let catalogCount = 0;
|
||||||
|
try {
|
||||||
|
await writeFile(
|
||||||
|
path.join(example.directory, "paseo-plugin.json"),
|
||||||
|
JSON.stringify({ id: PLUGIN_ID, requirements: pluginRequirements }),
|
||||||
|
);
|
||||||
|
await writeFile(clientEntry, retainedPluginSource("one"));
|
||||||
|
await peer.patchDaemonConfig({ pluginsEnabled: true });
|
||||||
|
await peer.installDirectoryPlugin(example.directory);
|
||||||
|
} catch (error) {
|
||||||
|
await peer.close();
|
||||||
|
await example.cleanup();
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
async open() {
|
||||||
|
await page.setViewportSize({ width: 1100, height: 800 });
|
||||||
|
await gotoAppShell(page);
|
||||||
|
await page.getByRole("button", { name: "Reconnect probe", exact: true }).click();
|
||||||
|
await expect(page.getByText("Stored title: Agent monitor", { exact: true })).toBeVisible();
|
||||||
|
},
|
||||||
|
async disconnect() {
|
||||||
|
catalogCount = gate.getClientRequestCount("plugin.catalog.get.request");
|
||||||
|
await gate.drop();
|
||||||
|
await gate.waitForBlockedConnection();
|
||||||
|
},
|
||||||
|
async reconnect() {
|
||||||
|
gate.restore();
|
||||||
|
await gate.waitForServerMessage("plugin.catalog.get.response", catalogCount + 1);
|
||||||
|
},
|
||||||
|
async changeStoredTitle(title: string) {
|
||||||
|
const rpc = settingsRpc("display");
|
||||||
|
const current = rpc.read.output.parse(
|
||||||
|
await peer.invokePluginRpc(PLUGIN_ID, rpc.read.name, {}),
|
||||||
|
);
|
||||||
|
if (current.status !== "ready") throw new Error("Expected ready settings");
|
||||||
|
const values = z
|
||||||
|
.object({ groupBy: z.string(), showMetadata: z.boolean(), title: z.string() })
|
||||||
|
.parse(current.values);
|
||||||
|
const result = await peer.invokePluginRpc(PLUGIN_ID, rpc.write.name, {
|
||||||
|
revision: current.revision,
|
||||||
|
values: { ...values, title },
|
||||||
|
});
|
||||||
|
expect(result).toMatchObject({ status: "saved", values: { title } });
|
||||||
|
},
|
||||||
|
async changeCode() {
|
||||||
|
await writeFile(clientEntry, retainedPluginSource("two"));
|
||||||
|
await peer.reloadPlugin(PLUGIN_ID);
|
||||||
|
},
|
||||||
|
async remove() {
|
||||||
|
await peer.removePlugin(PLUGIN_ID);
|
||||||
|
},
|
||||||
|
async close() {
|
||||||
|
gate.restore();
|
||||||
|
await peer.removePlugin(PLUGIN_ID).catch(() => undefined);
|
||||||
|
await peer.patchDaemonConfig({ pluginsEnabled: previous.config.pluginsEnabled ?? false });
|
||||||
|
await peer.close();
|
||||||
|
await example.cleanup();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function editRetainedDraft(page: Page, draft: string, clicks: number) {
|
||||||
|
await page.getByRole("textbox", { name: "Plugin draft", exact: true }).fill(draft);
|
||||||
|
await page.getByRole("button", { name: `Local clicks ${clicks}`, exact: true }).click();
|
||||||
|
await expectRetainedDraft(page, draft, clicks + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function expectRetainedDraft(page: Page, draft: string, clicks: number) {
|
||||||
|
await expect(page.getByRole("textbox", { name: "Plugin draft", exact: true })).toHaveValue(draft);
|
||||||
|
await expect(
|
||||||
|
page.getByRole("button", { name: `Local clicks ${clicks}`, exact: true }),
|
||||||
|
).toBeVisible();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function expectStoredPluginTitle(page: Page, title: string) {
|
||||||
|
await expect(page.getByText(`Stored title: ${title}`, { exact: true })).toBeVisible();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function hideRetainedPreferences(page: Page) {
|
||||||
|
await page.getByRole("button", { name: "Hide preferences", exact: true }).click();
|
||||||
|
await expect(page.getByText(/^Stored title:/)).toHaveCount(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function showRetainedPreferences(page: Page) {
|
||||||
|
await page.getByRole("button", { name: "Show preferences", exact: true }).click();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function expectChangedPlugin(page: Page) {
|
||||||
|
await expect(page.getByText("Plugin version two", { exact: true })).toBeVisible();
|
||||||
|
await expectRetainedDraft(page, "", 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function expectRemovedPlugin(page: Page) {
|
||||||
|
await expect(
|
||||||
|
page.getByText("This plugin surface is unavailable.", { exact: true }),
|
||||||
|
).toBeVisible();
|
||||||
|
await expect(page.getByRole("button", { name: "Reconnect probe", exact: true })).toHaveCount(0);
|
||||||
|
}
|
||||||
@@ -5,8 +5,64 @@ import { expect, type Page, type TestInfo } from "@playwright/test";
|
|||||||
import { copyPluginExample, pluginRequirements } from "./plugin-fixture";
|
import { copyPluginExample, pluginRequirements } from "./plugin-fixture";
|
||||||
import { connectNewWorkspaceDaemonClient } from "./new-workspace";
|
import { connectNewWorkspaceDaemonClient } from "./new-workspace";
|
||||||
import { openAgentRoute, seedMockAgentWorkspace, type MockAgentWorkspace } from "./mock-agent";
|
import { openAgentRoute, seedMockAgentWorkspace, type MockAgentWorkspace } from "./mock-agent";
|
||||||
|
import { installDaemonWebSocketGate } from "./daemon-websocket-gate";
|
||||||
|
import { expectReconnectingToastVisible } from "./workspace-ui";
|
||||||
|
|
||||||
const PLUGIN_ID = "timeline-transform-e2e";
|
const PLUGIN_ID = "timeline-transform-e2e";
|
||||||
|
|
||||||
|
/** Observe the app's real socket, including fresh sockets after a reload. */
|
||||||
|
export function trackPluginChatRecovery(page: Page) {
|
||||||
|
const messages: {
|
||||||
|
type: string;
|
||||||
|
payload?: { plugins?: { id: string; clientBundle?: string }[] };
|
||||||
|
}[] = [];
|
||||||
|
page.on("websocket", (socket) => {
|
||||||
|
const collect = ({ payload }: { payload: string | Buffer }) => {
|
||||||
|
if (typeof payload !== "string") return;
|
||||||
|
const frame = JSON.parse(payload);
|
||||||
|
if (frame.type === "session") messages.push(frame.message);
|
||||||
|
};
|
||||||
|
socket.on("framesent", collect);
|
||||||
|
socket.on("framereceived", collect);
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
reset() {
|
||||||
|
messages.length = 0;
|
||||||
|
},
|
||||||
|
async expectCatalogWithoutRetransmission() {
|
||||||
|
await expect
|
||||||
|
.poll(() =>
|
||||||
|
messages.some(
|
||||||
|
(message) =>
|
||||||
|
message.type === "plugin.catalog.get.response" &&
|
||||||
|
message.payload?.plugins?.some((plugin) => plugin.id === PLUGIN_ID),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.toBe(true);
|
||||||
|
const entry = messages
|
||||||
|
.find((message) => message.type === "plugin.catalog.get.response")
|
||||||
|
?.payload?.plugins?.find((plugin) => plugin.id === PLUGIN_ID);
|
||||||
|
expect(entry).toBeDefined();
|
||||||
|
expect(entry).not.toHaveProperty("clientBundle");
|
||||||
|
},
|
||||||
|
async expectRecoveredWithoutRetransmission() {
|
||||||
|
await this.expectCatalogWithoutRetransmission();
|
||||||
|
await expect
|
||||||
|
.poll(() => messages.some((message) => message.type === "fetch_agent_timeline_response"))
|
||||||
|
.toBe(true);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function reconnectPluginChat(
|
||||||
|
page: Page,
|
||||||
|
gate: Awaited<ReturnType<typeof installDaemonWebSocketGate>>,
|
||||||
|
) {
|
||||||
|
await gate.drop();
|
||||||
|
await gate.waitForBlockedConnection();
|
||||||
|
await expectReconnectingToastVisible(page);
|
||||||
|
gate.restore();
|
||||||
|
}
|
||||||
export const ASSISTANT_TEXT =
|
export const ASSISTANT_TEXT =
|
||||||
"Skill header\n\n# Instructions\n\nRead every paragraph and preserve the full message while this response is still streaming.";
|
"Skill header\n\n# Instructions\n\nRead every paragraph and preserve the full message while this response is still streaming.";
|
||||||
|
|
||||||
|
|||||||
@@ -28,6 +28,10 @@ interface SeedProjectDescriptor {
|
|||||||
* prefer those wrappers over reaching for this client directly.
|
* prefer those wrappers over reaching for this client directly.
|
||||||
*/
|
*/
|
||||||
export interface SeedDaemonClient {
|
export interface SeedDaemonClient {
|
||||||
|
patchDaemonConfig(
|
||||||
|
config: import("@getpaseo/protocol/messages").MutableDaemonConfigPatch,
|
||||||
|
): Promise<{ config: import("@getpaseo/protocol/messages").MutableDaemonConfig }>;
|
||||||
|
getDaemonConfig(): Promise<{ config: import("@getpaseo/protocol/messages").MutableDaemonConfig }>;
|
||||||
connect(): Promise<void>;
|
connect(): Promise<void>;
|
||||||
close(): Promise<void>;
|
close(): Promise<void>;
|
||||||
addProject(cwd: string): Promise<{
|
addProject(cwd: string): Promise<{
|
||||||
|
|||||||
@@ -560,3 +560,41 @@ export async function expectHostOnlineWithoutError(page: Page): Promise<void> {
|
|||||||
await expect(page.getByTestId("host-page-identity")).toContainText("Online");
|
await expect(page.getByTestId("host-page-identity")).toContainText("Online");
|
||||||
await expect(page.getByTestId("host-connection-error")).toHaveCount(0);
|
await expect(page.getByTestId("host-connection-error")).toHaveCount(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function restartRecoverySwitch(page: Page) {
|
||||||
|
return page.getByRole("switch", { name: "Resume agents after restart", exact: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
function restartRecoveryEditButton(page: Page) {
|
||||||
|
return page.getByRole("button", { name: "Edit prompt", exact: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function setRestartRecoveryEnabled(page: Page, enabled: boolean) {
|
||||||
|
const toggle = restartRecoverySwitch(page);
|
||||||
|
await toggle.click();
|
||||||
|
await expectRestartRecoveryEnabled(page, enabled);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The prompt is only editable while restart recovery is on.
|
||||||
|
export async function expectRestartRecoveryEnabled(page: Page, enabled: boolean) {
|
||||||
|
await expect(restartRecoverySwitch(page)).toBeChecked({ checked: enabled });
|
||||||
|
await expect(restartRecoveryEditButton(page)).toBeEnabled({ enabled });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function editRestartRecoveryPrompt(page: Page, prompt: string) {
|
||||||
|
await restartRecoveryEditButton(page).click();
|
||||||
|
const sheet = page.getByTestId("host-page-restart-recovery-sheet");
|
||||||
|
await sheet.getByRole("textbox", { name: "Resume prompt", exact: true }).fill(prompt);
|
||||||
|
await sheet.getByRole("button", { name: "Save", exact: true }).click();
|
||||||
|
await expect(sheet).toHaveCount(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function expectRestartRecoveryPrompt(page: Page, prompt: string) {
|
||||||
|
await restartRecoveryEditButton(page).click();
|
||||||
|
const sheet = page.getByTestId("host-page-restart-recovery-sheet");
|
||||||
|
await expect(sheet.getByRole("textbox", { name: "Resume prompt", exact: true })).toHaveValue(
|
||||||
|
prompt,
|
||||||
|
);
|
||||||
|
await sheet.getByRole("button", { name: "Cancel", exact: true }).click();
|
||||||
|
await expect(sheet).toHaveCount(0);
|
||||||
|
}
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ interface UsageReportsFixtureOptions {
|
|||||||
* app connects, so a reload can switch it.
|
* app connects, so a reload can switch it.
|
||||||
*/
|
*/
|
||||||
usageSupported?: boolean | (() => boolean);
|
usageSupported?: boolean | (() => boolean);
|
||||||
|
usageSettingSupported?: boolean;
|
||||||
/** Released hosts expose provider.usage.list with no source icons. */
|
/** Released hosts expose provider.usage.list with no source icons. */
|
||||||
providerUsageListOnly?: boolean;
|
providerUsageListOnly?: boolean;
|
||||||
/** The host daemon's port; defaults to the E2E daemon. */
|
/** The host daemon's port; defaults to the E2E daemon. */
|
||||||
@@ -63,6 +64,7 @@ function withUsageSupportFeature(
|
|||||||
message: WebSocketMessage,
|
message: WebSocketMessage,
|
||||||
enabled: boolean,
|
enabled: boolean,
|
||||||
providerUsageListOnly: boolean,
|
providerUsageListOnly: boolean,
|
||||||
|
usageSettingSupported: boolean,
|
||||||
): string | null {
|
): string | null {
|
||||||
const envelope = parseJson(message) as {
|
const envelope = parseJson(message) as {
|
||||||
type?: unknown;
|
type?: unknown;
|
||||||
@@ -86,6 +88,7 @@ function withUsageSupportFeature(
|
|||||||
...payload,
|
...payload,
|
||||||
features: {
|
features: {
|
||||||
...features,
|
...features,
|
||||||
|
usageSetting: usageSettingSupported ? true : undefined,
|
||||||
usageSources: enabled && !providerUsageListOnly,
|
usageSources: enabled && !providerUsageListOnly,
|
||||||
providerUsageList: enabled,
|
providerUsageList: enabled,
|
||||||
},
|
},
|
||||||
@@ -229,7 +232,12 @@ export async function installUsageReportsFixture(
|
|||||||
server.onMessage((message) => {
|
server.onMessage((message) => {
|
||||||
const serverInfo =
|
const serverInfo =
|
||||||
typeof message === "string"
|
typeof message === "string"
|
||||||
? withUsageSupportFeature(message, isUsageSupported(), providerUsageListOnly)
|
? withUsageSupportFeature(
|
||||||
|
message,
|
||||||
|
isUsageSupported(),
|
||||||
|
providerUsageListOnly,
|
||||||
|
options.usageSettingSupported ?? true,
|
||||||
|
)
|
||||||
: null;
|
: null;
|
||||||
ws.send(serverInfo ?? message);
|
ws.send(serverInfo ?? message);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -26,6 +26,22 @@ def stage_app_store_screenshots
|
|||||||
root
|
root
|
||||||
end
|
end
|
||||||
|
|
||||||
|
# Google Play only has en-US screenshots, and some F-Droid locales in
|
||||||
|
# ANDROID_METADATA are not Play languages (Play rejects "ja"). supply uploads
|
||||||
|
# every locale folder in one edit, so give it only the en-US images.
|
||||||
|
def stage_google_play_screenshots
|
||||||
|
root = Dir.mktmpdir("google-play-screenshots")
|
||||||
|
images = File.join(ANDROID_METADATA, "en-US/images")
|
||||||
|
%w[phoneScreenshots tenInchScreenshots].each do |kind|
|
||||||
|
target = File.join(root, "en-US/images", kind)
|
||||||
|
FileUtils.mkdir_p(target)
|
||||||
|
Dir.glob(File.join(images, kind, "*.png")).sort.each do |file|
|
||||||
|
FileUtils.cp(File.realpath(file), File.join(target, File.basename(file)))
|
||||||
|
end
|
||||||
|
end
|
||||||
|
root
|
||||||
|
end
|
||||||
|
|
||||||
platform :ios do
|
platform :ios do
|
||||||
desc "Submit the latest TestFlight build to App Store Review"
|
desc "Submit the latest TestFlight build to App Store Review"
|
||||||
lane :submit_review do
|
lane :submit_review do
|
||||||
@@ -132,7 +148,7 @@ platform :android do
|
|||||||
supply(
|
supply(
|
||||||
package_name: APP_IDENTIFIER,
|
package_name: APP_IDENTIFIER,
|
||||||
json_key: ENV.fetch("GOOGLE_PLAY_JSON_KEY"),
|
json_key: ENV.fetch("GOOGLE_PLAY_JSON_KEY"),
|
||||||
metadata_path: ANDROID_METADATA,
|
metadata_path: stage_google_play_screenshots,
|
||||||
version_code: version_code.empty? ? nil : version_code.to_i,
|
version_code: version_code.empty? ? nil : version_code.to_i,
|
||||||
skip_upload_apk: true,
|
skip_upload_apk: true,
|
||||||
skip_upload_aab: true,
|
skip_upload_aab: true,
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
|
import { Modal } from "@/components/ui/modal";
|
||||||
import equal from "fast-deep-equal";
|
import equal from "fast-deep-equal";
|
||||||
import { recordRenderProfileReasons } from "@/utils/render-profiler";
|
import { recordRenderProfileReasons } from "@/utils/render-profiler";
|
||||||
import {
|
import {
|
||||||
FlatList,
|
FlatList,
|
||||||
Modal,
|
|
||||||
Pressable,
|
Pressable,
|
||||||
Text,
|
Text,
|
||||||
View,
|
View,
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { Modal } from "@/components/ui/modal";
|
||||||
import { usePanelStore } from "@/stores/panel-store";
|
import { usePanelStore } from "@/stores/panel-store";
|
||||||
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
||||||
import { router } from "expo-router";
|
import { router } from "expo-router";
|
||||||
@@ -22,14 +23,7 @@ import {
|
|||||||
type ComponentType,
|
type ComponentType,
|
||||||
type RefObject,
|
type RefObject,
|
||||||
} from "react";
|
} from "react";
|
||||||
import {
|
import { Pressable, ScrollView, Text, View, type PressableStateCallbackType } from "react-native";
|
||||||
Modal,
|
|
||||||
Pressable,
|
|
||||||
ScrollView,
|
|
||||||
Text,
|
|
||||||
View,
|
|
||||||
type PressableStateCallbackType,
|
|
||||||
} from "react-native";
|
|
||||||
import {
|
import {
|
||||||
EditingTextInput as TextInput,
|
EditingTextInput as TextInput,
|
||||||
type EditingTextInputHandle,
|
type EditingTextInputHandle,
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
|
import { Modal } from "@/components/ui/modal";
|
||||||
import {
|
import {
|
||||||
View,
|
View,
|
||||||
Text,
|
Text,
|
||||||
Pressable,
|
Pressable,
|
||||||
Modal,
|
|
||||||
RefreshControl,
|
RefreshControl,
|
||||||
FlatList,
|
FlatList,
|
||||||
type ListRenderItem,
|
type ListRenderItem,
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
|
import { Modal } from "@/components/ui/modal";
|
||||||
import { type ReactNode, useCallback, useEffect, useMemo, useState } from "react";
|
import { type ReactNode, useCallback, useEffect, useMemo, useState } from "react";
|
||||||
import { Modal, Pressable, Text, View } from "react-native";
|
import { Pressable, Text, View } from "react-native";
|
||||||
import { GestureHandlerRootView } from "react-native-gesture-handler";
|
import { GestureHandlerRootView } from "react-native-gesture-handler";
|
||||||
import { StyleSheet } from "react-native-unistyles";
|
import { StyleSheet } from "react-native-unistyles";
|
||||||
import { SafeAreaProvider, useSafeAreaInsets } from "react-native-safe-area-context";
|
import { SafeAreaProvider, useSafeAreaInsets } from "react-native-safe-area-context";
|
||||||
|
|||||||
@@ -64,12 +64,7 @@ import { useCloseAgentListGesture } from "@/mobile-panels/gestures";
|
|||||||
import { MobilePanelOverlay } from "@/mobile-panels/presentation";
|
import { MobilePanelOverlay } from "@/mobile-panels/presentation";
|
||||||
import { buildSettingsAddHostRoute, buildSettingsRoute } from "@/utils/host-routes";
|
import { buildSettingsAddHostRoute, buildSettingsRoute } from "@/utils/host-routes";
|
||||||
import { openHostOverview } from "@/navigation/settings-navigation";
|
import { openHostOverview } from "@/navigation/settings-navigation";
|
||||||
import {
|
import { UsageSidebarItem, UsageSidebarRoot, useUsageSummary, useOpenSidebarUsage } from "@/usage";
|
||||||
UsageSidebarItem,
|
|
||||||
UsageSidebarRoot,
|
|
||||||
useHasUsageSummary,
|
|
||||||
useOpenSidebarUsage,
|
|
||||||
} from "@/usage";
|
|
||||||
import { SidebarAgentListSkeleton } from "./sidebar-agent-list-skeleton";
|
import { SidebarAgentListSkeleton } from "./sidebar-agent-list-skeleton";
|
||||||
import { SidebarCalloutSlot } from "./sidebar-callout-slot";
|
import { SidebarCalloutSlot } from "./sidebar-callout-slot";
|
||||||
import { SidebarWorkspaceList } from "./sidebar-workspace-list";
|
import { SidebarWorkspaceList } from "./sidebar-workspace-list";
|
||||||
@@ -480,10 +475,10 @@ function SidebarUsageIcon({ label }: { label: string }) {
|
|||||||
*/
|
*/
|
||||||
function SidebarFooterRows({ onBeforeNavigate }: { onBeforeNavigate?: () => void }) {
|
function SidebarFooterRows({ onBeforeNavigate }: { onBeforeNavigate?: () => void }) {
|
||||||
const { items } = useSidebarNavItems("footer");
|
const { items } = useSidebarNavItems("footer");
|
||||||
const hasUsageSummary = useHasUsageSummary();
|
const usageSummary = useUsageSummary();
|
||||||
const rowsRef = useRef<View | null>(null);
|
const rowsRef = useRef<View | null>(null);
|
||||||
const visibleItems = items.filter(
|
const visibleItems = items.filter(
|
||||||
(item) => item.visible && (item.kind === "plugin" || hasUsageSummary),
|
(item) => item.visible && (item.kind === "plugin" || usageSummary.length > 0),
|
||||||
);
|
);
|
||||||
if (visibleItems.length === 0) return null;
|
if (visibleItems.length === 0) return null;
|
||||||
return (
|
return (
|
||||||
@@ -499,7 +494,7 @@ function SidebarFooterRows({ onBeforeNavigate }: { onBeforeNavigate?: () => void
|
|||||||
onBeforeNavigate={onBeforeNavigate}
|
onBeforeNavigate={onBeforeNavigate}
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
<UsageSidebarItem key={item.key} />
|
<UsageSidebarItem key={item.key} sources={usageSummary} />
|
||||||
),
|
),
|
||||||
)}
|
)}
|
||||||
</View>
|
</View>
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
|
import { Modal } from "@/components/ui/modal";
|
||||||
import { useCallback, useEffect, useMemo, useRef } from "react";
|
import { useCallback, useEffect, useMemo, useRef } from "react";
|
||||||
import { Modal, View } from "react-native";
|
import { View } from "react-native";
|
||||||
import { X } from "lucide-react-native";
|
import { X } from "lucide-react-native";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { StyleSheet } from "react-native-unistyles";
|
import { StyleSheet } from "react-native-unistyles";
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
|
import { Modal } from "@/components/ui/modal";
|
||||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||||
import {
|
import {
|
||||||
Modal,
|
|
||||||
Pressable,
|
Pressable,
|
||||||
StyleSheet as RNStyleSheet,
|
StyleSheet as RNStyleSheet,
|
||||||
ScrollView,
|
ScrollView,
|
||||||
|
|||||||
@@ -49,7 +49,7 @@ export function ResizeHandle({
|
|||||||
const { theme } = useUnistyles();
|
const { theme } = useUnistyles();
|
||||||
const finePointer = useHasFinePointer();
|
const finePointer = useHasFinePointer();
|
||||||
const pointerStatesRef = useRef(new Map<number, PointerState>());
|
const pointerStatesRef = useRef(new Map<number, PointerState>());
|
||||||
const touchDragRef = useRef<ResizeHandleDrag | null>(null);
|
const touchStateRef = useRef<PointerState | null>(null);
|
||||||
const cursorBeforeDragRef = useRef<string | null>(null);
|
const cursorBeforeDragRef = useRef<string | null>(null);
|
||||||
const hoverTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
const hoverTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||||
const [active, setActive] = useState(false);
|
const [active, setActive] = useState(false);
|
||||||
@@ -151,23 +151,30 @@ export function ResizeHandle({
|
|||||||
const touchGesture = useMemo(() => {
|
const touchGesture = useMemo(() => {
|
||||||
const gesture = Gesture.Pan()
|
const gesture = Gesture.Pan()
|
||||||
.runOnJS(true)
|
.runOnJS(true)
|
||||||
.onBegin(() => setDragging(true))
|
.onBegin((event) => {
|
||||||
.onStart(() => {
|
setDragging(true);
|
||||||
touchDragRef.current = startResizeHandleDrag({
|
touchStateRef.current = {
|
||||||
sizes,
|
containerSize,
|
||||||
index,
|
pointerStart: direction === "horizontal" ? event.absoluteX : event.absoluteY,
|
||||||
preview: (nextSizes) => onPreviewResizeSplit(groupId, nextSizes),
|
drag: startResizeHandleDrag({
|
||||||
commit: (nextSizes) => onResizeSplit(groupId, nextSizes),
|
sizes,
|
||||||
});
|
index,
|
||||||
|
preview: (nextSizes) => onPreviewResizeSplit(groupId, nextSizes),
|
||||||
|
commit: (nextSizes) => onResizeSplit(groupId, nextSizes),
|
||||||
|
}),
|
||||||
|
};
|
||||||
})
|
})
|
||||||
.onUpdate((event) => {
|
.onUpdate((event) => {
|
||||||
if (containerSize <= 0) return;
|
const state = touchStateRef.current;
|
||||||
const translation = direction === "horizontal" ? event.translationX : event.translationY;
|
if (!state || state.containerSize <= 0) return;
|
||||||
touchDragRef.current?.move(translation / containerSize);
|
// Gesture Handler resets web translation when the pan activates. Measure from
|
||||||
|
// the initial press so the activation distance is included on every platform.
|
||||||
|
const pointerCurrent = direction === "horizontal" ? event.absoluteX : event.absoluteY;
|
||||||
|
state.drag.move((pointerCurrent - state.pointerStart) / state.containerSize);
|
||||||
})
|
})
|
||||||
.onEnd(() => touchDragRef.current?.finish())
|
.onEnd(() => touchStateRef.current?.drag.finish())
|
||||||
.onFinalize(() => {
|
.onFinalize(() => {
|
||||||
touchDragRef.current = null;
|
touchStateRef.current = null;
|
||||||
setDragging(false);
|
setDragging(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -48,6 +48,7 @@ import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-
|
|||||||
import {
|
import {
|
||||||
collectAllPanes,
|
collectAllPanes,
|
||||||
createDefaultLayout,
|
createDefaultLayout,
|
||||||
|
selectExplorerSidebarPaneId,
|
||||||
useWorkspaceLayoutStore,
|
useWorkspaceLayoutStore,
|
||||||
type SplitNode,
|
type SplitNode,
|
||||||
type SplitPane,
|
type SplitPane,
|
||||||
@@ -183,8 +184,8 @@ export function SplitContainer({
|
|||||||
} | null>(null);
|
} | null>(null);
|
||||||
const maximizedPaneId =
|
const maximizedPaneId =
|
||||||
maximizedPane?.workspaceKey === workspaceKey ? maximizedPane.paneId : null;
|
maximizedPane?.workspaceKey === workspaceKey ? maximizedPane.paneId : null;
|
||||||
const explorerSidebarPaneId = useWorkspaceLayoutStore(
|
const explorerSidebarPaneId = useWorkspaceLayoutStore((state) =>
|
||||||
(state) => state.explorerSidebarPaneIdByWorkspace[workspaceKey] ?? null,
|
selectExplorerSidebarPaneId(state, workspaceKey),
|
||||||
);
|
);
|
||||||
|
|
||||||
const mainRoot = useMemo(
|
const mainRoot = useMemo(
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { Modal } from "@/components/ui/modal";
|
||||||
import {
|
import {
|
||||||
useCallback,
|
useCallback,
|
||||||
useEffect,
|
useEffect,
|
||||||
@@ -12,7 +13,6 @@ import {
|
|||||||
View,
|
View,
|
||||||
Text,
|
Text,
|
||||||
Pressable,
|
Pressable,
|
||||||
Modal,
|
|
||||||
ScrollView,
|
ScrollView,
|
||||||
Platform,
|
Platform,
|
||||||
StatusBar,
|
StatusBar,
|
||||||
|
|||||||
@@ -0,0 +1,124 @@
|
|||||||
|
import React, { act, useEffect, useState, type ReactNode } from "react";
|
||||||
|
import { createRoot, type Root } from "react-dom/client";
|
||||||
|
import { Text, View } from "react-native";
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
import { page } from "vitest/browser";
|
||||||
|
import { MenuRoot, MenuSurface, MenuTrigger, type Size } from "./index";
|
||||||
|
|
||||||
|
// App sources compile against the classic JSX runtime, which expects React on the global.
|
||||||
|
beforeEach(() => vi.stubGlobal("React", React));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A real browser, because the regression lives in Reanimated's web entering path: it snapshots
|
||||||
|
* the surface's rect when a custom keyframe ends and writes that rect back as inline
|
||||||
|
* top/left/width/height when it cleans the keyframe up, 750ms after the animation starts.
|
||||||
|
* Anything that moved or resized the surface in between is undone by that write.
|
||||||
|
*/
|
||||||
|
|
||||||
|
interface Mounted {
|
||||||
|
root: Root;
|
||||||
|
container: HTMLDivElement;
|
||||||
|
}
|
||||||
|
|
||||||
|
const mounted: Mounted[] = [];
|
||||||
|
|
||||||
|
function mount(node: ReactNode): void {
|
||||||
|
const container = document.createElement("div");
|
||||||
|
document.body.appendChild(container);
|
||||||
|
const root = createRoot(container);
|
||||||
|
act(() => root.render(node));
|
||||||
|
mounted.push({ root, container });
|
||||||
|
}
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
for (const entry of mounted.splice(0)) {
|
||||||
|
act(() => entry.root.unmount());
|
||||||
|
entry.container.remove();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const OFFSET = 12;
|
||||||
|
const PILL_POSITION = { position: "absolute", top: 700, left: 40 } as const;
|
||||||
|
const SHORT: Size = { width: 200, height: 40 };
|
||||||
|
const TALL: Size = { width: 200, height: 240 };
|
||||||
|
const WIDE: Size = { width: 480, height: 40 };
|
||||||
|
/** Inside the window between the entering animation ending and Reanimated's cleanup. */
|
||||||
|
const GROWS_BEFORE_CLEANUP_MS = 400;
|
||||||
|
/** Past Reanimated's cleanup, where the surface used to keep a fixed height. */
|
||||||
|
const GROWS_AFTER_CLEANUP_MS = 1_000;
|
||||||
|
/** Long enough after the content grew for anything that would write to the surface to land. */
|
||||||
|
const SETTLE_MS = 1_200;
|
||||||
|
|
||||||
|
/** Plain timers, not `act`: an async `act` holds every update until it resolves. */
|
||||||
|
function wait(ms: number): Promise<void> {
|
||||||
|
return new Promise<void>((resolve) => setTimeout(resolve, ms));
|
||||||
|
}
|
||||||
|
|
||||||
|
function element(testID: string): HTMLElement {
|
||||||
|
const found = document.querySelector(`[data-testid="${testID}"]`);
|
||||||
|
if (!(found instanceof HTMLElement)) throw new Error(`${testID} did not render`);
|
||||||
|
return found;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Stands in for a popover whose data lands after it opened, like a plugin's first RPC. */
|
||||||
|
function GrowsAfterOpen({ afterMs, from, to }: { afterMs: number; from: Size; to: Size }) {
|
||||||
|
const [grown, setGrown] = useState(false);
|
||||||
|
useEffect(() => {
|
||||||
|
const timer = setTimeout(() => setGrown(true), afterMs);
|
||||||
|
return () => clearTimeout(timer);
|
||||||
|
}, [afterMs]);
|
||||||
|
return <View testID="body" style={grown ? to : from} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function mountMenuAbovePill(body: ReactNode): void {
|
||||||
|
mount(
|
||||||
|
<View style={PILL_POSITION}>
|
||||||
|
<MenuRoot>
|
||||||
|
<MenuTrigger testID="pill" accessibilityLabel="Open panel">
|
||||||
|
<Text>Open panel</Text>
|
||||||
|
</MenuTrigger>
|
||||||
|
<MenuSurface
|
||||||
|
side="top"
|
||||||
|
align="start"
|
||||||
|
offset={OFFSET}
|
||||||
|
minWidth={280}
|
||||||
|
maxWidth={620}
|
||||||
|
testID="panel"
|
||||||
|
>
|
||||||
|
{body}
|
||||||
|
</MenuSurface>
|
||||||
|
</MenuRoot>
|
||||||
|
</View>,
|
||||||
|
);
|
||||||
|
act(() => element("pill").click());
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("anchored menu surface on web", () => {
|
||||||
|
beforeEach(async () => {
|
||||||
|
await page.viewport(1280, 900);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([GROWS_BEFORE_CLEANUP_MS, GROWS_AFTER_CLEANUP_MS])(
|
||||||
|
"stays on its anchor when its content grows %ims after opening",
|
||||||
|
async (afterMs) => {
|
||||||
|
mountMenuAbovePill(<GrowsAfterOpen afterMs={afterMs} from={SHORT} to={TALL} />);
|
||||||
|
|
||||||
|
await wait(afterMs + SETTLE_MS);
|
||||||
|
|
||||||
|
const pill = element("pill").getBoundingClientRect();
|
||||||
|
const panel = element("panel").getBoundingClientRect();
|
||||||
|
expect(panel.height).toBeGreaterThan(240);
|
||||||
|
expect(panel.bottom).toBeLessThanOrEqual(pill.top);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
it("widens when its content widens after the entering animation", async () => {
|
||||||
|
mountMenuAbovePill(<GrowsAfterOpen afterMs={GROWS_BEFORE_CLEANUP_MS} from={SHORT} to={WIDE} />);
|
||||||
|
|
||||||
|
await wait(GROWS_BEFORE_CLEANUP_MS + SETTLE_MS);
|
||||||
|
|
||||||
|
const body = element("body").getBoundingClientRect();
|
||||||
|
const panel = element("panel").getBoundingClientRect();
|
||||||
|
expect(panel.width).toBeGreaterThanOrEqual(body.width);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,7 +1,9 @@
|
|||||||
|
import { Modal } from "@/components/ui/modal";
|
||||||
import {
|
import {
|
||||||
useCallback,
|
useCallback,
|
||||||
useEffect,
|
useEffect,
|
||||||
useId,
|
useId,
|
||||||
|
useLayoutEffect,
|
||||||
useMemo,
|
useMemo,
|
||||||
useState,
|
useState,
|
||||||
type ReactElement,
|
type ReactElement,
|
||||||
@@ -11,7 +13,6 @@ import { createPortal } from "react-dom";
|
|||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import {
|
import {
|
||||||
Dimensions,
|
Dimensions,
|
||||||
Modal,
|
|
||||||
Platform,
|
Platform,
|
||||||
Pressable,
|
Pressable,
|
||||||
View,
|
View,
|
||||||
@@ -47,56 +48,41 @@ const contentEntering = new Keyframe({
|
|||||||
100: { opacity: 1, transform: [{ scale: 1 }] },
|
100: { opacity: 1, transform: [{ scale: 1 }] },
|
||||||
}).duration(CONTENT_ENTERING_DURATION_MS);
|
}).duration(CONTENT_ENTERING_DURATION_MS);
|
||||||
|
|
||||||
|
/** `contentEntering` for the browser's own animation engine. Both default to linear easing. */
|
||||||
|
const WEB_CONTENT_ENTERING_KEYFRAMES: PropertyIndexedKeyframes = {
|
||||||
|
opacity: [0, 1],
|
||||||
|
transform: ["scale(0.97)", "scale(1)"],
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Web plays the same keyframes itself; see `useWebContentEntering`. */
|
||||||
|
const nativeContentEntering = isWeb ? undefined : contentEntering;
|
||||||
|
|
||||||
const contentExiting = new Keyframe({
|
const contentExiting = new Keyframe({
|
||||||
0: { opacity: 1, transform: [{ scale: 1 }] },
|
0: { opacity: 1, transform: [{ scale: 1 }] },
|
||||||
100: { opacity: 0, transform: [{ scale: 0.97 }] },
|
100: { opacity: 0, transform: [{ scale: 0.97 }] },
|
||||||
}).duration(100);
|
}).duration(100);
|
||||||
|
|
||||||
function releaseFixedMenuHeight(surfaceNativeID: string): void {
|
|
||||||
if (!isWeb) return;
|
|
||||||
document.getElementById(surfaceNativeID)?.style.removeProperty("height");
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Reanimated's web entering animation leaves an inline height snapshot on the measured surface.
|
* On web the surface enters through the Web Animations API rather than Reanimated. Reanimated's
|
||||||
* Once the menu is open, height must return to content-sized so rows can grow in place — and so
|
* web path snapshots an element's rect when a custom keyframe ends and, when it cleans the keyframe
|
||||||
* a submenu page taller than the page it replaced is not clipped to the old height.
|
* up 750ms after the start, writes that rect back as inline top/left/width/height. A surface that
|
||||||
*
|
* moved or resized in between — content that grew once its data arrived — snapped back to the old
|
||||||
* `revision` is what makes that second case work: bump it whenever the rendered content changes
|
* rect and stayed there, clipped or hanging past its anchor. A Web Animation leaves no inline style.
|
||||||
* identity (a page push, for instance) and the snapshot is released again.
|
|
||||||
*/
|
*/
|
||||||
function useReleaseFixedMenuHeight({
|
function useWebContentEntering({
|
||||||
contentSize,
|
placed,
|
||||||
enabled,
|
|
||||||
surfaceNativeID,
|
surfaceNativeID,
|
||||||
revision,
|
|
||||||
}: {
|
}: {
|
||||||
contentSize: Size | null;
|
placed: boolean;
|
||||||
enabled: boolean;
|
|
||||||
surfaceNativeID: string;
|
surfaceNativeID: string;
|
||||||
revision?: string | number;
|
|
||||||
}): void {
|
}): void {
|
||||||
useEffect(() => {
|
useLayoutEffect(() => {
|
||||||
if (!enabled) return undefined;
|
if (!isWeb || !placed || typeof document === "undefined") return undefined;
|
||||||
|
const animation = document
|
||||||
const release = () => {
|
.getElementById(surfaceNativeID)
|
||||||
releaseFixedMenuHeight(surfaceNativeID);
|
?.animate(WEB_CONTENT_ENTERING_KEYFRAMES, CONTENT_ENTERING_DURATION_MS);
|
||||||
if (typeof requestAnimationFrame === "function") {
|
return () => animation?.cancel();
|
||||||
requestAnimationFrame(() => releaseFixedMenuHeight(surfaceNativeID));
|
}, [placed, surfaceNativeID]);
|
||||||
}
|
|
||||||
};
|
|
||||||
const timers: ReturnType<typeof setTimeout>[] = [
|
|
||||||
setTimeout(release, CONTENT_ENTERING_DURATION_MS),
|
|
||||||
];
|
|
||||||
|
|
||||||
if (contentSize) {
|
|
||||||
timers.push(setTimeout(release, 0));
|
|
||||||
}
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
for (const timer of timers) clearTimeout(timer);
|
|
||||||
};
|
|
||||||
}, [contentSize, enabled, surfaceNativeID, revision]);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -224,8 +210,6 @@ export interface AnchoredSurfaceProps {
|
|||||||
fullWidth?: boolean;
|
fullWidth?: boolean;
|
||||||
horizontalPadding?: number;
|
horizontalPadding?: number;
|
||||||
scrollable?: boolean;
|
scrollable?: boolean;
|
||||||
/** Bump when the rendered content changes identity, so the height snapshot is released. */
|
|
||||||
revision?: string | number;
|
|
||||||
/** A submenu sits inside its parent's overlay and must not paint a second backdrop. */
|
/** A submenu sits inside its parent's overlay and must not paint a second backdrop. */
|
||||||
backdrop?: boolean;
|
backdrop?: boolean;
|
||||||
/**
|
/**
|
||||||
@@ -259,7 +243,6 @@ export function AnchoredSurface({
|
|||||||
fullWidth = false,
|
fullWidth = false,
|
||||||
horizontalPadding = 16,
|
horizontalPadding = 16,
|
||||||
scrollable = false,
|
scrollable = false,
|
||||||
revision,
|
|
||||||
backdrop = true,
|
backdrop = true,
|
||||||
onPointerEnter,
|
onPointerEnter,
|
||||||
onPointerLeave,
|
onPointerLeave,
|
||||||
@@ -269,33 +252,25 @@ export function AnchoredSurface({
|
|||||||
}: AnchoredSurfaceProps): ReactElement | null {
|
}: AnchoredSurfaceProps): ReactElement | null {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const surfaceNativeID = useId();
|
const surfaceNativeID = useId();
|
||||||
const { position, actualPlacement, contentSize, visibleContentSize, onContentLayout } =
|
const { position, actualPlacement, visibleContentSize, onContentLayout } = useAnchoredPosition({
|
||||||
useAnchoredPosition({
|
open,
|
||||||
open,
|
anchorRect,
|
||||||
anchorRect,
|
anchorRef,
|
||||||
anchorRef,
|
side,
|
||||||
side,
|
align,
|
||||||
align,
|
offset,
|
||||||
offset,
|
scrollable,
|
||||||
scrollable,
|
maxHeight,
|
||||||
maxHeight,
|
|
||||||
});
|
|
||||||
|
|
||||||
useReleaseFixedMenuHeight({
|
|
||||||
contentSize,
|
|
||||||
enabled: open,
|
|
||||||
surfaceNativeID,
|
|
||||||
revision,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// The surface is placed once both measurements land. Until then it sits off-screen so it can
|
// The surface is placed once both measurements land. Until then it sits off-screen so it can
|
||||||
// be measured, and it must not animate: Reanimated's web entering path snapshots the element's
|
// be measured, and it must not animate: an entering animation that ran there would be over
|
||||||
// rect when the animation ends and writes that rect back as inline top/left when it cleans the
|
// before anyone saw the menu. Remounting on placement starts the native animation from the
|
||||||
// keyframe up 750ms later. If the animation ends before placement, the snapshot is the
|
// final position; web starts its own animation on placement.
|
||||||
// off-screen rect and the menu jumps back off-screen. Remounting on placement starts the
|
|
||||||
// animation from the final position.
|
|
||||||
const placed = position !== null;
|
const placed = position !== null;
|
||||||
|
|
||||||
|
useWebContentEntering({ placed, surfaceNativeID });
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!isWeb || !open || !placed || typeof document === "undefined") return undefined;
|
if (!isWeb || !open || !placed || typeof document === "undefined") return undefined;
|
||||||
const frame = requestAnimationFrame(() => {
|
const frame = requestAnimationFrame(() => {
|
||||||
@@ -383,7 +358,7 @@ export function AnchoredSurface({
|
|||||||
dataSet={surfaceDataSet}
|
dataSet={surfaceDataSet}
|
||||||
style={styles.content}
|
style={styles.content}
|
||||||
frameStyle={frameStyle}
|
frameStyle={frameStyle}
|
||||||
entering={placed ? contentEntering : undefined}
|
entering={placed ? nativeContentEntering : undefined}
|
||||||
exiting={
|
exiting={
|
||||||
!placed || isWeb || !onExited
|
!placed || isWeb || !onExited
|
||||||
? undefined
|
? undefined
|
||||||
|
|||||||
@@ -344,7 +344,6 @@ function MenuFlyout({
|
|||||||
maxHeight={maxHeight}
|
maxHeight={maxHeight}
|
||||||
scrollable={scrollable}
|
scrollable={scrollable}
|
||||||
backdrop={false}
|
backdrop={false}
|
||||||
revision={page.id}
|
|
||||||
onPointerEnter={cancelHoverClose}
|
onPointerEnter={cancelHoverClose}
|
||||||
onPointerLeave={handleHoverOut}
|
onPointerLeave={handleHoverOut}
|
||||||
testID={testID}
|
testID={testID}
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import { Modal as NativeModal, type ModalProps } from "react-native";
|
||||||
|
|
||||||
|
// React Native defaults iPhone modals to portrait even when the app supports rotation.
|
||||||
|
const orientations: NonNullable<ModalProps["supportedOrientations"]> = [
|
||||||
|
"portrait",
|
||||||
|
"portrait-upside-down",
|
||||||
|
"landscape-left",
|
||||||
|
"landscape-right",
|
||||||
|
];
|
||||||
|
|
||||||
|
export function Modal(props: ModalProps) {
|
||||||
|
return <NativeModal supportedOrientations={orientations} {...props} />;
|
||||||
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { Modal } from "@/components/ui/modal";
|
||||||
import {
|
import {
|
||||||
Children,
|
Children,
|
||||||
cloneElement,
|
cloneElement,
|
||||||
@@ -16,7 +17,6 @@ import { createPortal } from "react-dom";
|
|||||||
import {
|
import {
|
||||||
Dimensions,
|
Dimensions,
|
||||||
Platform,
|
Platform,
|
||||||
Modal,
|
|
||||||
Pressable,
|
Pressable,
|
||||||
View,
|
View,
|
||||||
type PressableProps,
|
type PressableProps,
|
||||||
|
|||||||
@@ -455,10 +455,6 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
|
|||||||
reportError: (error) => {
|
reportError: (error) => {
|
||||||
console.warn("[Session] viewed timeline synchronization failed", { serverId, error });
|
console.warn("[Session] viewed timeline synchronization failed", { serverId, error });
|
||||||
},
|
},
|
||||||
schedule: (task, delayMs) => {
|
|
||||||
const timeout = setTimeout(task, delayMs);
|
|
||||||
return () => clearTimeout(timeout);
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
viewedTimelineSyncRef.current = sync;
|
viewedTimelineSyncRef.current = sync;
|
||||||
setViewedTimelineSync(serverId, sync);
|
setViewedTimelineSync(serverId, sync);
|
||||||
|
|||||||
@@ -292,7 +292,10 @@ const CATALOG_DATA = [
|
|||||||
version: "0.6.13",
|
version: "0.6.13",
|
||||||
iconId: "minimax-code",
|
iconId: "minimax-code",
|
||||||
installLink: "https://agent.minimax.io",
|
installLink: "https://agent.minimax.io",
|
||||||
command: ["npx", "-y", "@minimax-ai/code@0.6.13", "acp"],
|
// `-p <pkg>` names the package and `mcode` names its binary. Without the
|
||||||
|
// explicit binary, npx resolves the executable from the unscoped package
|
||||||
|
// name (`code`), which this package does not publish.
|
||||||
|
command: ["npx", "-y", "-p", "@minimax-ai/code@0.6.13", "mcode", "acp"],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: "minion-code",
|
id: "minion-code",
|
||||||
|
|||||||
@@ -62,7 +62,9 @@ describe("ACP provider catalog", () => {
|
|||||||
expect(findProvider("minimax-code")).toMatchObject({
|
expect(findProvider("minimax-code")).toMatchObject({
|
||||||
title: "MiniMax Code",
|
title: "MiniMax Code",
|
||||||
version: "0.6.13",
|
version: "0.6.13",
|
||||||
command: ["npx", "-y", "@minimax-ai/code@0.6.13", "acp"],
|
// The package publishes `mcode`, not `code`, so npx needs the package and
|
||||||
|
// the binary named separately.
|
||||||
|
command: ["npx", "-y", "-p", "@minimax-ai/code@0.6.13", "mcode", "acp"],
|
||||||
});
|
});
|
||||||
expect(findProvider("minimax-code").iconSvg).toContain("<svg");
|
expect(findProvider("minimax-code").iconSvg).toContain("<svg");
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -422,6 +422,23 @@ describe("deriveAgentScreenViewState", () => {
|
|||||||
expect(result.memory.lastReadyAgent).toBeNull();
|
expect(result.memory.lastReadyAgent).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it.each(["error", "retrying"] as const)("shows archived history sync %s", (status) => {
|
||||||
|
const result = deriveAgentScreenViewState({
|
||||||
|
input: {
|
||||||
|
...createBaseInput(),
|
||||||
|
agent: createAgent("agent-1"),
|
||||||
|
isArchived: true,
|
||||||
|
hasHydratedHistoryBefore: true,
|
||||||
|
visibilityCatchUpStatus: status,
|
||||||
|
},
|
||||||
|
memory: createBaseMemory(),
|
||||||
|
});
|
||||||
|
expect(expectReadyState(result.state).sync).toEqual({
|
||||||
|
status: "sync_error",
|
||||||
|
isRetrying: status === "retrying",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
it("renders an archived agent before provider history is initialized", () => {
|
it("renders an archived agent before provider history is initialized", () => {
|
||||||
const result = deriveAgentScreenViewState({
|
const result = deriveAgentScreenViewState({
|
||||||
input: {
|
input: {
|
||||||
|
|||||||
@@ -175,10 +175,14 @@ function resolveAgentScreenSync(args: {
|
|||||||
hadInitialSyncFailure: boolean;
|
hadInitialSyncFailure: boolean;
|
||||||
}): AgentScreenReadySyncState {
|
}): AgentScreenReadySyncState {
|
||||||
const { input, hadInitialSyncFailure } = args;
|
const { input, hadInitialSyncFailure } = args;
|
||||||
if (input.isArchived) {
|
if (
|
||||||
|
input.isArchived &&
|
||||||
|
input.visibilityCatchUpStatus !== "error" &&
|
||||||
|
input.visibilityCatchUpStatus !== "retrying"
|
||||||
|
) {
|
||||||
return { status: "idle" };
|
return { status: "idle" };
|
||||||
}
|
}
|
||||||
if (!input.isConnected) {
|
if (!input.isConnected && !input.isArchived) {
|
||||||
return { status: "reconnecting" };
|
return { status: "reconnecting" };
|
||||||
}
|
}
|
||||||
if (input.missingAgentState.kind === "error") {
|
if (input.missingAgentState.kind === "error") {
|
||||||
|
|||||||
@@ -1,13 +1,7 @@
|
|||||||
|
import { Modal } from "@/components/ui/modal";
|
||||||
import { usePanelStore } from "@/stores/panel-store";
|
import { usePanelStore } from "@/stores/panel-store";
|
||||||
import { createElement, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
import { createElement, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||||
import {
|
import { Pressable, ScrollView, Text, View, type PressableStateCallbackType } from "react-native";
|
||||||
Modal,
|
|
||||||
Pressable,
|
|
||||||
ScrollView,
|
|
||||||
Text,
|
|
||||||
View,
|
|
||||||
type PressableStateCallbackType,
|
|
||||||
} from "react-native";
|
|
||||||
import {
|
import {
|
||||||
EditingTextInput as TextInput,
|
EditingTextInput as TextInput,
|
||||||
type EditingTextInputHandle,
|
type EditingTextInputHandle,
|
||||||
|
|||||||
@@ -2092,6 +2092,11 @@ export const ar: TranslationResources = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
providerUsage: {
|
providerUsage: {
|
||||||
|
checkUsage: "التحقق من الاستخدام",
|
||||||
|
checkUsageHint: "ينطبق على {{host}} على جميع الأجهزة",
|
||||||
|
off: "التحقق من الاستخدام متوقف على {{host}}.",
|
||||||
|
turnOn: "تشغيل",
|
||||||
|
|
||||||
options: "الإعدادات",
|
options: "الإعدادات",
|
||||||
refreshFailed: "تعذّر تحديث الاستخدام",
|
refreshFailed: "تعذّر تحديث الاستخدام",
|
||||||
noHosts: "لا توجد مضيفات متصلة",
|
noHosts: "لا توجد مضيفات متصلة",
|
||||||
@@ -2157,6 +2162,7 @@ export const ar: TranslationResources = {
|
|||||||
minutes_few: "{{value}} دقائق",
|
minutes_few: "{{value}} دقائق",
|
||||||
minutes_many: "{{value}} دقيقة",
|
minutes_many: "{{value}} دقيقة",
|
||||||
minutes_other: "{{value}} دقيقة",
|
minutes_other: "{{value}} دقيقة",
|
||||||
|
pair: "{{first}} و{{second}}",
|
||||||
},
|
},
|
||||||
timing: {
|
timing: {
|
||||||
lastUpdated: "آخر تحديث {{relativeTime}}",
|
lastUpdated: "آخر تحديث {{relativeTime}}",
|
||||||
@@ -2164,6 +2170,8 @@ export const ar: TranslationResources = {
|
|||||||
resetTimePassed: "مضى وقت إعادة التعيين",
|
resetTimePassed: "مضى وقت إعادة التعيين",
|
||||||
resettingNow: "تتم إعادة التعيين الآن",
|
resettingNow: "تتم إعادة التعيين الآن",
|
||||||
resetsIn: "تتم إعادة التعيين خلال {{duration}}",
|
resetsIn: "تتم إعادة التعيين خلال {{duration}}",
|
||||||
|
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||||
|
resetsAtDate: "{{date}}، {{time}}",
|
||||||
runsOutNow: "ينفد الآن",
|
runsOutNow: "ينفد الآن",
|
||||||
runsOutIn: "ينفد خلال {{duration}}",
|
runsOutIn: "ينفد خلال {{duration}}",
|
||||||
justNow: "الآن",
|
justNow: "الآن",
|
||||||
@@ -2778,6 +2786,14 @@ export const ar: TranslationResources = {
|
|||||||
},
|
},
|
||||||
agents: {
|
agents: {
|
||||||
unavailable: "Connect to this host to manage agents",
|
unavailable: "Connect to this host to manage agents",
|
||||||
|
resumeOnStartup: {
|
||||||
|
title: "استئناف الوكلاء بعد إعادة التشغيل",
|
||||||
|
info: "إعادة فتح الوكلاء الذين كانوا يعملون عند توقف المضيف وإرسال طلب الاستئناف. ينطبق ذلك بعد إعادة التشغيل العادية والتعطّل.",
|
||||||
|
hint: "متابعة العمل المنقطع تلقائيًا.",
|
||||||
|
prompt: "طلب الاستئناف",
|
||||||
|
edit: "تحرير",
|
||||||
|
editAccessibilityLabel: "تعديل الطلب",
|
||||||
|
},
|
||||||
idleRuntimeCleanup: {
|
idleRuntimeCleanup: {
|
||||||
title: "تحرير الوكلاء الخاملين",
|
title: "تحرير الوكلاء الخاملين",
|
||||||
hint: "تحرير الذاكرة بعد ساعة من الخمول.",
|
hint: "تحرير الذاكرة بعد ساعة من الخمول.",
|
||||||
@@ -2873,6 +2889,10 @@ export const ar: TranslationResources = {
|
|||||||
requestFailedTitle: "خطأ",
|
requestFailedTitle: "خطأ",
|
||||||
requestFailedMessage:
|
requestFailedMessage:
|
||||||
"فشل في إرسال طلب إعادة التشغيل. يقوم Paseo بإعادة الاتصال تلقائيًا - حاول مرة أخرى بمجرد ظهور المضيف على أنه متصل بالإنترنت.",
|
"فشل في إرسال طلب إعادة التشغيل. يقوم Paseo بإعادة الاتصال تلقائيًا - حاول مرة أخرى بمجرد ظهور المضيف على أنه متصل بالإنترنت.",
|
||||||
|
closeTerminals: "إعادة التشغيل وإغلاق الطرفيات",
|
||||||
|
closeTerminalsHint: "يعيد التشغيل ويغلق أيضًا كل الطرفيات المفتوحة على هذا المضيف.",
|
||||||
|
closeTerminalsConfirmMessage:
|
||||||
|
"سيُعاد تشغيل الخدمة وتُغلق كل طرفياتها، مما ينهي البرامج التي تعمل فيها. سيعيد التطبيق الاتصال تلقائيًا.",
|
||||||
dialogFailedMessage: "غير قادر على فتح مربع حوار تأكيد إعادة التشغيل.",
|
dialogFailedMessage: "غير قادر على فتح مربع حوار تأكيد إعادة التشغيل.",
|
||||||
},
|
},
|
||||||
update: {
|
update: {
|
||||||
|
|||||||
@@ -2117,6 +2117,11 @@ export const en = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
providerUsage: {
|
providerUsage: {
|
||||||
|
checkUsage: "Check usage",
|
||||||
|
checkUsageHint: "Applies to {{host}} on every device",
|
||||||
|
off: "Usage is off on {{host}}.",
|
||||||
|
turnOn: "Turn on",
|
||||||
|
|
||||||
options: "Settings",
|
options: "Settings",
|
||||||
refreshFailed: "Unable to refresh usage",
|
refreshFailed: "Unable to refresh usage",
|
||||||
noHosts: "No connected hosts",
|
noHosts: "No connected hosts",
|
||||||
@@ -2164,15 +2169,18 @@ export const en = {
|
|||||||
days: "{{value}}d",
|
days: "{{value}}d",
|
||||||
hours: "{{value}}h",
|
hours: "{{value}}h",
|
||||||
minutes: "{{value}}m",
|
minutes: "{{value}}m",
|
||||||
|
pair: "{{first}} {{second}}",
|
||||||
},
|
},
|
||||||
timing: {
|
timing: {
|
||||||
lastUpdated: "Last updated {{relativeTime}}",
|
lastUpdated: "Last updated {{relativeTime}}",
|
||||||
noSuccessfulUpdate: "No successful update",
|
noSuccessfulUpdate: "No successful update",
|
||||||
resetTimePassed: "Reset time passed",
|
resetTimePassed: "Reset time passed",
|
||||||
resettingNow: "resetting now",
|
resettingNow: "resetting now",
|
||||||
resetsIn: "resets {{duration}}",
|
resetsIn: "resets in {{duration}}",
|
||||||
|
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||||
|
resetsAtDate: "{{date}}, {{time}}",
|
||||||
runsOutNow: "runs out now",
|
runsOutNow: "runs out now",
|
||||||
runsOutIn: "runs out {{duration}}",
|
runsOutIn: "runs out in {{duration}}",
|
||||||
justNow: "just now",
|
justNow: "just now",
|
||||||
daysAgo: "{{value}}d ago",
|
daysAgo: "{{value}}d ago",
|
||||||
hoursAgo: "{{value}}h ago",
|
hoursAgo: "{{value}}h ago",
|
||||||
@@ -2870,6 +2878,14 @@ export const en = {
|
|||||||
},
|
},
|
||||||
agents: {
|
agents: {
|
||||||
unavailable: "Connect to this host to manage agents",
|
unavailable: "Connect to this host to manage agents",
|
||||||
|
resumeOnStartup: {
|
||||||
|
title: "Resume agents after restart",
|
||||||
|
info: "Reopen agents that were working when the host stopped and send the resume prompt. Applies after graceful restarts and crashes.",
|
||||||
|
hint: "Continue interrupted work automatically.",
|
||||||
|
prompt: "Resume prompt",
|
||||||
|
edit: "Edit",
|
||||||
|
editAccessibilityLabel: "Edit prompt",
|
||||||
|
},
|
||||||
idleRuntimeCleanup: {
|
idleRuntimeCleanup: {
|
||||||
title: "Release idle agents",
|
title: "Release idle agents",
|
||||||
hint: "Free up memory after an hour of inactivity.",
|
hint: "Free up memory after an hour of inactivity.",
|
||||||
@@ -2966,6 +2982,10 @@ export const en = {
|
|||||||
requestFailedTitle: "Error",
|
requestFailedTitle: "Error",
|
||||||
requestFailedMessage:
|
requestFailedMessage:
|
||||||
"Failed to send the restart request. Paseo reconnects automatically-try again once the host shows as online.",
|
"Failed to send the restart request. Paseo reconnects automatically-try again once the host shows as online.",
|
||||||
|
closeTerminals: "Restart and close terminals",
|
||||||
|
closeTerminalsHint: "Restart and also close every terminal running on this host.",
|
||||||
|
closeTerminalsConfirmMessage:
|
||||||
|
"This will restart the daemon and close every terminal on it, ending the programs running in them. The app will reconnect automatically.",
|
||||||
dialogFailedMessage: "Unable to open the restart confirmation dialog.",
|
dialogFailedMessage: "Unable to open the restart confirmation dialog.",
|
||||||
},
|
},
|
||||||
update: {
|
update: {
|
||||||
|
|||||||
@@ -2140,6 +2140,11 @@ export const es: TranslationResources = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
providerUsage: {
|
providerUsage: {
|
||||||
|
checkUsage: "Consultar uso",
|
||||||
|
checkUsageHint: "Se aplica a {{host}} en todos los dispositivos",
|
||||||
|
off: "El uso está desactivado en {{host}}.",
|
||||||
|
turnOn: "Activar",
|
||||||
|
|
||||||
options: "Configuración",
|
options: "Configuración",
|
||||||
refreshFailed: "No se pudo actualizar el uso",
|
refreshFailed: "No se pudo actualizar el uso",
|
||||||
noHosts: "No hay hosts conectados",
|
noHosts: "No hay hosts conectados",
|
||||||
@@ -2187,6 +2192,7 @@ export const es: TranslationResources = {
|
|||||||
days: "{{value}} d",
|
days: "{{value}} d",
|
||||||
hours: "{{value}} h",
|
hours: "{{value}} h",
|
||||||
minutes: "{{value}} min",
|
minutes: "{{value}} min",
|
||||||
|
pair: "{{first}} {{second}}",
|
||||||
},
|
},
|
||||||
timing: {
|
timing: {
|
||||||
lastUpdated: "Última actualización {{relativeTime}}",
|
lastUpdated: "Última actualización {{relativeTime}}",
|
||||||
@@ -2194,6 +2200,8 @@ export const es: TranslationResources = {
|
|||||||
resetTimePassed: "Pasó la hora de restablecimiento",
|
resetTimePassed: "Pasó la hora de restablecimiento",
|
||||||
resettingNow: "se restablece ahora",
|
resettingNow: "se restablece ahora",
|
||||||
resetsIn: "se restablece en {{duration}}",
|
resetsIn: "se restablece en {{duration}}",
|
||||||
|
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||||
|
resetsAtDate: "{{date}}, {{time}}",
|
||||||
runsOutNow: "se agota ahora",
|
runsOutNow: "se agota ahora",
|
||||||
runsOutIn: "se agota en {{duration}}",
|
runsOutIn: "se agota en {{duration}}",
|
||||||
justNow: "ahora mismo",
|
justNow: "ahora mismo",
|
||||||
@@ -2800,6 +2808,14 @@ export const es: TranslationResources = {
|
|||||||
},
|
},
|
||||||
agents: {
|
agents: {
|
||||||
unavailable: "Connect to this host to manage agents",
|
unavailable: "Connect to this host to manage agents",
|
||||||
|
resumeOnStartup: {
|
||||||
|
title: "Reanudar agentes tras reiniciar",
|
||||||
|
info: "Vuelve a abrir los agentes que estaban trabajando cuando se detuvo el host y envía el mensaje de reanudación. Se aplica tras reinicios normales y fallos.",
|
||||||
|
hint: "Continuar automáticamente el trabajo interrumpido.",
|
||||||
|
prompt: "Mensaje de reanudación",
|
||||||
|
edit: "Editar",
|
||||||
|
editAccessibilityLabel: "Editar mensaje",
|
||||||
|
},
|
||||||
idleRuntimeCleanup: {
|
idleRuntimeCleanup: {
|
||||||
title: "Liberar agentes inactivos",
|
title: "Liberar agentes inactivos",
|
||||||
hint: "Libera memoria tras una hora de inactividad.",
|
hint: "Libera memoria tras una hora de inactividad.",
|
||||||
@@ -2897,6 +2913,11 @@ export const es: TranslationResources = {
|
|||||||
requestFailedTitle: "Error",
|
requestFailedTitle: "Error",
|
||||||
requestFailedMessage:
|
requestFailedMessage:
|
||||||
"No se pudo enviar la solicitud de reinicio.Paseose vuelve a conectar automáticamente; inténtelo nuevamente una vez que el host se muestre en línea.",
|
"No se pudo enviar la solicitud de reinicio.Paseose vuelve a conectar automáticamente; inténtelo nuevamente una vez que el host se muestre en línea.",
|
||||||
|
closeTerminals: "Reiniciar y cerrar terminales",
|
||||||
|
closeTerminalsHint:
|
||||||
|
"Reinicia y además cierra todas las terminales abiertas en este host.",
|
||||||
|
closeTerminalsConfirmMessage:
|
||||||
|
"Esto reiniciará el daemon y cerrará todas sus terminales, terminando los programas que se ejecutan en ellas. La app se reconectará automáticamente.",
|
||||||
dialogFailedMessage:
|
dialogFailedMessage:
|
||||||
"No se puede abrir el cuadro de diálogo de confirmación de reinicio.",
|
"No se puede abrir el cuadro de diálogo de confirmación de reinicio.",
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -2140,6 +2140,11 @@ export const fr: TranslationResources = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
providerUsage: {
|
providerUsage: {
|
||||||
|
checkUsage: "Vérifier l’utilisation",
|
||||||
|
checkUsageHint: "S’applique à {{host}} sur tous les appareils",
|
||||||
|
off: "L’utilisation est désactivée sur {{host}}.",
|
||||||
|
turnOn: "Activer",
|
||||||
|
|
||||||
options: "Paramètres",
|
options: "Paramètres",
|
||||||
refreshFailed: "Impossible d’actualiser l’utilisation",
|
refreshFailed: "Impossible d’actualiser l’utilisation",
|
||||||
noHosts: "Aucun hôte connecté",
|
noHosts: "Aucun hôte connecté",
|
||||||
@@ -2187,6 +2192,7 @@ export const fr: TranslationResources = {
|
|||||||
days: "{{value}} j",
|
days: "{{value}} j",
|
||||||
hours: "{{value}} h",
|
hours: "{{value}} h",
|
||||||
minutes: "{{value}} min",
|
minutes: "{{value}} min",
|
||||||
|
pair: "{{first}} {{second}}",
|
||||||
},
|
},
|
||||||
timing: {
|
timing: {
|
||||||
lastUpdated: "Dernière mise à jour {{relativeTime}}",
|
lastUpdated: "Dernière mise à jour {{relativeTime}}",
|
||||||
@@ -2194,6 +2200,8 @@ export const fr: TranslationResources = {
|
|||||||
resetTimePassed: "Heure de réinitialisation dépassée",
|
resetTimePassed: "Heure de réinitialisation dépassée",
|
||||||
resettingNow: "réinitialisation en cours",
|
resettingNow: "réinitialisation en cours",
|
||||||
resetsIn: "se réinitialise dans {{duration}}",
|
resetsIn: "se réinitialise dans {{duration}}",
|
||||||
|
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||||
|
resetsAtDate: "{{date}}, {{time}}",
|
||||||
runsOutNow: "s’épuise maintenant",
|
runsOutNow: "s’épuise maintenant",
|
||||||
runsOutIn: "s’épuise dans {{duration}}",
|
runsOutIn: "s’épuise dans {{duration}}",
|
||||||
justNow: "à l’instant",
|
justNow: "à l’instant",
|
||||||
@@ -2803,6 +2811,14 @@ export const fr: TranslationResources = {
|
|||||||
},
|
},
|
||||||
agents: {
|
agents: {
|
||||||
unavailable: "Connectez-vous à cet hôte pour gérer les agents",
|
unavailable: "Connectez-vous à cet hôte pour gérer les agents",
|
||||||
|
resumeOnStartup: {
|
||||||
|
title: "Reprendre les agents après un redémarrage",
|
||||||
|
info: "Rouvre les agents qui travaillaient lorsque l’hôte s’est arrêté et envoie le message de reprise. S’applique après un redémarrage normal ou un plantage.",
|
||||||
|
hint: "Continuer automatiquement le travail interrompu.",
|
||||||
|
prompt: "Message de reprise",
|
||||||
|
edit: "Modifier",
|
||||||
|
editAccessibilityLabel: "Modifier le message",
|
||||||
|
},
|
||||||
idleRuntimeCleanup: {
|
idleRuntimeCleanup: {
|
||||||
title: "Libérer les agents inactifs",
|
title: "Libérer les agents inactifs",
|
||||||
hint: "Libère de la mémoire après une heure d’inactivité.",
|
hint: "Libère de la mémoire après une heure d’inactivité.",
|
||||||
@@ -2902,6 +2918,10 @@ export const fr: TranslationResources = {
|
|||||||
requestFailedTitle: "Erreur",
|
requestFailedTitle: "Erreur",
|
||||||
requestFailedMessage:
|
requestFailedMessage:
|
||||||
"Impossible d’envoyer la demande de redémarrage. Paseo se reconnecte automatiquement : réessayez quand l’hôte apparaît en ligne.",
|
"Impossible d’envoyer la demande de redémarrage. Paseo se reconnecte automatiquement : réessayez quand l’hôte apparaît en ligne.",
|
||||||
|
closeTerminals: "Redémarrer et fermer les terminaux",
|
||||||
|
closeTerminalsHint: "Redémarre et ferme aussi tous les terminaux ouverts sur cet hôte.",
|
||||||
|
closeTerminalsConfirmMessage:
|
||||||
|
"Le daemon va redémarrer et fermer tous ses terminaux, ce qui arrêtera les programmes qui y tournent. L'app se reconnectera automatiquement.",
|
||||||
dialogFailedMessage:
|
dialogFailedMessage:
|
||||||
"Impossible d’ouvrir la boîte de dialogue de confirmation du redémarrage.",
|
"Impossible d’ouvrir la boîte de dialogue de confirmation du redémarrage.",
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -2113,6 +2113,11 @@ export const ja: TranslationResources = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
providerUsage: {
|
providerUsage: {
|
||||||
|
checkUsage: "使用状況を確認",
|
||||||
|
checkUsageHint: "すべてのデバイスで {{host}} に適用",
|
||||||
|
off: "{{host}} の使用状況確認はオフです。",
|
||||||
|
turnOn: "オンにする",
|
||||||
|
|
||||||
options: "設定",
|
options: "設定",
|
||||||
refreshFailed: "使用状況を更新できません",
|
refreshFailed: "使用状況を更新できません",
|
||||||
noHosts: "接続中のホストがありません",
|
noHosts: "接続中のホストがありません",
|
||||||
@@ -2160,6 +2165,7 @@ export const ja: TranslationResources = {
|
|||||||
days: "{{value}}日",
|
days: "{{value}}日",
|
||||||
hours: "{{value}}時間",
|
hours: "{{value}}時間",
|
||||||
minutes: "{{value}}分",
|
minutes: "{{value}}分",
|
||||||
|
pair: "{{first}}{{second}}",
|
||||||
},
|
},
|
||||||
timing: {
|
timing: {
|
||||||
lastUpdated: "最終更新: {{relativeTime}}",
|
lastUpdated: "最終更新: {{relativeTime}}",
|
||||||
@@ -2167,6 +2173,8 @@ export const ja: TranslationResources = {
|
|||||||
resetTimePassed: "リセット時刻を過ぎています",
|
resetTimePassed: "リセット時刻を過ぎています",
|
||||||
resettingNow: "まもなくリセット",
|
resettingNow: "まもなくリセット",
|
||||||
resetsIn: "{{duration}}後にリセット",
|
resetsIn: "{{duration}}後にリセット",
|
||||||
|
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||||
|
resetsAtDate: "{{date}} {{time}}",
|
||||||
runsOutNow: "まもなく上限に到達",
|
runsOutNow: "まもなく上限に到達",
|
||||||
runsOutIn: "{{duration}}後に上限に到達",
|
runsOutIn: "{{duration}}後に上限に到達",
|
||||||
justNow: "たった今",
|
justNow: "たった今",
|
||||||
@@ -2767,6 +2775,14 @@ export const ja: TranslationResources = {
|
|||||||
},
|
},
|
||||||
agents: {
|
agents: {
|
||||||
unavailable: "エージェントを管理するにはこのホストに接続してください",
|
unavailable: "エージェントを管理するにはこのホストに接続してください",
|
||||||
|
resumeOnStartup: {
|
||||||
|
title: "再起動後にエージェントを再開",
|
||||||
|
info: "ホストの停止時に作業中だったエージェントを開き直し、再開メッセージを送信します。通常の再起動とクラッシュの両方に適用されます。",
|
||||||
|
hint: "中断された作業を自動的に続行します。",
|
||||||
|
prompt: "再開メッセージ",
|
||||||
|
edit: "編集",
|
||||||
|
editAccessibilityLabel: "メッセージを編集",
|
||||||
|
},
|
||||||
idleRuntimeCleanup: {
|
idleRuntimeCleanup: {
|
||||||
title: "アイドル状態のエージェントを解放",
|
title: "アイドル状態のエージェントを解放",
|
||||||
hint: "1 時間のアイドル状態の後にメモリを解放します。",
|
hint: "1 時間のアイドル状態の後にメモリを解放します。",
|
||||||
@@ -2865,6 +2881,10 @@ export const ja: TranslationResources = {
|
|||||||
requestFailedTitle: "エラー",
|
requestFailedTitle: "エラー",
|
||||||
requestFailedMessage:
|
requestFailedMessage:
|
||||||
"再起動リクエストの送信に失敗しました。Paseoは自動的に再接続します。ホストがオンラインになったら再試行してください。",
|
"再起動リクエストの送信に失敗しました。Paseoは自動的に再接続します。ホストがオンラインになったら再試行してください。",
|
||||||
|
closeTerminals: "再起動してターミナルを閉じる",
|
||||||
|
closeTerminalsHint: "再起動し、このホストのすべてのターミナルも閉じます。",
|
||||||
|
closeTerminalsConfirmMessage:
|
||||||
|
"デーモンを再起動し、すべてのターミナルを閉じます。ターミナルで実行中のプログラムは終了します。アプリは自動的に再接続します。",
|
||||||
dialogFailedMessage: "再起動確認ダイアログを開けませんでした。",
|
dialogFailedMessage: "再起動確認ダイアログを開けませんでした。",
|
||||||
},
|
},
|
||||||
update: {
|
update: {
|
||||||
|
|||||||
@@ -2102,6 +2102,11 @@ export const ko: TranslationResources = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
providerUsage: {
|
providerUsage: {
|
||||||
|
checkUsage: "사용량 확인",
|
||||||
|
checkUsageHint: "모든 기기에서 {{host}}에 적용",
|
||||||
|
off: "{{host}}의 사용량 확인이 꺼져 있습니다.",
|
||||||
|
turnOn: "켜기",
|
||||||
|
|
||||||
options: "설정",
|
options: "설정",
|
||||||
refreshFailed: "사용량을 새로 고칠 수 없습니다",
|
refreshFailed: "사용량을 새로 고칠 수 없습니다",
|
||||||
noHosts: "연결된 호스트가 없습니다",
|
noHosts: "연결된 호스트가 없습니다",
|
||||||
@@ -2149,6 +2154,7 @@ export const ko: TranslationResources = {
|
|||||||
days: "{{value}}일",
|
days: "{{value}}일",
|
||||||
hours: "{{value}}시간",
|
hours: "{{value}}시간",
|
||||||
minutes: "{{value}}분",
|
minutes: "{{value}}분",
|
||||||
|
pair: "{{first}} {{second}}",
|
||||||
},
|
},
|
||||||
timing: {
|
timing: {
|
||||||
lastUpdated: "마지막 업데이트: {{relativeTime}}",
|
lastUpdated: "마지막 업데이트: {{relativeTime}}",
|
||||||
@@ -2156,6 +2162,8 @@ export const ko: TranslationResources = {
|
|||||||
resetTimePassed: "초기화 시간이 지났습니다",
|
resetTimePassed: "초기화 시간이 지났습니다",
|
||||||
resettingNow: "지금 재설정 중",
|
resettingNow: "지금 재설정 중",
|
||||||
resetsIn: "{{duration}} 후 재설정",
|
resetsIn: "{{duration}} 후 재설정",
|
||||||
|
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||||
|
resetsAtDate: "{{date}} {{time}}",
|
||||||
runsOutNow: "지금 한도에 도달",
|
runsOutNow: "지금 한도에 도달",
|
||||||
runsOutIn: "{{duration}} 후 한도에 도달",
|
runsOutIn: "{{duration}} 후 한도에 도달",
|
||||||
justNow: "방금",
|
justNow: "방금",
|
||||||
@@ -2755,6 +2763,14 @@ export const ko: TranslationResources = {
|
|||||||
},
|
},
|
||||||
agents: {
|
agents: {
|
||||||
unavailable: "에이전트를 관리하려면 이 호스트에 연결하세요",
|
unavailable: "에이전트를 관리하려면 이 호스트에 연결하세요",
|
||||||
|
resumeOnStartup: {
|
||||||
|
title: "재시작 후 에이전트 재개",
|
||||||
|
info: "호스트가 중지될 때 작업 중이던 에이전트를 다시 열고 재개 메시지를 보냅니다. 정상 재시작과 비정상 종료 후 모두 적용됩니다.",
|
||||||
|
hint: "중단된 작업을 자동으로 계속합니다.",
|
||||||
|
prompt: "재개 메시지",
|
||||||
|
edit: "편집",
|
||||||
|
editAccessibilityLabel: "메시지 편집",
|
||||||
|
},
|
||||||
idleRuntimeCleanup: {
|
idleRuntimeCleanup: {
|
||||||
title: "유휴 에이전트 해제",
|
title: "유휴 에이전트 해제",
|
||||||
hint: "1시간 동안 활동이 없으면 메모리를 확보합니다.",
|
hint: "1시간 동안 활동이 없으면 메모리를 확보합니다.",
|
||||||
@@ -2852,6 +2868,10 @@ export const ko: TranslationResources = {
|
|||||||
requestFailedTitle: "오류",
|
requestFailedTitle: "오류",
|
||||||
requestFailedMessage:
|
requestFailedMessage:
|
||||||
"재시작 요청을 보내지 못했습니다. Paseo가 자동으로 다시 연결하므로 호스트가 온라인으로 표시되면 다시 시도하세요.",
|
"재시작 요청을 보내지 못했습니다. Paseo가 자동으로 다시 연결하므로 호스트가 온라인으로 표시되면 다시 시도하세요.",
|
||||||
|
closeTerminals: "재시작하고 터미널 닫기",
|
||||||
|
closeTerminalsHint: "재시작하면서 이 호스트의 모든 터미널도 닫습니다.",
|
||||||
|
closeTerminalsConfirmMessage:
|
||||||
|
"데몬을 재시작하고 모든 터미널을 닫습니다. 터미널에서 실행 중인 프로그램은 종료됩니다. 앱은 자동으로 다시 연결됩니다.",
|
||||||
dialogFailedMessage: "재시작 확인 대화 상자를 열 수 없습니다.",
|
dialogFailedMessage: "재시작 확인 대화 상자를 열 수 없습니다.",
|
||||||
},
|
},
|
||||||
update: {
|
update: {
|
||||||
|
|||||||
@@ -2125,6 +2125,11 @@ export const ptBR: TranslationResources = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
providerUsage: {
|
providerUsage: {
|
||||||
|
checkUsage: "Consultar uso",
|
||||||
|
checkUsageHint: "Aplica-se a {{host}} em todos os dispositivos",
|
||||||
|
off: "O uso está desativado em {{host}}.",
|
||||||
|
turnOn: "Ativar",
|
||||||
|
|
||||||
options: "Configurações",
|
options: "Configurações",
|
||||||
refreshFailed: "Não foi possível atualizar o uso",
|
refreshFailed: "Não foi possível atualizar o uso",
|
||||||
noHosts: "Nenhum host conectado",
|
noHosts: "Nenhum host conectado",
|
||||||
@@ -2172,6 +2177,7 @@ export const ptBR: TranslationResources = {
|
|||||||
days: "{{value}} d",
|
days: "{{value}} d",
|
||||||
hours: "{{value}} h",
|
hours: "{{value}} h",
|
||||||
minutes: "{{value}} min",
|
minutes: "{{value}} min",
|
||||||
|
pair: "{{first}} {{second}}",
|
||||||
},
|
},
|
||||||
timing: {
|
timing: {
|
||||||
lastUpdated: "Última atualização {{relativeTime}}",
|
lastUpdated: "Última atualização {{relativeTime}}",
|
||||||
@@ -2179,6 +2185,8 @@ export const ptBR: TranslationResources = {
|
|||||||
resetTimePassed: "O horário de redefinição passou",
|
resetTimePassed: "O horário de redefinição passou",
|
||||||
resettingNow: "redefinindo agora",
|
resettingNow: "redefinindo agora",
|
||||||
resetsIn: "redefine em {{duration}}",
|
resetsIn: "redefine em {{duration}}",
|
||||||
|
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||||
|
resetsAtDate: "{{date}}, {{time}}",
|
||||||
runsOutNow: "esgota agora",
|
runsOutNow: "esgota agora",
|
||||||
runsOutIn: "esgota em {{duration}}",
|
runsOutIn: "esgota em {{duration}}",
|
||||||
justNow: "agora mesmo",
|
justNow: "agora mesmo",
|
||||||
@@ -2782,6 +2790,14 @@ export const ptBR: TranslationResources = {
|
|||||||
},
|
},
|
||||||
agents: {
|
agents: {
|
||||||
unavailable: "Conecte-se a este host para gerenciar agentes",
|
unavailable: "Conecte-se a este host para gerenciar agentes",
|
||||||
|
resumeOnStartup: {
|
||||||
|
title: "Retomar agentes após reiniciar",
|
||||||
|
info: "Reabre os agentes que estavam trabalhando quando o host parou e envia a mensagem de retomada. Aplica-se após reinicializações normais e falhas.",
|
||||||
|
hint: "Continuar automaticamente o trabalho interrompido.",
|
||||||
|
prompt: "Mensagem de retomada",
|
||||||
|
edit: "Editar",
|
||||||
|
editAccessibilityLabel: "Editar mensagem",
|
||||||
|
},
|
||||||
idleRuntimeCleanup: {
|
idleRuntimeCleanup: {
|
||||||
title: "Liberar agentes ociosos",
|
title: "Liberar agentes ociosos",
|
||||||
hint: "Libera memória após uma hora de inatividade.",
|
hint: "Libera memória após uma hora de inatividade.",
|
||||||
@@ -2880,6 +2896,10 @@ export const ptBR: TranslationResources = {
|
|||||||
requestFailedTitle: "Erro",
|
requestFailedTitle: "Erro",
|
||||||
requestFailedMessage:
|
requestFailedMessage:
|
||||||
"Falha ao enviar a solicitação de reinício. O Paseo reconecta automaticamente. Tente novamente quando o host aparecer como online.",
|
"Falha ao enviar a solicitação de reinício. O Paseo reconecta automaticamente. Tente novamente quando o host aparecer como online.",
|
||||||
|
closeTerminals: "Reiniciar e fechar terminais",
|
||||||
|
closeTerminalsHint: "Reinicia e também fecha todos os terminais abertos neste host.",
|
||||||
|
closeTerminalsConfirmMessage:
|
||||||
|
"Isso reiniciará o daemon e fechará todos os terminais dele, encerrando os programas que rodam neles. O app vai se reconectar automaticamente.",
|
||||||
dialogFailedMessage: "Não foi possível abrir o diálogo de confirmação de reinício.",
|
dialogFailedMessage: "Não foi possível abrir o diálogo de confirmação de reinício.",
|
||||||
},
|
},
|
||||||
update: {
|
update: {
|
||||||
|
|||||||
@@ -2125,6 +2125,11 @@ export const ru: TranslationResources = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
providerUsage: {
|
providerUsage: {
|
||||||
|
checkUsage: "Проверять использование",
|
||||||
|
checkUsageHint: "Применяется к {{host}} на всех устройствах",
|
||||||
|
off: "Проверка использования отключена на {{host}}.",
|
||||||
|
turnOn: "Включить",
|
||||||
|
|
||||||
options: "Настройки",
|
options: "Настройки",
|
||||||
refreshFailed: "Не удалось обновить использование",
|
refreshFailed: "Не удалось обновить использование",
|
||||||
noHosts: "Нет подключённых хостов",
|
noHosts: "Нет подключённых хостов",
|
||||||
@@ -2172,6 +2177,7 @@ export const ru: TranslationResources = {
|
|||||||
days: "{{value}} дн.",
|
days: "{{value}} дн.",
|
||||||
hours: "{{value}} ч",
|
hours: "{{value}} ч",
|
||||||
minutes: "{{value}} мин",
|
minutes: "{{value}} мин",
|
||||||
|
pair: "{{first}} {{second}}",
|
||||||
},
|
},
|
||||||
timing: {
|
timing: {
|
||||||
lastUpdated: "Последнее обновление {{relativeTime}}",
|
lastUpdated: "Последнее обновление {{relativeTime}}",
|
||||||
@@ -2179,6 +2185,8 @@ export const ru: TranslationResources = {
|
|||||||
resetTimePassed: "Время сброса прошло",
|
resetTimePassed: "Время сброса прошло",
|
||||||
resettingNow: "сброс сейчас",
|
resettingNow: "сброс сейчас",
|
||||||
resetsIn: "сброс через {{duration}}",
|
resetsIn: "сброс через {{duration}}",
|
||||||
|
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||||
|
resetsAtDate: "{{date}}, {{time}}",
|
||||||
runsOutNow: "закончится сейчас",
|
runsOutNow: "закончится сейчас",
|
||||||
runsOutIn: "закончится через {{duration}}",
|
runsOutIn: "закончится через {{duration}}",
|
||||||
justNow: "только что",
|
justNow: "только что",
|
||||||
@@ -2792,6 +2800,14 @@ export const ru: TranslationResources = {
|
|||||||
},
|
},
|
||||||
agents: {
|
agents: {
|
||||||
unavailable: "Подключитесь к этому хосту, чтобы управлять агентами",
|
unavailable: "Подключитесь к этому хосту, чтобы управлять агентами",
|
||||||
|
resumeOnStartup: {
|
||||||
|
title: "Возобновлять агентов после перезапуска",
|
||||||
|
info: "Открывает агентов, которые работали при остановке хоста, и отправляет сообщение для продолжения. Применяется после обычного перезапуска и сбоя.",
|
||||||
|
hint: "Автоматически продолжать прерванную работу.",
|
||||||
|
prompt: "Сообщение для продолжения",
|
||||||
|
edit: "Редактировать",
|
||||||
|
editAccessibilityLabel: "Изменить сообщение",
|
||||||
|
},
|
||||||
idleRuntimeCleanup: {
|
idleRuntimeCleanup: {
|
||||||
title: "Освобождать неактивных агентов",
|
title: "Освобождать неактивных агентов",
|
||||||
hint: "Освобождает память после часа бездействия.",
|
hint: "Освобождает память после часа бездействия.",
|
||||||
@@ -2890,6 +2906,10 @@ export const ru: TranslationResources = {
|
|||||||
requestFailedTitle: "Ошибка",
|
requestFailedTitle: "Ошибка",
|
||||||
requestFailedMessage:
|
requestFailedMessage:
|
||||||
"Не удалось отправить запрос на перезапуск. Paseo переподключается автоматически. Повторите попытку, когда хост появится в сети.",
|
"Не удалось отправить запрос на перезапуск. Paseo переподключается автоматически. Повторите попытку, когда хост появится в сети.",
|
||||||
|
closeTerminals: "Перезапустить и закрыть терминалы",
|
||||||
|
closeTerminalsHint: "Перезапускает демон и закрывает все терминалы на этом хосте.",
|
||||||
|
closeTerminalsConfirmMessage:
|
||||||
|
"Демон будет перезапущен, а все его терминалы закрыты вместе с запущенными в них программами. Приложение переподключится автоматически.",
|
||||||
dialogFailedMessage: "Не удалось открыть диалог подтверждения перезапуска.",
|
dialogFailedMessage: "Не удалось открыть диалог подтверждения перезапуска.",
|
||||||
},
|
},
|
||||||
update: {
|
update: {
|
||||||
|
|||||||
@@ -2070,6 +2070,11 @@ export const zhCN: TranslationResources = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
providerUsage: {
|
providerUsage: {
|
||||||
|
checkUsage: "检查用量",
|
||||||
|
checkUsageHint: "在所有设备上应用于 {{host}}",
|
||||||
|
off: "{{host}} 的用量检查已关闭。",
|
||||||
|
turnOn: "开启",
|
||||||
|
|
||||||
options: "设置",
|
options: "设置",
|
||||||
refreshFailed: "无法刷新用量",
|
refreshFailed: "无法刷新用量",
|
||||||
noHosts: "没有已连接的主机",
|
noHosts: "没有已连接的主机",
|
||||||
@@ -2117,6 +2122,7 @@ export const zhCN: TranslationResources = {
|
|||||||
days: "{{value}}天",
|
days: "{{value}}天",
|
||||||
hours: "{{value}}小时",
|
hours: "{{value}}小时",
|
||||||
minutes: "{{value}}分钟",
|
minutes: "{{value}}分钟",
|
||||||
|
pair: "{{first}}{{second}}",
|
||||||
},
|
},
|
||||||
timing: {
|
timing: {
|
||||||
lastUpdated: "上次更新于 {{relativeTime}}",
|
lastUpdated: "上次更新于 {{relativeTime}}",
|
||||||
@@ -2124,6 +2130,8 @@ export const zhCN: TranslationResources = {
|
|||||||
resetTimePassed: "重置时间已过",
|
resetTimePassed: "重置时间已过",
|
||||||
resettingNow: "正在重置",
|
resettingNow: "正在重置",
|
||||||
resetsIn: "将在 {{duration}}后重置",
|
resetsIn: "将在 {{duration}}后重置",
|
||||||
|
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||||
|
resetsAtDate: "{{date}} {{time}}",
|
||||||
runsOutNow: "即将用尽",
|
runsOutNow: "即将用尽",
|
||||||
runsOutIn: "将在 {{duration}}后用尽",
|
runsOutIn: "将在 {{duration}}后用尽",
|
||||||
justNow: "刚刚",
|
justNow: "刚刚",
|
||||||
@@ -2713,6 +2721,14 @@ export const zhCN: TranslationResources = {
|
|||||||
},
|
},
|
||||||
agents: {
|
agents: {
|
||||||
unavailable: "连接到这个 Host 以管理 Agent",
|
unavailable: "连接到这个 Host 以管理 Agent",
|
||||||
|
resumeOnStartup: {
|
||||||
|
title: "重启后恢复智能体",
|
||||||
|
info: "重新打开主机停止时正在工作的智能体,并发送恢复提示。适用于正常重启和崩溃后的恢复。",
|
||||||
|
hint: "自动继续被中断的工作。",
|
||||||
|
prompt: "恢复提示",
|
||||||
|
edit: "编辑",
|
||||||
|
editAccessibilityLabel: "编辑提示",
|
||||||
|
},
|
||||||
idleRuntimeCleanup: {
|
idleRuntimeCleanup: {
|
||||||
title: "释放空闲 Agent",
|
title: "释放空闲 Agent",
|
||||||
hint: "空闲一小时后释放内存。",
|
hint: "空闲一小时后释放内存。",
|
||||||
@@ -2804,6 +2820,10 @@ export const zhCN: TranslationResources = {
|
|||||||
offlineMessage: "这个 Host 已离线。Paseo 会自动重连,请等它恢复在线后再重启。",
|
offlineMessage: "这个 Host 已离线。Paseo 会自动重连,请等它恢复在线后再重启。",
|
||||||
requestFailedTitle: "错误",
|
requestFailedTitle: "错误",
|
||||||
requestFailedMessage: "发送重启请求失败。Paseo 会自动重连,请在 Host 显示在线后重试。",
|
requestFailedMessage: "发送重启请求失败。Paseo 会自动重连,请在 Host 显示在线后重试。",
|
||||||
|
closeTerminals: "重启并关闭终端",
|
||||||
|
closeTerminalsHint: "重启的同时关闭此主机上的所有终端。",
|
||||||
|
closeTerminalsConfirmMessage:
|
||||||
|
"这将重启守护进程并关闭其所有终端,终端中运行的程序会被结束。应用会自动重新连接。",
|
||||||
dialogFailedMessage: "无法打开重启确认对话框。",
|
dialogFailedMessage: "无法打开重启确认对话框。",
|
||||||
},
|
},
|
||||||
update: {
|
update: {
|
||||||
|
|||||||
@@ -0,0 +1,424 @@
|
|||||||
|
import appPackage from "../../package.json";
|
||||||
|
import { afterEach, expect, it } from "vitest";
|
||||||
|
import { QueryObserver } from "@tanstack/react-query";
|
||||||
|
import { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||||
|
import type { SessionOutboundMessage } from "@getpaseo/protocol/messages";
|
||||||
|
import { settingsRpc } from "@getpaseo/plugin";
|
||||||
|
import { syncPluginCatalog } from "./catalog-sync-model";
|
||||||
|
import { createPluginHosts } from "./hosts";
|
||||||
|
import { PluginRegistry } from "./registry";
|
||||||
|
import { pluginSettingsKey } from "./settings/query";
|
||||||
|
import type { InstalledPlugin } from "./types";
|
||||||
|
|
||||||
|
const audio = { play: async () => 0 };
|
||||||
|
const rpc = settingsRpc("preferences");
|
||||||
|
type Catalog = Awaited<ReturnType<DaemonClient["getPluginCatalog"]>>;
|
||||||
|
type Observation = ReturnType<DaemonClient["observeEvents"]>;
|
||||||
|
type Observer = Parameters<Observation["subscribe"]>[0];
|
||||||
|
|
||||||
|
class SettingsStore {
|
||||||
|
private revision = 1;
|
||||||
|
private values = { label: "original" };
|
||||||
|
reads = 0;
|
||||||
|
|
||||||
|
read() {
|
||||||
|
this.reads++;
|
||||||
|
return { status: "ready", revision: String(this.revision), values: this.values } as const;
|
||||||
|
}
|
||||||
|
|
||||||
|
write(input: unknown) {
|
||||||
|
const write = rpc.write.input.parse(input);
|
||||||
|
if (write.revision !== String(this.revision)) {
|
||||||
|
return { status: "conflict", error: "Settings changed" } as const;
|
||||||
|
}
|
||||||
|
const values = write.values;
|
||||||
|
if (typeof values !== "object" || values === null || !("label" in values)) {
|
||||||
|
throw new Error("Expected settings values");
|
||||||
|
}
|
||||||
|
if (typeof values.label !== "string") throw new Error("Expected label");
|
||||||
|
this.values = { label: values.label };
|
||||||
|
this.revision++;
|
||||||
|
return { status: "saved", revision: String(this.revision), values: this.values } as const;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** In-memory daemon port; it delivers owned snapshots and stops updates on release. */
|
||||||
|
class CatalogClient extends DaemonClient {
|
||||||
|
catalog = catalog("one");
|
||||||
|
fetches = 0;
|
||||||
|
releases = 0;
|
||||||
|
events: Parameters<DaemonClient["observeEvents"]>[0] = [];
|
||||||
|
private readonly observers = new Set<Observer>();
|
||||||
|
|
||||||
|
constructor(readonly settings = new SettingsStore()) {
|
||||||
|
super({ url: "ws://unused.test", clientId: "catalog-sync-test" });
|
||||||
|
}
|
||||||
|
|
||||||
|
override async getPluginCatalog(): Promise<Catalog> {
|
||||||
|
this.fetches++;
|
||||||
|
return this.catalog;
|
||||||
|
}
|
||||||
|
|
||||||
|
override observeEvents(events: Parameters<DaemonClient["observeEvents"]>[0]): Observation {
|
||||||
|
this.events = events;
|
||||||
|
const snapshot = { requestId: "events", subscriptionId: "catalog" };
|
||||||
|
const subscribers = new Set<Observer>();
|
||||||
|
return {
|
||||||
|
subscriptionId: snapshot.subscriptionId,
|
||||||
|
ready: Promise.resolve(snapshot),
|
||||||
|
subscribe: (observer) => {
|
||||||
|
subscribers.add(observer);
|
||||||
|
this.observers.add(observer);
|
||||||
|
observer.snapshot(snapshot);
|
||||||
|
return () => {
|
||||||
|
subscribers.delete(observer);
|
||||||
|
this.observers.delete(observer);
|
||||||
|
};
|
||||||
|
},
|
||||||
|
release: async () => {
|
||||||
|
this.releases++;
|
||||||
|
for (const observer of subscribers) this.observers.delete(observer);
|
||||||
|
subscribers.clear();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
override async invokePluginRpc(_pluginId: string, method: string, input: unknown) {
|
||||||
|
if (method === rpc.read.name) return this.settings.read();
|
||||||
|
if (method === rpc.write.name) return this.settings.write(input);
|
||||||
|
throw new Error(`Unexpected RPC: ${method}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
update(message: SessionOutboundMessage) {
|
||||||
|
for (const observer of this.observers) observer.update(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
snapshot() {
|
||||||
|
for (const observer of this.observers) {
|
||||||
|
observer.snapshot({ requestId: "reconnect", subscriptionId: "catalog" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function catalog(marker: string): Catalog {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
id: "reports",
|
||||||
|
requirements: { paseo: `>=${appPackage.version}` },
|
||||||
|
clientBundle: `(function() { return { default: function(plugin) {
|
||||||
|
plugin.addTimelineTransformer({
|
||||||
|
id: "report", query: { itemType: "tool_call" },
|
||||||
|
transform() { return ${JSON.stringify(marker)} ? { items: [] } : undefined; }
|
||||||
|
});
|
||||||
|
return function() { plugin.openSettings("cleanup"); };
|
||||||
|
} }; })`,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
const cleanups: Array<() => void> = [];
|
||||||
|
afterEach(() => {
|
||||||
|
for (const cleanup of cleanups.splice(0).toReversed()) cleanup();
|
||||||
|
});
|
||||||
|
|
||||||
|
function harness() {
|
||||||
|
let evaluations = 0;
|
||||||
|
let disposals = 0;
|
||||||
|
const registry = new PluginRegistry({
|
||||||
|
localeSource: { getLocale: () => "en", subscribe: () => () => {} },
|
||||||
|
version: appPackage.version,
|
||||||
|
createRuntime(installation) {
|
||||||
|
evaluations++;
|
||||||
|
return {
|
||||||
|
hosts: createPluginHosts(
|
||||||
|
{
|
||||||
|
getHosts: () => [],
|
||||||
|
getSnapshot: () => null,
|
||||||
|
subscribeAll: () => () => {},
|
||||||
|
subscribeHostList: () => () => {},
|
||||||
|
},
|
||||||
|
installation.lifetime.signal,
|
||||||
|
),
|
||||||
|
paseo: installation.paseo,
|
||||||
|
i18n: installation.i18n,
|
||||||
|
rpc: async () => {
|
||||||
|
throw new Error("Unexpected runtime RPC");
|
||||||
|
},
|
||||||
|
openSettings: () => {
|
||||||
|
disposals++;
|
||||||
|
},
|
||||||
|
openScreen() {},
|
||||||
|
openSurface() {},
|
||||||
|
async playAudio() {},
|
||||||
|
openPanel() {},
|
||||||
|
addComposerPill: () => ({ update() {}, remove() {} }),
|
||||||
|
addHeaderButton: () => ({ update() {}, remove() {} }),
|
||||||
|
};
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const client = new CatalogClient();
|
||||||
|
cleanups.push(() => {
|
||||||
|
registry.removeHost("host");
|
||||||
|
registry.removeHost("other");
|
||||||
|
});
|
||||||
|
function sync(options: Partial<Parameters<typeof syncPluginCatalog>[0]> = {}) {
|
||||||
|
const stop = syncPluginCatalog({
|
||||||
|
serverId: "host",
|
||||||
|
client,
|
||||||
|
audio,
|
||||||
|
connected: true,
|
||||||
|
supported: true,
|
||||||
|
registry,
|
||||||
|
...options,
|
||||||
|
});
|
||||||
|
cleanups.push(stop);
|
||||||
|
return stop;
|
||||||
|
}
|
||||||
|
function installed(serverId = "host") {
|
||||||
|
const plugin = registry.getSnapshot().find((entry) => entry.serverId === serverId);
|
||||||
|
if (!plugin) throw new Error(`Missing installation: ${serverId}`);
|
||||||
|
return plugin;
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
registry,
|
||||||
|
client,
|
||||||
|
sync,
|
||||||
|
installed,
|
||||||
|
evaluations: () => evaluations,
|
||||||
|
disposals: () => disposals,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function connected() {
|
||||||
|
const h = harness();
|
||||||
|
const stop = h.sync();
|
||||||
|
await expect.poll(() => h.registry.getSnapshot().length).toBe(1);
|
||||||
|
return { ...h, stop };
|
||||||
|
}
|
||||||
|
|
||||||
|
function settingsQuery(plugin: InstalledPlugin) {
|
||||||
|
return {
|
||||||
|
queryKey: pluginSettingsKey("preferences"),
|
||||||
|
queryFn: async () => rpc.read.output.parse(await plugin.invoke(rpc.read.name, {})),
|
||||||
|
// The replica policy used by useSettings deliberately disables automatic refetches.
|
||||||
|
gcTime: Infinity,
|
||||||
|
staleTime: Infinity,
|
||||||
|
refetchOnMount: false,
|
||||||
|
refetchOnReconnect: false,
|
||||||
|
refetchOnWindowFocus: false,
|
||||||
|
retry: false,
|
||||||
|
} as const;
|
||||||
|
}
|
||||||
|
|
||||||
|
it("retains installations and timeline transforms while disconnected", async () => {
|
||||||
|
const h = await connected();
|
||||||
|
const plugin = h.installed();
|
||||||
|
const snapshot = h.registry.getSnapshot();
|
||||||
|
const transformers = plugin.timelineTransformers;
|
||||||
|
h.stop();
|
||||||
|
h.sync({ connected: false });
|
||||||
|
h.client.update({
|
||||||
|
type: "status",
|
||||||
|
payload: { status: "plugin_catalog_changed", pluginId: "reports" },
|
||||||
|
});
|
||||||
|
expect(h.registry.getSnapshot()).toBe(snapshot);
|
||||||
|
expect(h.installed().timelineTransformers).toBe(transformers);
|
||||||
|
expect(plugin.lifetime.signal.aborted).toBe(false);
|
||||||
|
expect(h.disposals()).toBe(0);
|
||||||
|
expect(h.client.fetches).toBe(1);
|
||||||
|
expect(h.client.events).toEqual([
|
||||||
|
"status.plugin_catalog_changed",
|
||||||
|
"status.plugin_settings_changed",
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each(["mounted", "unmounted"])(
|
||||||
|
"refreshes %s settings and revisions after another client saves offline",
|
||||||
|
async (surface) => {
|
||||||
|
const h = await connected();
|
||||||
|
const plugin = h.installed();
|
||||||
|
const snapshot = h.registry.getSnapshot();
|
||||||
|
const options = settingsQuery(plugin);
|
||||||
|
const original = await plugin.queryClient.fetchQuery(options);
|
||||||
|
const observer = new QueryObserver(plugin.queryClient, options);
|
||||||
|
const unsubscribe = observer.subscribe(() => {});
|
||||||
|
cleanups.push(unsubscribe);
|
||||||
|
if (surface === "unmounted") unsubscribe();
|
||||||
|
plugin.queryClient.setQueryData(["attachment-search"], "retained");
|
||||||
|
const otherClient = new CatalogClient();
|
||||||
|
h.registry.installCatalog("other", otherClient.catalog, { client: otherClient, audio });
|
||||||
|
const otherPlugin = h.installed("other");
|
||||||
|
await otherPlugin.queryClient.fetchQuery(settingsQuery(otherPlugin));
|
||||||
|
// Another host publishes new presentation snapshots without replacing the owning lifetime.
|
||||||
|
const beforeReconnect = h.registry.getSnapshot();
|
||||||
|
const retainedInstallation = h.installed();
|
||||||
|
|
||||||
|
h.stop();
|
||||||
|
h.sync({ connected: false });
|
||||||
|
const clientB = new CatalogClient(h.client.settings);
|
||||||
|
expect(
|
||||||
|
await clientB.invokePluginRpc("reports", rpc.write.name, {
|
||||||
|
revision: original.revision,
|
||||||
|
values: { label: "client B" },
|
||||||
|
}),
|
||||||
|
).toEqual({ status: "saved", revision: "2", values: { label: "client B" } });
|
||||||
|
expect(plugin.queryClient.getQueryData(options.queryKey)).toEqual(original);
|
||||||
|
h.sync();
|
||||||
|
|
||||||
|
await expect
|
||||||
|
.poll(() => plugin.queryClient.getQueryData(options.queryKey))
|
||||||
|
.toEqual({
|
||||||
|
status: "ready",
|
||||||
|
revision: "2",
|
||||||
|
values: { label: "client B" },
|
||||||
|
});
|
||||||
|
const refreshed = await plugin.queryClient.fetchQuery(options);
|
||||||
|
expect(
|
||||||
|
await plugin.invoke(rpc.write.name, {
|
||||||
|
revision: refreshed.revision,
|
||||||
|
values: { label: "client A" },
|
||||||
|
}),
|
||||||
|
).toEqual({ status: "saved", revision: "3", values: { label: "client A" } });
|
||||||
|
expect(h.registry.getSnapshot()).toBe(beforeReconnect);
|
||||||
|
expect(h.installed()).toBe(retainedInstallation);
|
||||||
|
expect(h.installed().lifetime).toBe(plugin.lifetime);
|
||||||
|
expect(h.installed().queryClient).toBe(plugin.queryClient);
|
||||||
|
expect(h.installed().timelineTransformers).toBe(snapshot[0].timelineTransformers);
|
||||||
|
expect(plugin.queryClient.getQueryData(["attachment-search"])).toBe("retained");
|
||||||
|
expect(otherClient.settings.reads).toBe(1);
|
||||||
|
expect(otherPlugin.queryClient.getQueryState(options.queryKey)?.isInvalidated).toBe(false);
|
||||||
|
expect(otherPlugin.queryClient.getQueryData(options.queryKey)).toEqual(original);
|
||||||
|
expect(h.evaluations()).toBe(2);
|
||||||
|
expect(h.disposals()).toBe(0);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
it("replaces changed bundles on reconnect and disposes the old installation", async () => {
|
||||||
|
const h = await connected();
|
||||||
|
const plugin = h.installed();
|
||||||
|
plugin.queryClient.setQueryData(["attachment-search"], "old");
|
||||||
|
h.stop();
|
||||||
|
h.client.catalog = catalog("two");
|
||||||
|
h.sync();
|
||||||
|
await expect.poll(() => h.installed() === plugin).toBe(false);
|
||||||
|
expect(plugin.lifetime.signal.aborted).toBe(true);
|
||||||
|
expect(plugin.queryClient.getQueryCache().getAll()).toEqual([]);
|
||||||
|
expect(h.installed().timelineTransformers.map((entry) => entry.id)).toEqual(["report"]);
|
||||||
|
expect(h.evaluations()).toBe(2);
|
||||||
|
expect(h.disposals()).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("replaces an explicitly reloaded bundle even when its source is unchanged", async () => {
|
||||||
|
const h = await connected();
|
||||||
|
const plugin = h.installed();
|
||||||
|
h.client.update({
|
||||||
|
type: "status",
|
||||||
|
payload: { status: "plugin_catalog_changed", pluginId: "reports" },
|
||||||
|
});
|
||||||
|
await expect.poll(() => h.installed() === plugin).toBe(false);
|
||||||
|
expect(h.disposals()).toBe(1);
|
||||||
|
expect(h.evaluations()).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each(["unsupported", "no audio"])("disposes plugins when %s", async (reason) => {
|
||||||
|
const h = await connected();
|
||||||
|
const plugin = h.installed();
|
||||||
|
h.stop();
|
||||||
|
h.sync({ supported: reason !== "unsupported", audio: reason === "no audio" ? null : audio });
|
||||||
|
expect(h.registry.getSnapshot()).toEqual([]);
|
||||||
|
expect(plugin.lifetime.signal.aborted).toBe(true);
|
||||||
|
expect(h.disposals()).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("refreshes settings on a replayed subscription snapshot without reinstalling", async () => {
|
||||||
|
const h = await connected();
|
||||||
|
const plugin = h.installed();
|
||||||
|
const options = settingsQuery(plugin);
|
||||||
|
await plugin.queryClient.fetchQuery(options);
|
||||||
|
h.client.settings.write({ revision: "1", values: { label: "replayed" } });
|
||||||
|
h.client.snapshot();
|
||||||
|
await expect
|
||||||
|
.poll(() => plugin.queryClient.getQueryData(options.queryKey))
|
||||||
|
.toEqual({
|
||||||
|
status: "ready",
|
||||||
|
revision: "2",
|
||||||
|
values: { label: "replayed" },
|
||||||
|
});
|
||||||
|
expect(h.installed()).toBe(plugin);
|
||||||
|
expect(h.evaluations()).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("invalidates only the named settings on its host for a live notification", async () => {
|
||||||
|
const h = await connected();
|
||||||
|
const plugin = h.installed();
|
||||||
|
const options = settingsQuery(plugin);
|
||||||
|
await plugin.queryClient.fetchQuery(options);
|
||||||
|
const observer = new QueryObserver(plugin.queryClient, options);
|
||||||
|
cleanups.push(observer.subscribe(() => {}));
|
||||||
|
plugin.queryClient.setQueryData(pluginSettingsKey("other-settings"), "unchanged");
|
||||||
|
const other = new CatalogClient();
|
||||||
|
h.registry.installCatalog("other", other.catalog, { client: other, audio });
|
||||||
|
await h.installed("other").queryClient.fetchQuery(settingsQuery(h.installed("other")));
|
||||||
|
|
||||||
|
const beforeNotification = h.registry.getSnapshot();
|
||||||
|
const retainedInstallation = h.installed();
|
||||||
|
h.client.settings.write({ revision: "1", values: { label: "live" } });
|
||||||
|
h.client.update({
|
||||||
|
type: "status",
|
||||||
|
payload: {
|
||||||
|
status: "plugin_settings_changed",
|
||||||
|
pluginId: "reports",
|
||||||
|
settingsId: "preferences",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect
|
||||||
|
.poll(() => plugin.queryClient.getQueryData(options.queryKey))
|
||||||
|
.toEqual({
|
||||||
|
status: "ready",
|
||||||
|
revision: "2",
|
||||||
|
values: { label: "live" },
|
||||||
|
});
|
||||||
|
expect(plugin.queryClient.getQueryState(pluginSettingsKey("other-settings"))?.isInvalidated).toBe(
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
expect(other.settings.reads).toBe(1);
|
||||||
|
expect(h.registry.getSnapshot()).toBe(beforeNotification);
|
||||||
|
expect(h.installed()).toBe(retainedInstallation);
|
||||||
|
expect(h.installed().lifetime).toBe(plugin.lifetime);
|
||||||
|
expect(h.installed().queryClient).toBe(plugin.queryClient);
|
||||||
|
expect(h.evaluations()).toBe(2);
|
||||||
|
expect(h.client.fetches).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ignores an in-flight catalog snapshot after disconnect", async () => {
|
||||||
|
const h = await connected();
|
||||||
|
const plugin = h.installed();
|
||||||
|
await plugin.queryClient.fetchQuery(settingsQuery(plugin));
|
||||||
|
const snapshot = h.registry.getSnapshot();
|
||||||
|
h.stop();
|
||||||
|
let resolveCatalog: (value: Catalog) => void = () => {};
|
||||||
|
const pending = new Promise<Catalog>((resolve) => {
|
||||||
|
resolveCatalog = resolve;
|
||||||
|
});
|
||||||
|
let fetching: () => void = () => {};
|
||||||
|
const started = new Promise<void>((resolve) => {
|
||||||
|
fetching = resolve;
|
||||||
|
});
|
||||||
|
class PendingClient extends CatalogClient {
|
||||||
|
override getPluginCatalog() {
|
||||||
|
fetching();
|
||||||
|
return pending;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const stop = h.sync({ client: new PendingClient(h.client.settings) });
|
||||||
|
await started;
|
||||||
|
stop();
|
||||||
|
resolveCatalog(catalog("late"));
|
||||||
|
await pending;
|
||||||
|
// Drain the catalog continuation through a subsequently queued task.
|
||||||
|
await new Promise<void>((resolve) => setTimeout(resolve, 0));
|
||||||
|
expect(h.registry.getSnapshot()).toBe(snapshot);
|
||||||
|
expect(h.client.settings.reads).toBe(1);
|
||||||
|
expect(h.evaluations()).toBe(1);
|
||||||
|
});
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
import type { AudioEngine } from "@/audio";
|
||||||
|
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||||
|
import type { PluginRegistry } from "./registry";
|
||||||
|
import { pluginSettingsKey, pluginSettingsPrefix } from "./settings/query";
|
||||||
|
|
||||||
|
interface CatalogSyncInput {
|
||||||
|
serverId: string;
|
||||||
|
client: DaemonClient;
|
||||||
|
audio: Pick<AudioEngine, "play"> | null;
|
||||||
|
connected: boolean;
|
||||||
|
supported: boolean;
|
||||||
|
registry: Pick<PluginRegistry, "installCatalog" | "getSnapshot" | "removeHost">;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function syncPluginCatalog({
|
||||||
|
serverId,
|
||||||
|
client,
|
||||||
|
audio,
|
||||||
|
connected,
|
||||||
|
supported,
|
||||||
|
registry,
|
||||||
|
}: CatalogSyncInput): () => void {
|
||||||
|
if (!supported || !audio) {
|
||||||
|
registry.removeHost(serverId);
|
||||||
|
return () => {};
|
||||||
|
}
|
||||||
|
// A dropped socket reconnects on the same client, so installations keep rendering offline.
|
||||||
|
if (!connected) return () => {};
|
||||||
|
const installationOptions = { client, audio };
|
||||||
|
let cancelled = false;
|
||||||
|
let refreshQueue = Promise.resolve();
|
||||||
|
function refresh(replacePluginId?: string) {
|
||||||
|
refreshQueue = refreshQueue.then(() =>
|
||||||
|
client
|
||||||
|
.getPluginCatalog()
|
||||||
|
.then((catalog) => {
|
||||||
|
if (!cancelled) {
|
||||||
|
registry.installCatalog(serverId, catalog, { ...installationOptions, replacePluginId });
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
if (!cancelled) {
|
||||||
|
console.warn(`[Plugins] Failed to load catalog for ${serverId}`, error);
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
return refreshQueue;
|
||||||
|
}
|
||||||
|
const observation = client.observeEvents([
|
||||||
|
"status.plugin_catalog_changed",
|
||||||
|
"status.plugin_settings_changed",
|
||||||
|
]);
|
||||||
|
observation.subscribe({
|
||||||
|
snapshot: () => {
|
||||||
|
void refresh().then(() => {
|
||||||
|
if (cancelled) return undefined;
|
||||||
|
// Retained replicas miss offline writes and do not refetch when a screen mounts.
|
||||||
|
for (const plugin of registry.getSnapshot()) {
|
||||||
|
if (plugin.serverId !== serverId) continue;
|
||||||
|
void plugin.queryClient.invalidateQueries({
|
||||||
|
queryKey: pluginSettingsPrefix,
|
||||||
|
refetchType: "all",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
});
|
||||||
|
},
|
||||||
|
update: (message) => {
|
||||||
|
if (message.type !== "status") return;
|
||||||
|
if (message.payload.status === "plugin_settings_changed") {
|
||||||
|
const { pluginId, settingsId } = message.payload;
|
||||||
|
if (typeof settingsId === "string") {
|
||||||
|
const plugin = registry
|
||||||
|
.getSnapshot()
|
||||||
|
.find((item) => item.serverId === serverId && item.id === pluginId);
|
||||||
|
void plugin?.queryClient.invalidateQueries({ queryKey: pluginSettingsKey(settingsId) });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (message.payload.status === "plugin_catalog_changed") {
|
||||||
|
const pluginId = message.payload.pluginId;
|
||||||
|
if (typeof pluginId === "string") void refresh(pluginId);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
void observation
|
||||||
|
.release()
|
||||||
|
.catch((error) => console.warn("[Plugins] Failed to release catalog", error));
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
import { useVoiceAudioEngineOptional } from "@/contexts/voice-context";
|
import { useVoiceAudioEngineOptional } from "@/contexts/voice-context";
|
||||||
import { pluginSettingsKey } from "./settings/use-settings";
|
|
||||||
import { useEffect } from "react";
|
import { useEffect } from "react";
|
||||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||||
import { useHostFeature } from "@/runtime/host-features";
|
import { useHostFeature } from "@/runtime/host-features";
|
||||||
import { useHostRuntimeIsConnected } from "@/runtime/host-runtime";
|
import { useHostRuntimeIsConnected } from "@/runtime/host-runtime";
|
||||||
import { pluginRegistry } from "./registry";
|
import { pluginRegistry } from "./registry";
|
||||||
|
import { syncPluginCatalog } from "./catalog-sync-model";
|
||||||
|
|
||||||
export function PluginCatalogSync({
|
export function PluginCatalogSync({
|
||||||
serverId,
|
serverId,
|
||||||
@@ -17,72 +17,18 @@ export function PluginCatalogSync({
|
|||||||
const connected = useHostRuntimeIsConnected(serverId);
|
const connected = useHostRuntimeIsConnected(serverId);
|
||||||
const supported = useHostFeature(serverId, "plugins");
|
const supported = useHostFeature(serverId, "plugins");
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(
|
||||||
let cancelled = false;
|
() =>
|
||||||
let refreshQueue = Promise.resolve();
|
syncPluginCatalog({
|
||||||
if (!supported || !audio) {
|
serverId,
|
||||||
pluginRegistry.removeHost(serverId);
|
client,
|
||||||
return;
|
audio,
|
||||||
}
|
connected,
|
||||||
if (!connected) {
|
supported,
|
||||||
pluginRegistry.removeHost(serverId);
|
registry: pluginRegistry,
|
||||||
return;
|
}),
|
||||||
}
|
[audio, client, connected, serverId, supported],
|
||||||
const refresh = (replacePluginId?: string) => {
|
);
|
||||||
refreshQueue = refreshQueue.then(() =>
|
|
||||||
client
|
|
||||||
.getPluginCatalog()
|
|
||||||
.then((catalog) => {
|
|
||||||
if (!cancelled) {
|
|
||||||
pluginRegistry.installCatalog(serverId, catalog, {
|
|
||||||
replacePluginId,
|
|
||||||
client,
|
|
||||||
audio,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return undefined;
|
|
||||||
})
|
|
||||||
.catch((error) => {
|
|
||||||
if (!cancelled) {
|
|
||||||
console.warn(`[Plugins] Failed to load catalog for ${serverId}`, error);
|
|
||||||
}
|
|
||||||
return undefined;
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
return refreshQueue;
|
|
||||||
};
|
|
||||||
const observation = client.observeEvents([
|
|
||||||
"status.plugin_catalog_changed",
|
|
||||||
"status.plugin_settings_changed",
|
|
||||||
]);
|
|
||||||
observation.subscribe({
|
|
||||||
snapshot: () => {
|
|
||||||
void refresh();
|
|
||||||
},
|
|
||||||
update: (message) => {
|
|
||||||
if (message.type !== "status") return;
|
|
||||||
if (message.payload.status === "plugin_settings_changed") {
|
|
||||||
const { pluginId, settingsId } = message.payload;
|
|
||||||
if (typeof settingsId === "string") {
|
|
||||||
const plugin = pluginRegistry
|
|
||||||
.getSnapshot()
|
|
||||||
.find((item) => item.serverId === serverId && item.id === pluginId);
|
|
||||||
void plugin?.queryClient.invalidateQueries({ queryKey: pluginSettingsKey(settingsId) });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (message.payload.status === "plugin_catalog_changed") {
|
|
||||||
const pluginId = message.payload.pluginId;
|
|
||||||
if (typeof pluginId === "string") void refresh(pluginId);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
});
|
|
||||||
return () => {
|
|
||||||
cancelled = true;
|
|
||||||
void observation
|
|
||||||
.release()
|
|
||||||
.catch((error) => console.warn("[Plugins] Failed to release catalog", error));
|
|
||||||
};
|
|
||||||
}, [audio, client, connected, serverId, supported]);
|
|
||||||
|
|
||||||
useEffect(() => () => pluginRegistry.removeHost(serverId), [serverId]);
|
useEffect(() => () => pluginRegistry.removeHost(serverId), [serverId]);
|
||||||
return null;
|
return null;
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import * as FileSystem from "expo-file-system/legacy";
|
||||||
|
import { CryptoDigestAlgorithm, digestStringAsync, randomUUID } from "expo-crypto";
|
||||||
|
import { createPluginClientBundleStore } from "./store";
|
||||||
|
|
||||||
|
export function createHostPluginClientBundleStore(serverId: string) {
|
||||||
|
const directory = `${FileSystem.cacheDirectory}plugin-client-bundles/${encodeURIComponent(serverId)}/`;
|
||||||
|
const ensureDirectory = async () => {
|
||||||
|
if (!FileSystem.cacheDirectory) throw new Error("Plugin bundle cache directory unavailable");
|
||||||
|
await FileSystem.makeDirectoryAsync(directory, { intermediates: true });
|
||||||
|
};
|
||||||
|
return createPluginClientBundleStore(
|
||||||
|
{
|
||||||
|
async list() {
|
||||||
|
await ensureDirectory();
|
||||||
|
return FileSystem.readDirectoryAsync(directory);
|
||||||
|
},
|
||||||
|
read: (name) => FileSystem.readAsStringAsync(`${directory}${name}`),
|
||||||
|
async writeAtomic(name, contents) {
|
||||||
|
await ensureDirectory();
|
||||||
|
const temporary = `${directory}${randomUUID()}.tmp`;
|
||||||
|
try {
|
||||||
|
await FileSystem.writeAsStringAsync(temporary, contents);
|
||||||
|
await FileSystem.moveAsync({ from: temporary, to: `${directory}${name}` });
|
||||||
|
} finally {
|
||||||
|
await FileSystem.deleteAsync(temporary, { idempotent: true });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
remove: (name) => FileSystem.deleteAsync(`${directory}${name}`, { idempotent: true }),
|
||||||
|
},
|
||||||
|
(contents) => digestStringAsync(CryptoDigestAlgorithm.SHA256, contents),
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
import { createPluginClientBundleStore } from "./store";
|
||||||
|
|
||||||
|
const DATABASE_NAME = "paseo-plugin-client-bundles";
|
||||||
|
const STORE_NAME = "bundles";
|
||||||
|
let opening: Promise<IDBDatabase> | undefined;
|
||||||
|
|
||||||
|
function openDatabase(): Promise<IDBDatabase> {
|
||||||
|
opening ??= new Promise<IDBDatabase>((resolve, reject) => {
|
||||||
|
const request = indexedDB.open(DATABASE_NAME, 1);
|
||||||
|
request.addEventListener("upgradeneeded", () => request.result.createObjectStore(STORE_NAME));
|
||||||
|
request.addEventListener("success", () => resolve(request.result));
|
||||||
|
request.addEventListener("error", () => reject(request.error));
|
||||||
|
}).catch((error) => {
|
||||||
|
opening = undefined;
|
||||||
|
throw error;
|
||||||
|
});
|
||||||
|
return opening;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createHostPluginClientBundleStore(serverId: string) {
|
||||||
|
const prefix = `${encodeURIComponent(serverId)}/`;
|
||||||
|
const range = () => IDBKeyRange.bound(prefix, `${prefix}\uffff`);
|
||||||
|
async function run<T>(
|
||||||
|
mode: IDBTransactionMode,
|
||||||
|
operation: (store: IDBObjectStore) => IDBRequest<T>,
|
||||||
|
): Promise<T> {
|
||||||
|
const database = await openDatabase();
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const transaction = database.transaction(STORE_NAME, mode);
|
||||||
|
const request = operation(transaction.objectStore(STORE_NAME));
|
||||||
|
transaction.addEventListener("complete", () => resolve(request.result));
|
||||||
|
transaction.addEventListener("abort", () => reject(transaction.error));
|
||||||
|
transaction.addEventListener("error", () => reject(transaction.error));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return createPluginClientBundleStore(
|
||||||
|
{
|
||||||
|
async list() {
|
||||||
|
return (await run("readonly", (store) => store.getAllKeys(range())))
|
||||||
|
.filter((key): key is string => typeof key === "string")
|
||||||
|
.map((key) => key.slice(prefix.length));
|
||||||
|
},
|
||||||
|
async read(name) {
|
||||||
|
const result: unknown = await run("readonly", (store) => store.get(`${prefix}${name}`));
|
||||||
|
if (typeof result !== "string") throw new Error("Missing plugin client bundle");
|
||||||
|
return result;
|
||||||
|
},
|
||||||
|
async writeAtomic(name, contents) {
|
||||||
|
await run("readwrite", (store) => store.put(contents, `${prefix}${name}`));
|
||||||
|
},
|
||||||
|
async remove(name) {
|
||||||
|
await run("readwrite", (store) => store.delete(`${prefix}${name}`));
|
||||||
|
},
|
||||||
|
},
|
||||||
|
async (contents) => {
|
||||||
|
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(contents));
|
||||||
|
return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join(
|
||||||
|
"",
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import { expect, test } from "vitest";
|
||||||
|
import { createHostPluginClientBundleStore } from "./index.web";
|
||||||
|
|
||||||
|
async function sha256(contents: string) {
|
||||||
|
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(contents));
|
||||||
|
return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
||||||
|
}
|
||||||
|
|
||||||
|
test("browser bundles survive a fresh store and remain isolated by host", async () => {
|
||||||
|
const first = createHostPluginClientBundleStore("bundle-test-host-a");
|
||||||
|
const second = createHostPluginClientBundleStore("bundle-test-host-b");
|
||||||
|
const clientBundle = "bundle".repeat(250_000);
|
||||||
|
const entry = {
|
||||||
|
id: "same-plugin",
|
||||||
|
clientBundle,
|
||||||
|
clientBundleHash: await sha256(clientBundle),
|
||||||
|
};
|
||||||
|
const otherCode = "other host code";
|
||||||
|
const other = {
|
||||||
|
id: entry.id,
|
||||||
|
clientBundle: otherCode,
|
||||||
|
clientBundleHash: await sha256(otherCode),
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
await first.replace([entry]);
|
||||||
|
await second.replace([other]);
|
||||||
|
expect(await createHostPluginClientBundleStore("bundle-test-host-a").load()).toEqual([entry]);
|
||||||
|
expect(await createHostPluginClientBundleStore("bundle-test-host-b").load()).toEqual([other]);
|
||||||
|
await first.replace([]);
|
||||||
|
expect(await createHostPluginClientBundleStore("bundle-test-host-a").load()).toEqual([]);
|
||||||
|
expect(await second.load()).toEqual([other]);
|
||||||
|
} finally {
|
||||||
|
await first.replace([]);
|
||||||
|
await second.replace([]);
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,179 @@
|
|||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||||
|
import { expect, test } from "vitest";
|
||||||
|
import { createPluginClientBundleStore, type PluginBundleFiles } from "./store";
|
||||||
|
|
||||||
|
const sha256 = async (contents: string) => createHash("sha256").update(contents).digest("hex");
|
||||||
|
|
||||||
|
class BundleFiles implements PluginBundleFiles {
|
||||||
|
readonly contents = new Map<string, string>();
|
||||||
|
readonly writes: string[] = [];
|
||||||
|
async list() {
|
||||||
|
return [...this.contents.keys()];
|
||||||
|
}
|
||||||
|
async read(name: string) {
|
||||||
|
const contents = this.contents.get(name);
|
||||||
|
if (contents === undefined) throw new Error("File disappeared");
|
||||||
|
return contents;
|
||||||
|
}
|
||||||
|
async writeAtomic(name: string, contents: string) {
|
||||||
|
this.writes.push(name);
|
||||||
|
this.contents.set(name, contents);
|
||||||
|
}
|
||||||
|
async remove(name: string) {
|
||||||
|
this.contents.delete(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function bundle(id: string, clientBundle: string) {
|
||||||
|
return { id, clientBundle, clientBundleHash: await sha256(clientBundle) };
|
||||||
|
}
|
||||||
|
|
||||||
|
test("a cold store loads verified bundles and prunes versions missing from the latest catalog", async () => {
|
||||||
|
const files = new BundleFiles();
|
||||||
|
const old = await bundle("changed", "old");
|
||||||
|
const kept = await bundle("kept", "Unicode: 折叠屏 🐚");
|
||||||
|
await createPluginClientBundleStore(files, sha256).replace([old, kept]);
|
||||||
|
const cold = createPluginClientBundleStore(files, sha256);
|
||||||
|
expect(await cold.load()).toEqual([old, kept]);
|
||||||
|
const changed = await bundle("changed", "new");
|
||||||
|
await cold.replace([kept, changed]);
|
||||||
|
expect(files.contents.size).toBe(2);
|
||||||
|
expect(await createPluginClientBundleStore(files, sha256).load()).toEqual([kept, changed]);
|
||||||
|
expect(files.writes).toHaveLength(3);
|
||||||
|
await cold.replace([]);
|
||||||
|
expect(files.contents.size).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("same-length corruption, truncated files and unreadable files are not advertised", async () => {
|
||||||
|
const files = new BundleFiles();
|
||||||
|
const entries = await Promise.all([
|
||||||
|
bundle("same-length", "good"),
|
||||||
|
bundle("truncated", "long"),
|
||||||
|
bundle("missing", "lost"),
|
||||||
|
]);
|
||||||
|
await createPluginClientBundleStore(files, sha256).replace(entries);
|
||||||
|
const names = [...files.contents.keys()];
|
||||||
|
files.contents.set(names[0]!, "evil");
|
||||||
|
files.contents.set(names[1]!, "lo");
|
||||||
|
// The directory entry still exists while reading the file fails.
|
||||||
|
const unreadable: PluginBundleFiles = {
|
||||||
|
list: () => files.list(),
|
||||||
|
read: (name) =>
|
||||||
|
name === names[2] ? Promise.reject(new Error("Unreadable")) : files.read(name),
|
||||||
|
writeAtomic: (name, contents) => files.writeAtomic(name, contents),
|
||||||
|
remove: (name) => files.remove(name),
|
||||||
|
};
|
||||||
|
const cold = createPluginClientBundleStore(unreadable, sha256);
|
||||||
|
expect(await cold.load()).toEqual([]);
|
||||||
|
await cold.replace(entries);
|
||||||
|
expect(await createPluginClientBundleStore(files, sha256).load()).toEqual(entries);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("an interrupted atomic write leaves the prior catalog available for a cold reader", async () => {
|
||||||
|
const files = new BundleFiles();
|
||||||
|
const previous = await bundle("plugin", "previous");
|
||||||
|
await createPluginClientBundleStore(files, sha256).replace([previous]);
|
||||||
|
const failing: PluginBundleFiles = {
|
||||||
|
list: () => files.list(),
|
||||||
|
read: (name) => files.read(name),
|
||||||
|
remove: (name) => files.remove(name),
|
||||||
|
writeAtomic: async () => {
|
||||||
|
throw new Error("Disk full");
|
||||||
|
},
|
||||||
|
};
|
||||||
|
await expect(
|
||||||
|
createPluginClientBundleStore(failing, sha256).replace([await bundle("plugin", "next")]),
|
||||||
|
).rejects.toThrow("Disk full");
|
||||||
|
expect(await createPluginClientBundleStore(files, sha256).load()).toEqual([previous]);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Exercise the app store through a fresh platform-agnostic client, using its transport port.
|
||||||
|
test.each(["valid", "corrupt", "missing"])(
|
||||||
|
"cold catalog uses a %s persisted bundle correctly",
|
||||||
|
async (state) => {
|
||||||
|
const files = new BundleFiles();
|
||||||
|
const entry = await bundle("plugin", "good code");
|
||||||
|
await createPluginClientBundleStore(files, sha256).replace([entry]);
|
||||||
|
if (state === "corrupt") files.contents.set([...files.contents.keys()][0]!, "evil code");
|
||||||
|
if (state === "missing") files.contents.clear();
|
||||||
|
let open = () => {};
|
||||||
|
let receive: (data: unknown, binary: boolean) => void = () => {};
|
||||||
|
const requests: Record<string, unknown>[] = [];
|
||||||
|
const client = new DaemonClient({
|
||||||
|
url: "ws://test",
|
||||||
|
clientId: "plugin-cache-test",
|
||||||
|
reconnect: { enabled: false },
|
||||||
|
createPluginClientBundleStore: () => createPluginClientBundleStore(files, sha256),
|
||||||
|
transportFactory: () => ({
|
||||||
|
send(data) {
|
||||||
|
if (typeof data !== "string") return;
|
||||||
|
const frame = JSON.parse(data);
|
||||||
|
if (frame.type !== "session") return;
|
||||||
|
const request = frame.message;
|
||||||
|
if (request.type !== "plugin.catalog.get.request") return;
|
||||||
|
requests.push(request);
|
||||||
|
const { clientBundle: _code, ...reference } = entry;
|
||||||
|
receive(
|
||||||
|
JSON.stringify({
|
||||||
|
type: "session",
|
||||||
|
message: {
|
||||||
|
type: "plugin.catalog.get.response",
|
||||||
|
payload: {
|
||||||
|
requestId: request.requestId,
|
||||||
|
plugins: [request.cachedClientBundles ? reference : entry],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
close() {},
|
||||||
|
onOpen(handler) {
|
||||||
|
open = handler;
|
||||||
|
return () => {};
|
||||||
|
},
|
||||||
|
onMessage(handler) {
|
||||||
|
receive = handler;
|
||||||
|
return () => {};
|
||||||
|
},
|
||||||
|
onClose() {
|
||||||
|
return () => {};
|
||||||
|
},
|
||||||
|
onError() {
|
||||||
|
return () => {};
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
const connecting = client.connect();
|
||||||
|
open();
|
||||||
|
receive(
|
||||||
|
JSON.stringify({
|
||||||
|
type: "session",
|
||||||
|
message: {
|
||||||
|
type: "status",
|
||||||
|
payload: {
|
||||||
|
status: "server_info",
|
||||||
|
serverId: "cache-host",
|
||||||
|
hostname: null,
|
||||||
|
version: null,
|
||||||
|
features: { plugins: true },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
await connecting;
|
||||||
|
expect(await client.getPluginCatalog()).toEqual([entry]);
|
||||||
|
if (state === "valid")
|
||||||
|
expect(requests[0]?.cachedClientBundles).toEqual([
|
||||||
|
{ id: entry.id, clientBundleHash: entry.clientBundleHash },
|
||||||
|
]);
|
||||||
|
else expect(requests[0]).not.toHaveProperty("cachedClientBundles");
|
||||||
|
await expect.poll(() => createPluginClientBundleStore(files, sha256).load()).toEqual([entry]);
|
||||||
|
} finally {
|
||||||
|
await client.close();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
import type {
|
||||||
|
PluginClientBundle,
|
||||||
|
PluginClientBundleStore,
|
||||||
|
} from "@getpaseo/client/internal/daemon-client";
|
||||||
|
|
||||||
|
/** Each adapter is scoped to one host. Writes publish a complete file/record atomically. */
|
||||||
|
export interface PluginBundleFiles {
|
||||||
|
list(): Promise<string[]>;
|
||||||
|
read(name: string): Promise<string>;
|
||||||
|
writeAtomic(name: string, contents: string): Promise<void>;
|
||||||
|
remove(name: string): Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createPluginClientBundleStore(
|
||||||
|
files: PluginBundleFiles,
|
||||||
|
sha256: (contents: string) => Promise<string>,
|
||||||
|
): PluginClientBundleStore {
|
||||||
|
const verified = new Set<string>();
|
||||||
|
const filename = (bundle: PluginClientBundle) =>
|
||||||
|
`${encodeURIComponent(bundle.id)}.${bundle.clientBundleHash}.js`;
|
||||||
|
return {
|
||||||
|
async load() {
|
||||||
|
const bundles: PluginClientBundle[] = [];
|
||||||
|
for (const name of await files.list()) {
|
||||||
|
try {
|
||||||
|
const match = /^(.*)\.([a-f0-9]{64})\.js$/.exec(name);
|
||||||
|
if (!match) continue;
|
||||||
|
const id = decodeURIComponent(match[1]!);
|
||||||
|
const clientBundleHash = match[2]!;
|
||||||
|
const clientBundle = await files.read(name);
|
||||||
|
if ((await sha256(clientBundle)) !== clientBundleHash) continue;
|
||||||
|
verified.add(name);
|
||||||
|
bundles.push({ id, clientBundleHash, clientBundle });
|
||||||
|
} catch {
|
||||||
|
// Missing, unreadable or corrupt files are cache misses, never executable code.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return bundles;
|
||||||
|
},
|
||||||
|
async replace(bundles) {
|
||||||
|
const retained = new Set<string>();
|
||||||
|
for (const bundle of bundles) {
|
||||||
|
const name = filename(bundle);
|
||||||
|
retained.add(name);
|
||||||
|
if (verified.has(name)) continue;
|
||||||
|
await files.writeAtomic(name, bundle.clientBundle);
|
||||||
|
verified.add(name);
|
||||||
|
}
|
||||||
|
for (const name of await files.list()) {
|
||||||
|
if (retained.has(name)) continue;
|
||||||
|
await files.remove(name);
|
||||||
|
verified.delete(name);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -219,7 +219,10 @@ test("locale snapshots preserve installation state and observations, then releas
|
|||||||
expect(after.paseo).toBe(before.paseo);
|
expect(after.paseo).toBe(before.paseo);
|
||||||
expect(after.surfaces[0].Component).toBe(before.surfaces[0].Component);
|
expect(after.surfaces[0].Component).toBe(before.surfaces[0].Component);
|
||||||
expect(h.open).toEqual(new Set(["notes"]));
|
expect(h.open).toEqual(new Set(["notes"]));
|
||||||
|
const translatedSnapshot = h.plugins.getSnapshot();
|
||||||
h.plugins.installCatalog("host", [translated], { client: h.client, audio });
|
h.plugins.installCatalog("host", [translated], { client: h.client, audio });
|
||||||
|
expect(h.plugins.getSnapshot()).toBe(translatedSnapshot);
|
||||||
|
expect(h.plugins.getSnapshot()[0].locale).toBe("zh-CN");
|
||||||
expect(h.plugins.getSnapshot()[0].i18n).toBe(before.i18n);
|
expect(h.plugins.getSnapshot()[0].i18n).toBe(before.i18n);
|
||||||
h.plugins.removeHost("host");
|
h.plugins.removeHost("host");
|
||||||
expect(listeners.size).toBe(0);
|
expect(listeners.size).toBe(0);
|
||||||
|
|||||||
@@ -27,12 +27,12 @@ const pluginRegistry = {
|
|||||||
installCatalog(
|
installCatalog(
|
||||||
serverId: string,
|
serverId: string,
|
||||||
catalog: Parameters<typeof registry.installCatalog>[1],
|
catalog: Parameters<typeof registry.installCatalog>[1],
|
||||||
options: { replacePluginId?: string } = {},
|
options: { replacePluginId?: string; client?: DaemonClient } = {},
|
||||||
) {
|
) {
|
||||||
return registry.installCatalog(
|
return registry.installCatalog(
|
||||||
serverId,
|
serverId,
|
||||||
catalog.map((entry) => ({ ...entry, requirements: { paseo: `>=${appPackage.version}` } })),
|
catalog.map((entry) => ({ ...entry, requirements: { paseo: `>=${appPackage.version}` } })),
|
||||||
{ ...options, client: daemonClient, audio },
|
{ client: daemonClient, ...options, audio },
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
@@ -118,6 +118,37 @@ describe("PluginRegistry", () => {
|
|||||||
expect(second?.queryClient.getQueryData(["counter"])).toBe(3);
|
expect(second?.queryClient.getQueryData(["counter"])).toBe(3);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("keeps the snapshot when the same catalog is installed again", () => {
|
||||||
|
const clientBundle = timelineBundle("one");
|
||||||
|
pluginRegistry.installCatalog("host-a", [{ id: "reports", clientBundle }]);
|
||||||
|
const snapshot = pluginRegistry.getSnapshot();
|
||||||
|
const transformers = snapshot[0]?.timelineTransformers;
|
||||||
|
const listener = vi.fn();
|
||||||
|
const unsubscribe = pluginRegistry.subscribe(listener);
|
||||||
|
|
||||||
|
pluginRegistry.installCatalog("host-a", [{ id: "reports", clientBundle }]);
|
||||||
|
unsubscribe();
|
||||||
|
|
||||||
|
expect(pluginRegistry.getSnapshot()).toBe(snapshot);
|
||||||
|
expect(pluginRegistry.getSnapshot()[0]?.timelineTransformers).toBe(transformers);
|
||||||
|
expect(listener).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reinstalls an unchanged bundle for a new host client", () => {
|
||||||
|
const clientBundle = bundle("one");
|
||||||
|
pluginRegistry.installCatalog("host-a", [{ id: "example", clientBundle }]);
|
||||||
|
const first = pluginRegistry.getSnapshot()[0];
|
||||||
|
|
||||||
|
pluginRegistry.installCatalog("host-a", [{ id: "example", clientBundle }], {
|
||||||
|
client: {} as DaemonClient,
|
||||||
|
});
|
||||||
|
|
||||||
|
const second = pluginRegistry.getSnapshot()[0];
|
||||||
|
expect(second).not.toBe(first);
|
||||||
|
expect(first?.lifetime.signal.aborted).toBe(true);
|
||||||
|
expect(Reflect.get(globalThis, "__pluginCleanups")).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
it("replaces the query cache when the plugin bundle changes", () => {
|
it("replaces the query cache when the plugin bundle changes", () => {
|
||||||
pluginRegistry.installCatalog("host-a", [{ id: "example", clientBundle: bundle("one") }]);
|
pluginRegistry.installCatalog("host-a", [{ id: "example", clientBundle: bundle("one") }]);
|
||||||
const first = pluginRegistry.getSnapshot()[0];
|
const first = pluginRegistry.getSnapshot()[0];
|
||||||
|
|||||||
@@ -19,6 +19,8 @@ export class PluginRegistry {
|
|||||||
private snapshot: InstalledPlugin[] = [];
|
private snapshot: InstalledPlugin[] = [];
|
||||||
private readonly disposed = new WeakSet<InstalledPlugin>();
|
private readonly disposed = new WeakSet<InstalledPlugin>();
|
||||||
private readonly evaluationErrors = new Map<string, string>();
|
private readonly evaluationErrors = new Map<string, string>();
|
||||||
|
/** The client each host's installations were bound to; their Paseo API and RPCs call it. */
|
||||||
|
private readonly clientByHost = new Map<string, DaemonClient>();
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly dependencies: {
|
private readonly dependencies: {
|
||||||
@@ -49,10 +51,15 @@ export class PluginRegistry {
|
|||||||
},
|
},
|
||||||
): boolean {
|
): boolean {
|
||||||
const previous = this.byHost.get(serverId) ?? [];
|
const previous = this.byHost.get(serverId) ?? [];
|
||||||
|
const previousErrors = this.hostEvaluationErrors(serverId);
|
||||||
|
// Installations call the client they were created with, so a new client replaces them all.
|
||||||
|
const sameClient = this.clientByHost.get(serverId) === options.client;
|
||||||
|
this.clientByHost.set(serverId, options.client);
|
||||||
const previousTimelineBundles = previous
|
const previousTimelineBundles = previous
|
||||||
.filter((plugin) => plugin.timelineTransformers.length > 0)
|
.filter((plugin) => plugin.timelineTransformers.length > 0)
|
||||||
.map((plugin) => `${plugin.id}\0${plugin.clientBundle}`);
|
.map((plugin) => `${plugin.id}\0${plugin.clientBundle}`);
|
||||||
const preserved = catalog.flatMap((entry) => {
|
const preserved = catalog.flatMap((entry) => {
|
||||||
|
if (!sameClient) return [];
|
||||||
const existing = previous.find(
|
const existing = previous.find(
|
||||||
(plugin) =>
|
(plugin) =>
|
||||||
plugin.id !== options.replacePluginId &&
|
plugin.id !== options.replacePluginId &&
|
||||||
@@ -146,13 +153,13 @@ export class PluginRegistry {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
this.byHost.set(serverId, installed);
|
this.byHost.set(serverId, installed);
|
||||||
if (
|
// An unchanged catalog keeps the snapshot, so timeline projections cached against the
|
||||||
installed.length !== catalog.length ||
|
// installed transformers stay valid across a reconnect.
|
||||||
installed.length !== previous.length ||
|
const unchanged =
|
||||||
installed.some((plugin, index) => plugin !== previous[index])
|
installed.length === previous.length &&
|
||||||
) {
|
installed.every((plugin, index) => plugin === previous[index]) &&
|
||||||
this.publish();
|
this.hostEvaluationErrors(serverId) === previousErrors;
|
||||||
}
|
if (!unchanged) this.publish();
|
||||||
const installedTimelineBundles = installed
|
const installedTimelineBundles = installed
|
||||||
.filter((plugin) => plugin.timelineTransformers.length > 0)
|
.filter((plugin) => plugin.timelineTransformers.length > 0)
|
||||||
.map((plugin) => `${plugin.id}\0${plugin.clientBundle}`);
|
.map((plugin) => `${plugin.id}\0${plugin.clientBundle}`);
|
||||||
@@ -170,9 +177,17 @@ export class PluginRegistry {
|
|||||||
if (key.startsWith(`${serverId}/`)) this.evaluationErrors.delete(key);
|
if (key.startsWith(`${serverId}/`)) this.evaluationErrors.delete(key);
|
||||||
}
|
}
|
||||||
this.byHost.delete(serverId);
|
this.byHost.delete(serverId);
|
||||||
|
this.clientByHost.delete(serverId);
|
||||||
this.publish();
|
this.publish();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private hostEvaluationErrors(serverId: string): string {
|
||||||
|
const prefix = `${serverId}/`;
|
||||||
|
return JSON.stringify(
|
||||||
|
[...this.evaluationErrors].filter(([key]) => key.startsWith(prefix)).sort(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
private dispose(plugin: InstalledPlugin): void {
|
private dispose(plugin: InstalledPlugin): void {
|
||||||
if (this.disposed.has(plugin)) return;
|
if (this.disposed.has(plugin)) return;
|
||||||
this.disposed.add(plugin);
|
this.disposed.add(plugin);
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
export const pluginSettingsPrefix = ["plugin-settings"] as const;
|
||||||
|
export const pluginSettingsKey = (id: string) => [...pluginSettingsPrefix, id] as const;
|
||||||
@@ -6,8 +6,8 @@ import { type SettingsDefinition } from "@getpaseo/plugin";
|
|||||||
import { settingsRpc } from "@getpaseo/plugin";
|
import { settingsRpc } from "@getpaseo/plugin";
|
||||||
import { useReplicaQuery } from "@/data/query";
|
import { useReplicaQuery } from "@/data/query";
|
||||||
import { z, type ZodType } from "zod";
|
import { z, type ZodType } from "zod";
|
||||||
|
import { pluginSettingsKey } from "./query";
|
||||||
|
|
||||||
export const pluginSettingsKey = (id: string) => ["plugin-settings", id] as const;
|
|
||||||
function message(error: unknown): string {
|
function message(error: unknown): string {
|
||||||
if (error instanceof z.ZodError) return error.issues.map((issue) => issue.message).join("\n");
|
if (error instanceof z.ZodError) return error.issues.map((issue) => issue.message).join("\n");
|
||||||
return error instanceof Error ? error.message : String(error);
|
return error instanceof Error ? error.message : String(error);
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { createHostPluginClientBundleStore } from "@/plugins/client-bundles";
|
||||||
import { watchdog } from "@/watchdog";
|
import { watchdog } from "@/watchdog";
|
||||||
import { createHostChannelTransport } from "@getpaseo/client/internal/hosts";
|
import { createHostChannelTransport } from "@getpaseo/client/internal/hosts";
|
||||||
import type { OwnedSubscription } from "@getpaseo/client";
|
import type { OwnedSubscription } from "@getpaseo/client";
|
||||||
@@ -589,6 +590,7 @@ function createDefaultDeps(
|
|||||||
capabilities: appCapabilities,
|
capabilities: appCapabilities,
|
||||||
trace: createPerformanceTrace({ host: host.serverId, connection: connection.id }),
|
trace: createPerformanceTrace({ host: host.serverId, connection: connection.id }),
|
||||||
providerSnapshots: "wire",
|
providerSnapshots: "wire",
|
||||||
|
createPluginClientBundleStore: createHostPluginClientBundleStore,
|
||||||
...(host.password ? { password: host.password } : {}),
|
...(host.password ? { password: host.password } : {}),
|
||||||
localCredential: () => readDesktopManagedLocalCredential(connection),
|
localCredential: () => readDesktopManagedLocalCredential(connection),
|
||||||
} satisfies Omit<DaemonClientConfig, "url">;
|
} satisfies Omit<DaemonClientConfig, "url">;
|
||||||
@@ -668,6 +670,7 @@ function createDefaultDeps(
|
|||||||
),
|
),
|
||||||
reconnect: { enabled: false },
|
reconnect: { enabled: false },
|
||||||
appVersion: resolveAppVersion() ?? undefined,
|
appVersion: resolveAppVersion() ?? undefined,
|
||||||
|
createPluginClientBundleStore: createHostPluginClientBundleStore,
|
||||||
});
|
});
|
||||||
try {
|
try {
|
||||||
await client.connect();
|
await client.connect();
|
||||||
@@ -684,6 +687,7 @@ function createDefaultDeps(
|
|||||||
...(timeoutMs !== undefined ? { timeoutMs } : {}),
|
...(timeoutMs !== undefined ? { timeoutMs } : {}),
|
||||||
capabilities: appCapabilities,
|
capabilities: appCapabilities,
|
||||||
trace: createPerformanceTrace({ host: host.serverId, connection: connection.id }),
|
trace: createPerformanceTrace({ host: host.serverId, connection: connection.id }),
|
||||||
|
createPluginClientBundleStore: createHostPluginClientBundleStore,
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
getClientId: () => getOrCreateClientId(),
|
getClientId: () => getOrCreateClientId(),
|
||||||
|
|||||||
@@ -12,6 +12,69 @@ test("settings restart completes when a replacement worker is observed without a
|
|||||||
expect(pid).toBe(11);
|
expect(pid).toBe(11);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("settings restart keeps terminals by default and closes them only when asked", async () => {
|
||||||
|
let pid = 10;
|
||||||
|
const requests: Array<{ killTerminals: boolean }> = [];
|
||||||
|
const deps = {
|
||||||
|
getStatus: async () => ({ pid, version: "1.0.0", serverId: "daemon" }),
|
||||||
|
restartServer: async (_reason: string, options: { killTerminals: boolean }) => {
|
||||||
|
requests.push(options);
|
||||||
|
pid += 1;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
await restartDaemonFromSettings("daemon", "settings", deps);
|
||||||
|
await restartDaemonFromSettings("daemon", "settings", deps, { killTerminals: true });
|
||||||
|
expect(requests).toEqual([{ killTerminals: false }, { killTerminals: true }]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a close-terminals restart completes when the replacement reports every terminal closed", async () => {
|
||||||
|
let pid = 10;
|
||||||
|
await restartDaemonFromSettings(
|
||||||
|
"daemon",
|
||||||
|
"settings",
|
||||||
|
{
|
||||||
|
getStatus: async () => ({
|
||||||
|
pid,
|
||||||
|
version: "1.0.0",
|
||||||
|
serverId: "daemon",
|
||||||
|
terminalCleanupUnconfirmed: [],
|
||||||
|
}),
|
||||||
|
restartServer: async () => {
|
||||||
|
pid = 11;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ killTerminals: true },
|
||||||
|
);
|
||||||
|
expect(pid).toBe(11);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a close-terminals restart fails with the processes the replacement could not confirm closed", async () => {
|
||||||
|
let pid = 10;
|
||||||
|
const leftover = {
|
||||||
|
pid: 4242,
|
||||||
|
role: "terminal program",
|
||||||
|
reason: "still alive",
|
||||||
|
detail: "survived SIGKILL",
|
||||||
|
};
|
||||||
|
const deps = {
|
||||||
|
getStatus: async () => ({
|
||||||
|
pid,
|
||||||
|
version: "1.0.0",
|
||||||
|
serverId: "daemon",
|
||||||
|
terminalCleanupUnconfirmed: pid === 10 ? [] : [leftover],
|
||||||
|
}),
|
||||||
|
restartServer: async () => {
|
||||||
|
pid += 1;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
restartDaemonFromSettings("daemon", "settings", deps, { killTerminals: true }),
|
||||||
|
).rejects.toThrow("pid 4242 (terminal program): still alive (survived SIGKILL)");
|
||||||
|
// Keeping terminals asks nothing of the cleanup, so a leftover does not fail it.
|
||||||
|
await restartDaemonFromSettings("daemon", "settings", deps);
|
||||||
|
});
|
||||||
|
|
||||||
test("a status permission failure prevents the restart request", async () => {
|
test("a status permission failure prevents the restart request", async () => {
|
||||||
let restarted = false;
|
let restarted = false;
|
||||||
await expect(
|
await expect(
|
||||||
|
|||||||
@@ -1,35 +1,61 @@
|
|||||||
|
interface UnconfirmedTerminalProcess {
|
||||||
|
pid: number;
|
||||||
|
role: string;
|
||||||
|
reason: string;
|
||||||
|
detail: string;
|
||||||
|
}
|
||||||
interface WorkerStatus {
|
interface WorkerStatus {
|
||||||
pid: number;
|
pid: number;
|
||||||
serverId: string;
|
serverId: string;
|
||||||
version: string | null;
|
version: string | null;
|
||||||
|
// Absent on daemons without terminalsSurviveRestart, which have no terminal cleanup to report.
|
||||||
|
terminalCleanupUnconfirmed?: UnconfirmedTerminalProcess[];
|
||||||
}
|
}
|
||||||
interface StatusReader {
|
interface StatusReader {
|
||||||
getStatus: () => Promise<WorkerStatus>;
|
getStatus: () => Promise<WorkerStatus>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface SettingsDaemonRestartDeps extends StatusReader {
|
export interface SettingsDaemonRestartDeps extends StatusReader {
|
||||||
restartServer: (reason: string) => Promise<unknown>;
|
restartServer: (reason: string, options: { killTerminals: boolean }) => Promise<unknown>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Acknowledgment starts the wait; only a different ready worker completes it. */
|
/**
|
||||||
|
* Acknowledgment starts the wait; only a different ready worker completes it. Terminals survive
|
||||||
|
* the restart unless `killTerminals` is set (daemons advertising terminalsSurviveRestart); then
|
||||||
|
* the replacement must also report every terminal process gone.
|
||||||
|
*/
|
||||||
export async function restartDaemonFromSettings(
|
export async function restartDaemonFromSettings(
|
||||||
hostServerId: string,
|
hostServerId: string,
|
||||||
reason: string,
|
reason: string,
|
||||||
deps: SettingsDaemonRestartDeps,
|
deps: SettingsDaemonRestartDeps,
|
||||||
|
options: { killTerminals: boolean } = { killTerminals: false },
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const previous = await readSelectedWorker(hostServerId, deps);
|
const previous = await readSelectedWorker(hostServerId, deps);
|
||||||
let acknowledged = false;
|
let acknowledged = false;
|
||||||
try {
|
try {
|
||||||
await deps.restartServer(reason);
|
await deps.restartServer(reason, options);
|
||||||
acknowledged = true;
|
acknowledged = true;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (!isReconnectFailure(error)) throw error;
|
if (!isReconnectFailure(error)) throw error;
|
||||||
}
|
}
|
||||||
|
let replacement: WorkerStatus;
|
||||||
try {
|
try {
|
||||||
await observeReplacement(previous, deps);
|
replacement = await observeReplacement(previous, deps);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw new Error(`Restart acknowledged: ${acknowledged}. ${String(error)}`, { cause: error });
|
throw new Error(`Restart acknowledged: ${acknowledged}. ${String(error)}`, { cause: error });
|
||||||
}
|
}
|
||||||
|
const unconfirmed = replacement.terminalCleanupUnconfirmed ?? [];
|
||||||
|
if (options.killTerminals && unconfirmed.length > 0) {
|
||||||
|
throw new Error(
|
||||||
|
[
|
||||||
|
"The daemon restarted, but closing its terminals was not confirmed; these processes may still be running:",
|
||||||
|
...unconfirmed.map(
|
||||||
|
(entry) => `pid ${entry.pid} (${entry.role}): ${entry.reason} (${entry.detail})`,
|
||||||
|
),
|
||||||
|
"Stopping the daemon retries the cleanup.",
|
||||||
|
].join("\n"),
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function updateDaemonFromSettings(
|
export async function updateDaemonFromSettings(
|
||||||
|
|||||||
@@ -65,6 +65,7 @@ import { ICON_SIZE } from "@/styles/theme";
|
|||||||
import type { Theme } from "@/styles/theme";
|
import type { Theme } from "@/styles/theme";
|
||||||
import { useProviderIcon } from "@/components/provider-icons";
|
import { useProviderIcon } from "@/components/provider-icons";
|
||||||
import { BrowserToolsOptInCard } from "./browser-tools-card";
|
import { BrowserToolsOptInCard } from "./browser-tools-card";
|
||||||
|
import { RestartRecoveryCard } from "./restart-recovery-card";
|
||||||
import { IdleRuntimeCleanupCard } from "./idle-runtime-cleanup-card";
|
import { IdleRuntimeCleanupCard } from "./idle-runtime-cleanup-card";
|
||||||
import { restartDaemonFromSettings, updateDaemonFromSettings } from "./daemon-lifecycle";
|
import { restartDaemonFromSettings, updateDaemonFromSettings } from "./daemon-lifecycle";
|
||||||
|
|
||||||
@@ -292,6 +293,7 @@ export function HostAgentsPage({ serverId }: { serverId: string }) {
|
|||||||
<InjectPaseoToolsCard serverId={serverId} />
|
<InjectPaseoToolsCard serverId={serverId} />
|
||||||
<BrowserToolsOptInCard serverId={serverId} />
|
<BrowserToolsOptInCard serverId={serverId} />
|
||||||
<AppendSystemPromptCard serverId={serverId} />
|
<AppendSystemPromptCard serverId={serverId} />
|
||||||
|
<RestartRecoveryCard serverId={serverId} />
|
||||||
<IdleRuntimeCleanupCard serverId={serverId} />
|
<IdleRuntimeCleanupCard serverId={serverId} />
|
||||||
</SettingsSection>
|
</SettingsSection>
|
||||||
) : (
|
) : (
|
||||||
@@ -565,7 +567,15 @@ function RestartDaemonCard({ host }: { host: HostProfile }) {
|
|||||||
const isConnected = useHostRuntimeIsConnected(host.serverId);
|
const isConnected = useHostRuntimeIsConnected(host.serverId);
|
||||||
const runtime = getHostRuntimeStore();
|
const runtime = getHostRuntimeStore();
|
||||||
const [isRestarting, setIsRestarting] = useState(false);
|
const [isRestarting, setIsRestarting] = useState(false);
|
||||||
|
// Rendered in the card, not an Alert.alert: react-native-web's Alert is a no-op, and a failed
|
||||||
|
// close-terminals restart must name the processes left running until the user retries.
|
||||||
|
const [restartError, setRestartError] = useState<string | null>(null);
|
||||||
const isMountedRef = useRef(true);
|
const isMountedRef = useRef(true);
|
||||||
|
// COMPAT(terminalsSurviveRestart): added in v0.12.0, remove gate after 2027-04-21.
|
||||||
|
const terminalsSurviveRestart = useSessionStore(
|
||||||
|
(state) =>
|
||||||
|
state.sessions[host.serverId]?.serverInfo?.features?.terminalsSurviveRestart === true,
|
||||||
|
);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
return () => {
|
return () => {
|
||||||
@@ -578,71 +588,80 @@ function RestartDaemonCard({ host }: { host: HostProfile }) {
|
|||||||
[host.serverId, runtime],
|
[host.serverId, runtime],
|
||||||
);
|
);
|
||||||
|
|
||||||
const waitForDaemonRestart = useCallback(
|
const waitForDaemonRestart = useCallback(async (request: Promise<void>) => {
|
||||||
async (request: Promise<void>) => {
|
try {
|
||||||
try {
|
await request;
|
||||||
await request;
|
} catch (error) {
|
||||||
} catch (error) {
|
console.error("[HostPage] Daemon restart failed", error);
|
||||||
Alert.alert(
|
if (isMountedRef.current) {
|
||||||
t("settings.host.daemon.restart.requestFailedTitle"),
|
setRestartError(error instanceof Error ? error.message : String(error));
|
||||||
error instanceof Error ? error.message : String(error),
|
|
||||||
);
|
|
||||||
} finally {
|
|
||||||
if (isMountedRef.current) setIsRestarting(false);
|
|
||||||
}
|
}
|
||||||
|
} finally {
|
||||||
|
if (isMountedRef.current) setIsRestarting(false);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const startRestart = useCallback(
|
||||||
|
(killTerminals: boolean) => {
|
||||||
|
if (!daemonClient) {
|
||||||
|
Alert.alert(
|
||||||
|
t("settings.host.daemon.restart.unavailableTitle"),
|
||||||
|
t("settings.host.daemon.restart.unavailableMessage"),
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!isHostConnected()) {
|
||||||
|
Alert.alert(
|
||||||
|
t("settings.host.daemon.restart.offlineTitle"),
|
||||||
|
t("settings.host.daemon.restart.offlineMessage"),
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
void confirmDialog({
|
||||||
|
title: t("settings.host.daemon.restart.confirmTitle", { name: host.label }),
|
||||||
|
message: killTerminals
|
||||||
|
? t("settings.host.daemon.restart.closeTerminalsConfirmMessage")
|
||||||
|
: t("settings.host.daemon.restart.confirmMessage"),
|
||||||
|
confirmLabel: killTerminals
|
||||||
|
? t("settings.host.daemon.restart.closeTerminals")
|
||||||
|
: t("settings.host.daemon.restart.confirm"),
|
||||||
|
cancelLabel: t("common.actions.cancel"),
|
||||||
|
destructive: true,
|
||||||
|
})
|
||||||
|
.then((confirmed) => {
|
||||||
|
if (!confirmed) return;
|
||||||
|
setRestartError(null);
|
||||||
|
setIsRestarting(true);
|
||||||
|
const restartRequest = restartDaemonFromSettings(
|
||||||
|
host.serverId,
|
||||||
|
`settings_daemon_restart_${host.serverId}`,
|
||||||
|
{
|
||||||
|
restartServer: (reason, options) =>
|
||||||
|
daemonClient.restartServer(reason, undefined, options),
|
||||||
|
getStatus: async () => ({
|
||||||
|
...(await daemonClient.getDaemonStatus()),
|
||||||
|
serverId: daemonClient.getLastServerInfoMessage()?.serverId ?? "",
|
||||||
|
version: daemonClient.getLastServerInfoMessage()?.version ?? null,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
{ killTerminals },
|
||||||
|
);
|
||||||
|
void waitForDaemonRestart(restartRequest);
|
||||||
|
return;
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
console.error(`[HostPage] Failed to open restart confirmation for ${host.label}`, error);
|
||||||
|
if (isMountedRef.current) {
|
||||||
|
setRestartError(t("settings.host.daemon.restart.dialogFailedMessage"));
|
||||||
|
}
|
||||||
|
});
|
||||||
},
|
},
|
||||||
[t],
|
[daemonClient, host.label, host.serverId, isHostConnected, t, waitForDaemonRestart],
|
||||||
);
|
);
|
||||||
|
|
||||||
const handleRestart = useCallback(() => {
|
const handleRestart = useCallback(() => startRestart(false), [startRestart]);
|
||||||
if (!daemonClient) {
|
const handleRestartAndCloseTerminals = useCallback(() => startRestart(true), [startRestart]);
|
||||||
Alert.alert(
|
|
||||||
t("settings.host.daemon.restart.unavailableTitle"),
|
|
||||||
t("settings.host.daemon.restart.unavailableMessage"),
|
|
||||||
);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!isHostConnected()) {
|
|
||||||
Alert.alert(
|
|
||||||
t("settings.host.daemon.restart.offlineTitle"),
|
|
||||||
t("settings.host.daemon.restart.offlineMessage"),
|
|
||||||
);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
void confirmDialog({
|
|
||||||
title: t("settings.host.daemon.restart.confirmTitle", { name: host.label }),
|
|
||||||
message: t("settings.host.daemon.restart.confirmMessage"),
|
|
||||||
confirmLabel: t("settings.host.daemon.restart.confirm"),
|
|
||||||
cancelLabel: t("common.actions.cancel"),
|
|
||||||
destructive: true,
|
|
||||||
})
|
|
||||||
.then((confirmed) => {
|
|
||||||
if (!confirmed) return;
|
|
||||||
setIsRestarting(true);
|
|
||||||
const restartRequest = restartDaemonFromSettings(
|
|
||||||
host.serverId,
|
|
||||||
`settings_daemon_restart_${host.serverId}`,
|
|
||||||
{
|
|
||||||
restartServer: (reason) => daemonClient.restartServer(reason),
|
|
||||||
getStatus: async () => ({
|
|
||||||
...(await daemonClient.getDaemonStatus()),
|
|
||||||
serverId: daemonClient.getLastServerInfoMessage()?.serverId ?? "",
|
|
||||||
version: daemonClient.getLastServerInfoMessage()?.version ?? null,
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
void waitForDaemonRestart(restartRequest);
|
|
||||||
return;
|
|
||||||
})
|
|
||||||
.catch((error) => {
|
|
||||||
console.error(`[HostPage] Failed to open restart confirmation for ${host.label}`, error);
|
|
||||||
Alert.alert(
|
|
||||||
t("settings.host.daemon.restart.requestFailedTitle"),
|
|
||||||
t("settings.host.daemon.restart.dialogFailedMessage"),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
}, [daemonClient, host.label, host.serverId, isHostConnected, t, waitForDaemonRestart]);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<View style={settingsStyles.card} testID="host-page-restart-card">
|
<View style={settingsStyles.card} testID="host-page-restart-card">
|
||||||
@@ -664,6 +683,35 @@ function RestartDaemonCard({ host }: { host: HostProfile }) {
|
|||||||
: t("settings.host.daemon.restart.confirm")}
|
: t("settings.host.daemon.restart.confirm")}
|
||||||
</Button>
|
</Button>
|
||||||
</View>
|
</View>
|
||||||
|
{terminalsSurviveRestart ? (
|
||||||
|
<View style={settingsStyles.row}>
|
||||||
|
<View style={settingsStyles.rowContent}>
|
||||||
|
<Text style={settingsStyles.rowHint}>
|
||||||
|
{t("settings.host.daemon.restart.closeTerminalsHint")}
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onPress={handleRestartAndCloseTerminals}
|
||||||
|
disabled={isRestarting || !daemonClient || !isConnected}
|
||||||
|
testID="host-page-restart-close-terminals-button"
|
||||||
|
>
|
||||||
|
{t("settings.host.daemon.restart.closeTerminals")}
|
||||||
|
</Button>
|
||||||
|
</View>
|
||||||
|
) : null}
|
||||||
|
{restartError ? (
|
||||||
|
<View style={styles.cardAlert}>
|
||||||
|
<InlineAlert
|
||||||
|
size="sm"
|
||||||
|
variant="error"
|
||||||
|
title={t("settings.host.daemon.restart.requestFailedTitle")}
|
||||||
|
description={restartError}
|
||||||
|
testID="host-page-restart-error"
|
||||||
|
/>
|
||||||
|
</View>
|
||||||
|
) : null}
|
||||||
</View>
|
</View>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -848,7 +896,7 @@ function UpdateDaemonCard({ host }: { host: HostProfile }) {
|
|||||||
/>
|
/>
|
||||||
) : null}
|
) : null}
|
||||||
{updateState.status === "failed" ? (
|
{updateState.status === "failed" ? (
|
||||||
<View style={styles.updateFailure}>
|
<View style={styles.cardAlert}>
|
||||||
<InlineAlert
|
<InlineAlert
|
||||||
size="sm"
|
size="sm"
|
||||||
variant="error"
|
variant="error"
|
||||||
@@ -1702,7 +1750,7 @@ const terminalProfileStyles = StyleSheet.create((theme) => ({
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
const styles = StyleSheet.create((theme) => ({
|
const styles = StyleSheet.create((theme) => ({
|
||||||
updateFailure: {
|
cardAlert: {
|
||||||
marginHorizontal: theme.spacing[4],
|
marginHorizontal: theme.spacing[4],
|
||||||
marginBottom: theme.spacing[4],
|
marginBottom: theme.spacing[4],
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -0,0 +1,199 @@
|
|||||||
|
import { useCallback, useMemo, useState } from "react";
|
||||||
|
import { Text, View } from "react-native";
|
||||||
|
import { useMutation } from "@tanstack/react-query";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { StyleSheet } from "react-native-unistyles";
|
||||||
|
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
|
||||||
|
import { SettingsTextAreaCard } from "@/components/settings-textarea";
|
||||||
|
import { SettingsInfoTip } from "@/components/settings/headings/settings-info-tip";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Switch } from "@/components/ui/switch";
|
||||||
|
import { useDaemonConfig } from "@/hooks/use-daemon-config";
|
||||||
|
import { useHostFeature } from "@/runtime/host-features";
|
||||||
|
import { useHostRuntimeIsConnected } from "@/runtime/host-runtime";
|
||||||
|
import { settingsStyles } from "@/styles/settings";
|
||||||
|
|
||||||
|
const DEFAULT_RESUME_PROMPT = "Resume working.";
|
||||||
|
|
||||||
|
// COMPAT(restartRecovery): added in v0.14.0, remove gate after 2027-04-28.
|
||||||
|
export function RestartRecoveryCard({ serverId }: { serverId: string }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const isConnected = useHostRuntimeIsConnected(serverId);
|
||||||
|
const isSupported = useHostFeature(serverId, "resumeOnStartupSetting");
|
||||||
|
const { config, patchConfig } = useDaemonConfig(serverId);
|
||||||
|
const [isEditing, setIsEditing] = useState(false);
|
||||||
|
const mutation = useMutation({
|
||||||
|
mutationFn: async (next: { resumeOnStartup?: boolean; resumePrompt?: string }) => {
|
||||||
|
const result = await patchConfig(next);
|
||||||
|
if (!result) {
|
||||||
|
throw new Error(t("workspace.terminal.hostDisconnected"));
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const handleValueChange = useCallback(
|
||||||
|
(next: boolean) => {
|
||||||
|
mutation.mutate({ resumeOnStartup: next });
|
||||||
|
},
|
||||||
|
[mutation],
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleOpen = useCallback(() => {
|
||||||
|
mutation.reset();
|
||||||
|
setIsEditing(true);
|
||||||
|
}, [mutation]);
|
||||||
|
|
||||||
|
const handleClose = useCallback(() => {
|
||||||
|
if (mutation.isPending) return;
|
||||||
|
mutation.reset();
|
||||||
|
setIsEditing(false);
|
||||||
|
}, [mutation]);
|
||||||
|
|
||||||
|
const handleSave = useCallback(
|
||||||
|
(prompt: string) => {
|
||||||
|
mutation.mutate({ resumePrompt: prompt }, { onSuccess: () => setIsEditing(false) });
|
||||||
|
},
|
||||||
|
[mutation],
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!isConnected || !isSupported || !config) return null;
|
||||||
|
|
||||||
|
const isEnabled = config.resumeOnStartup !== false;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<View style={settingsStyles.card} testID="host-page-restart-recovery-card">
|
||||||
|
<View style={settingsStyles.row}>
|
||||||
|
<View style={settingsStyles.rowContent}>
|
||||||
|
<View style={styles.titleRow}>
|
||||||
|
<Text style={settingsStyles.rowTitle}>
|
||||||
|
{t("settings.host.agents.resumeOnStartup.title")}
|
||||||
|
</Text>
|
||||||
|
<SettingsInfoTip
|
||||||
|
title={t("settings.host.agents.resumeOnStartup.title")}
|
||||||
|
info={t("settings.host.agents.resumeOnStartup.info")}
|
||||||
|
/>
|
||||||
|
</View>
|
||||||
|
<Text style={settingsStyles.rowHint}>
|
||||||
|
{t("settings.host.agents.resumeOnStartup.hint")}
|
||||||
|
</Text>
|
||||||
|
{mutation.error && !isEditing ? (
|
||||||
|
<Text style={settingsStyles.rowError} testID="host-page-restart-recovery-error">
|
||||||
|
{mutation.error.message}
|
||||||
|
</Text>
|
||||||
|
) : null}
|
||||||
|
</View>
|
||||||
|
<View style={styles.trailing}>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onPress={handleOpen}
|
||||||
|
disabled={!isEnabled || mutation.isPending}
|
||||||
|
accessibilityLabel={t("settings.host.agents.resumeOnStartup.editAccessibilityLabel")}
|
||||||
|
testID="host-page-restart-recovery-edit"
|
||||||
|
>
|
||||||
|
{t("settings.host.agents.resumeOnStartup.edit")}
|
||||||
|
</Button>
|
||||||
|
<Switch
|
||||||
|
value={isEnabled}
|
||||||
|
onValueChange={handleValueChange}
|
||||||
|
disabled={mutation.isPending}
|
||||||
|
accessibilityLabel={t("settings.host.agents.resumeOnStartup.title")}
|
||||||
|
testID="host-page-restart-recovery-switch"
|
||||||
|
/>
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
|
||||||
|
{isEditing ? (
|
||||||
|
<ResumePromptSheet
|
||||||
|
initialPrompt={config.resumePrompt ?? DEFAULT_RESUME_PROMPT}
|
||||||
|
isSaving={mutation.isPending}
|
||||||
|
error={mutation.error?.message ?? null}
|
||||||
|
onSave={handleSave}
|
||||||
|
onClose={handleClose}
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ResumePromptSheet({
|
||||||
|
initialPrompt,
|
||||||
|
isSaving,
|
||||||
|
error,
|
||||||
|
onSave,
|
||||||
|
onClose,
|
||||||
|
}: {
|
||||||
|
initialPrompt: string;
|
||||||
|
isSaving: boolean;
|
||||||
|
error: string | null;
|
||||||
|
onSave: (prompt: string) => void;
|
||||||
|
onClose: () => void;
|
||||||
|
}) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const [draft, setDraft] = useState(initialPrompt);
|
||||||
|
const header = useMemo<SheetHeader>(
|
||||||
|
() => ({ title: t("settings.host.agents.resumeOnStartup.prompt") }),
|
||||||
|
[t],
|
||||||
|
);
|
||||||
|
const canSave = draft !== initialPrompt && draft.trim().length > 0 && !isSaving;
|
||||||
|
|
||||||
|
const handleSave = useCallback(() => onSave(draft), [draft, onSave]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AdaptiveModalSheet
|
||||||
|
header={header}
|
||||||
|
visible
|
||||||
|
onClose={onClose}
|
||||||
|
testID="host-page-restart-recovery-sheet"
|
||||||
|
desktopMaxWidth={560}
|
||||||
|
>
|
||||||
|
<SettingsTextAreaCard
|
||||||
|
testID="host-page-restart-recovery-prompt-input"
|
||||||
|
accessibilityLabel={t("settings.host.agents.resumeOnStartup.prompt")}
|
||||||
|
value={draft}
|
||||||
|
onChangeText={setDraft}
|
||||||
|
placeholder={DEFAULT_RESUME_PROMPT}
|
||||||
|
/>
|
||||||
|
{error ? (
|
||||||
|
<Text style={settingsStyles.rowError} testID="host-page-restart-recovery-error">
|
||||||
|
{error}
|
||||||
|
</Text>
|
||||||
|
) : null}
|
||||||
|
<View style={styles.sheetActions}>
|
||||||
|
<Button variant="ghost" size="sm" onPress={onClose} disabled={isSaving}>
|
||||||
|
{t("common.actions.cancel")}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="default"
|
||||||
|
size="sm"
|
||||||
|
onPress={handleSave}
|
||||||
|
disabled={!canSave}
|
||||||
|
testID="host-page-restart-recovery-save"
|
||||||
|
>
|
||||||
|
{t("common.actions.save")}
|
||||||
|
</Button>
|
||||||
|
</View>
|
||||||
|
</AdaptiveModalSheet>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const styles = StyleSheet.create((theme) => ({
|
||||||
|
titleRow: {
|
||||||
|
flexDirection: "row",
|
||||||
|
alignItems: "center",
|
||||||
|
gap: theme.spacing[2],
|
||||||
|
},
|
||||||
|
trailing: {
|
||||||
|
flexDirection: "row",
|
||||||
|
alignItems: "center",
|
||||||
|
gap: theme.spacing[3],
|
||||||
|
},
|
||||||
|
sheetActions: {
|
||||||
|
flexDirection: "row",
|
||||||
|
justifyContent: "flex-end",
|
||||||
|
gap: theme.spacing[2],
|
||||||
|
},
|
||||||
|
}));
|
||||||
@@ -174,7 +174,6 @@ it("feeds restored layout to timeline sync as a release signal, not a subscripti
|
|||||||
fetchLatestTail: async () => ({ hasNewer: false, endCursor: null }),
|
fetchLatestTail: async () => ({ hasNewer: false, endCursor: null }),
|
||||||
onCatchUpEnded: () => undefined,
|
onCatchUpEnded: () => undefined,
|
||||||
reportError: () => undefined,
|
reportError: () => undefined,
|
||||||
schedule: () => () => undefined,
|
|
||||||
});
|
});
|
||||||
// The edge session-context.tsx owns. Pointing it at subscription instead would resume every
|
// The edge session-context.tsx owns. Pointing it at subscription instead would resume every
|
||||||
// agent behind a restored tab on the daemon.
|
// agent behind a restored tab on the daemon.
|
||||||
|
|||||||
@@ -57,7 +57,6 @@ function createOwner(storage: TimelineReplicaStorage): ViewedTimelineOwner {
|
|||||||
fetchPage: async () => ({ hasNewer: false, endCursor: null }),
|
fetchPage: async () => ({ hasNewer: false, endCursor: null }),
|
||||||
fetchLatestTail: async () => ({ hasNewer: false, endCursor: null }),
|
fetchLatestTail: async () => ({ hasNewer: false, endCursor: null }),
|
||||||
reportError: () => undefined,
|
reportError: () => undefined,
|
||||||
schedule: () => () => undefined,
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -371,6 +370,22 @@ describe("viewed timeline persistence", () => {
|
|||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("preparing an already painted cache again keeps history out of the live head", async () => {
|
||||||
|
useSessionStore.getState().initializeSession(SERVER_ID, null);
|
||||||
|
const replica = createTimelineReplica({
|
||||||
|
serverId: SERVER_ID,
|
||||||
|
storage: { readTimeline: async () => cachedTimeline(), commitTimeline: () => undefined },
|
||||||
|
prepareAgent: async () => undefined,
|
||||||
|
});
|
||||||
|
await replica.prepare(AGENT_ID);
|
||||||
|
const painted = useSessionStore.getState().sessions[SERVER_ID]!.agentStreamTail.get(AGENT_ID);
|
||||||
|
expect(painted).toEqual(cachedTimeline().items);
|
||||||
|
await replica.prepare(AGENT_ID);
|
||||||
|
const session = useSessionStore.getState().sessions[SERVER_ID]!;
|
||||||
|
expect(session.agentStreamHead.get(AGENT_ID) ?? []).toEqual([]);
|
||||||
|
expect(session.agentStreamTail.get(AGENT_ID)).toBe(painted);
|
||||||
|
});
|
||||||
|
|
||||||
it("reconciles a live head that overlaps the cached canonical timeline", async () => {
|
it("reconciles a live head that overlaps the cached canonical timeline", async () => {
|
||||||
useSessionStore.getState().initializeSession(SERVER_ID, null);
|
useSessionStore.getState().initializeSession(SERVER_ID, null);
|
||||||
let release!: (value: CachedTimeline) => void;
|
let release!: (value: CachedTimeline) => void;
|
||||||
@@ -601,7 +616,6 @@ describe("create handoff lifetime", () => {
|
|||||||
},
|
},
|
||||||
fetchLatestTail: async () => ({ hasNewer: false, endCursor: null }),
|
fetchLatestTail: async () => ({ hasNewer: false, endCursor: null }),
|
||||||
reportError: () => undefined,
|
reportError: () => undefined,
|
||||||
schedule: () => () => undefined,
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -90,7 +90,7 @@ test("visible catch-up settles before hidden open chats start fetching", async (
|
|||||||
world.sync.dispose();
|
world.sync.dispose();
|
||||||
});
|
});
|
||||||
|
|
||||||
test("a failed visible catch-up releases hidden chats without bypassing its retry delay", async () => {
|
test("a failed visible catch-up releases hidden chats without bypassing its error", async () => {
|
||||||
const world = new TimelineWorld();
|
const world = new TimelineWorld();
|
||||||
world.openedEarlier(["a-hidden"]);
|
world.openedEarlier(["a-hidden"]);
|
||||||
world.sync.replaceVisibleAgentIds("pane", ["z-visible"]);
|
world.sync.replaceVisibleAgentIds("pane", ["z-visible"]);
|
||||||
@@ -103,7 +103,7 @@ test("a failed visible catch-up releases hidden chats without bypassing its retr
|
|||||||
hidden.respond({ hasNewer: false });
|
hidden.respond({ hasNewer: false });
|
||||||
await world.nextError();
|
await world.nextError();
|
||||||
world.expectNoPendingFetch();
|
world.expectNoPendingFetch();
|
||||||
(await world.nextRetry())();
|
world.sync.retryVisibleAgentTimeline("z-visible");
|
||||||
(await world.nextFetch("z-visible")).respond({ hasNewer: false });
|
(await world.nextFetch("z-visible")).respond({ hasNewer: false });
|
||||||
world.sync.dispose();
|
world.sync.dispose();
|
||||||
});
|
});
|
||||||
@@ -200,20 +200,6 @@ class TimelineWorld {
|
|||||||
const waiter = this.errorWaiters.shift();
|
const waiter = this.errorWaiters.shift();
|
||||||
if (waiter) waiter(this.errors.at(-1) ?? "");
|
if (waiter) waiter(this.errors.at(-1) ?? "");
|
||||||
},
|
},
|
||||||
schedule: (task, delayMs) => {
|
|
||||||
const scheduled = { task, delayMs };
|
|
||||||
this.scheduled.push(scheduled);
|
|
||||||
const waiterIndex = this.retryWaiters.findIndex((waiter) => waiter.delayMs === delayMs);
|
|
||||||
if (waiterIndex >= 0) {
|
|
||||||
const [waiter] = this.retryWaiters.splice(waiterIndex, 1);
|
|
||||||
this.scheduled.splice(this.scheduled.indexOf(scheduled), 1);
|
|
||||||
waiter.resolve(task);
|
|
||||||
}
|
|
||||||
return () => {
|
|
||||||
const index = this.scheduled.indexOf(scheduled);
|
|
||||||
if (index >= 0) this.scheduled.splice(index, 1);
|
|
||||||
};
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
show(sourceId: string, agentIds: string[]): void {
|
show(sourceId: string, agentIds: string[]): void {
|
||||||
@@ -235,12 +221,6 @@ class TimelineWorld {
|
|||||||
}> = [];
|
}> = [];
|
||||||
private readonly errorWaiters: Array<(message: string) => void> = [];
|
private readonly errorWaiters: Array<(message: string) => void> = [];
|
||||||
private readonly cacheRequestWaiters: Array<(agentId: string) => void> = [];
|
private readonly cacheRequestWaiters: Array<(agentId: string) => void> = [];
|
||||||
private readonly scheduled: Array<{ task: () => void; delayMs: number }> = [];
|
|
||||||
private readonly retryWaiters: Array<{
|
|
||||||
delayMs: number;
|
|
||||||
resolve(retry: () => void): void;
|
|
||||||
}> = [];
|
|
||||||
|
|
||||||
get pendingFetchCount(): number {
|
get pendingFetchCount(): number {
|
||||||
return this.fetches.length;
|
return this.fetches.length;
|
||||||
}
|
}
|
||||||
@@ -300,22 +280,6 @@ class TimelineWorld {
|
|||||||
return new Promise((resolve) => this.errorWaiters.push(resolve));
|
return new Promise((resolve) => this.errorWaiters.push(resolve));
|
||||||
}
|
}
|
||||||
|
|
||||||
nextRetry(delayMs = 1_000): Promise<() => void> {
|
|
||||||
const index = this.scheduled.findIndex((entry) => entry.delayMs === delayMs);
|
|
||||||
if (index >= 0) return Promise.resolve(this.scheduled.splice(index, 1)[0].task);
|
|
||||||
return new Promise((resolve) => this.retryWaiters.push({ delayMs, resolve }));
|
|
||||||
}
|
|
||||||
|
|
||||||
elapse(elapsedMs: number): void {
|
|
||||||
const due = this.scheduled.filter((entry) => entry.delayMs <= elapsedMs);
|
|
||||||
this.scheduled.splice(
|
|
||||||
0,
|
|
||||||
this.scheduled.length,
|
|
||||||
...this.scheduled.filter((entry) => entry.delayMs > elapsedMs),
|
|
||||||
);
|
|
||||||
for (const entry of due) entry.task();
|
|
||||||
}
|
|
||||||
|
|
||||||
private releaseMembershipWaiter(): void {
|
private releaseMembershipWaiter(): void {
|
||||||
const waiter = this.membershipWaiters.shift();
|
const waiter = this.membershipWaiters.shift();
|
||||||
if (!waiter) return;
|
if (!waiter) return;
|
||||||
@@ -483,6 +447,28 @@ test("reports a chat current only once its parked follow-up page completes", asy
|
|||||||
world.sync.dispose();
|
world.sync.dispose();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("a gap during manual retry is recovered before reporting ready", async () => {
|
||||||
|
const world = new TimelineWorld();
|
||||||
|
world.sync.setConnected(true);
|
||||||
|
world.show("workspace", ["agent-a"]);
|
||||||
|
(await world.nextMembership()).succeed();
|
||||||
|
(await world.nextFetch("agent-a")).fail("unavailable");
|
||||||
|
await world.nextError();
|
||||||
|
world.sync.retryVisibleAgentTimeline("agent-a");
|
||||||
|
const retry = await world.nextFetch("agent-a");
|
||||||
|
world.sync.recoverGap("agent-a", { epoch: "epoch-agent-a", endSeq: 9 });
|
||||||
|
retry.respond({ hasNewer: false });
|
||||||
|
await vi.waitFor(() => expect(world.pendingFetchCount).toBe(1));
|
||||||
|
const recovery = await world.nextFetch("agent-a");
|
||||||
|
expect(recovery.request).toMatchObject({
|
||||||
|
direction: "after",
|
||||||
|
cursor: { epoch: "epoch-agent-a", seq: 9 },
|
||||||
|
});
|
||||||
|
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("retrying");
|
||||||
|
recovery.respond({ hasNewer: false });
|
||||||
|
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
|
||||||
|
});
|
||||||
|
|
||||||
test("reports a chat current once the latest-tail fallback replaces an overflowing catch-up", async () => {
|
test("reports a chat current once the latest-tail fallback replaces an overflowing catch-up", async () => {
|
||||||
const world = new TimelineWorld();
|
const world = new TimelineWorld();
|
||||||
world.cursors.set("agent-a", { epoch: "epoch-agent-a", endSeq: 42 });
|
world.cursors.set("agent-a", { epoch: "epoch-agent-a", endSeq: 42 });
|
||||||
@@ -780,6 +766,21 @@ test("overlapping sources deduplicate membership and retain open hidden chats",
|
|||||||
world.expectNoPendingFetch();
|
world.expectNoPendingFetch();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("failed timeline fetch does not schedule a retry", async () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
const world = new TimelineWorld();
|
||||||
|
world.sync.setConnected(true);
|
||||||
|
world.show("workspace", ["agent-a"]);
|
||||||
|
(await world.nextMembership()).succeed();
|
||||||
|
(await world.nextFetch("agent-a")).fail("unavailable");
|
||||||
|
await world.nextError();
|
||||||
|
expect(vi.getTimerCount()).toBe(0);
|
||||||
|
await vi.advanceTimersByTimeAsync(120_000);
|
||||||
|
world.expectNoPendingFetch();
|
||||||
|
world.expectNoPendingMembership();
|
||||||
|
vi.useRealTimers();
|
||||||
|
});
|
||||||
|
|
||||||
test("a failed catch-up reports once and retries through the explicit retry policy", async () => {
|
test("a failed catch-up reports once and retries through the explicit retry policy", async () => {
|
||||||
const world = new TimelineWorld();
|
const world = new TimelineWorld();
|
||||||
world.sync.setConnected(true);
|
world.sync.setConnected(true);
|
||||||
@@ -788,12 +789,12 @@ test("a failed catch-up reports once and retries through the explicit retry poli
|
|||||||
membership.succeed();
|
membership.succeed();
|
||||||
const failed = await world.nextFetch("agent-a");
|
const failed = await world.nextFetch("agent-a");
|
||||||
failed.fail("timeline unavailable");
|
failed.fail("timeline unavailable");
|
||||||
const [error, retryCatchUp] = await Promise.all([world.nextError(), world.nextRetry()]);
|
const error = await world.nextError();
|
||||||
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error");
|
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error");
|
||||||
|
|
||||||
retryCatchUp();
|
world.sync.retryVisibleAgentTimeline("agent-a");
|
||||||
const retry = await world.nextFetch("agent-a");
|
const retry = await world.nextFetch("agent-a");
|
||||||
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error");
|
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("retrying");
|
||||||
retry.respond({ hasNewer: false });
|
retry.respond({ hasNewer: false });
|
||||||
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
|
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
|
||||||
|
|
||||||
@@ -804,35 +805,6 @@ test("a failed catch-up reports once and retries through the explicit retry poli
|
|||||||
world.expectNoPendingMembership();
|
world.expectNoPendingMembership();
|
||||||
});
|
});
|
||||||
|
|
||||||
test("a failed catch-up retries with exponential backoff", async () => {
|
|
||||||
const world = new TimelineWorld();
|
|
||||||
world.sync.setConnected(true);
|
|
||||||
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
|
|
||||||
const membership = await world.nextMembership();
|
|
||||||
membership.succeed();
|
|
||||||
|
|
||||||
const first = await world.nextFetch("agent-a");
|
|
||||||
first.fail("timeline unavailable");
|
|
||||||
const [firstError, retryAfterFirstFailure] = await Promise.all([
|
|
||||||
world.nextError(),
|
|
||||||
world.nextRetry(),
|
|
||||||
]);
|
|
||||||
expect(firstError).toBe("timeline unavailable");
|
|
||||||
retryAfterFirstFailure();
|
|
||||||
|
|
||||||
const second = await world.nextFetch("agent-a");
|
|
||||||
second.fail("timeline unavailable");
|
|
||||||
await world.nextError();
|
|
||||||
|
|
||||||
const retryAfterSecondFailure = await world.nextRetry(2_000);
|
|
||||||
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error");
|
|
||||||
|
|
||||||
retryAfterSecondFailure();
|
|
||||||
const third = await world.nextFetch("agent-a");
|
|
||||||
third.respond({ hasNewer: false });
|
|
||||||
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
|
|
||||||
});
|
|
||||||
|
|
||||||
test("manual retries can immediately re-attempt a failed catch-up", async () => {
|
test("manual retries can immediately re-attempt a failed catch-up", async () => {
|
||||||
const world = new TimelineWorld();
|
const world = new TimelineWorld();
|
||||||
world.sync.setConnected(true);
|
world.sync.setConnected(true);
|
||||||
@@ -842,7 +814,7 @@ test("manual retries can immediately re-attempt a failed catch-up", async () =>
|
|||||||
|
|
||||||
const failed = await world.nextFetch("agent-a");
|
const failed = await world.nextFetch("agent-a");
|
||||||
failed.fail("timeline unavailable");
|
failed.fail("timeline unavailable");
|
||||||
await world.nextRetry();
|
await world.nextError();
|
||||||
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error");
|
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error");
|
||||||
|
|
||||||
world.sync.retryVisibleAgentTimeline("agent-a");
|
world.sync.retryVisibleAgentTimeline("agent-a");
|
||||||
@@ -853,7 +825,7 @@ test("manual retries can immediately re-attempt a failed catch-up", async () =>
|
|||||||
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
|
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
|
||||||
});
|
});
|
||||||
|
|
||||||
test("redeclaring unchanged visibility does not bypass catch-up backoff", async () => {
|
test("redeclaring unchanged visibility does not bypass catch-up error", async () => {
|
||||||
const world = new TimelineWorld();
|
const world = new TimelineWorld();
|
||||||
world.sync.setConnected(true);
|
world.sync.setConnected(true);
|
||||||
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
|
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
|
||||||
@@ -862,9 +834,11 @@ test("redeclaring unchanged visibility does not bypass catch-up backoff", async
|
|||||||
|
|
||||||
const failed = await world.nextFetch("agent-a");
|
const failed = await world.nextFetch("agent-a");
|
||||||
failed.fail("timeline unavailable");
|
failed.fail("timeline unavailable");
|
||||||
await world.nextRetry();
|
await world.nextError();
|
||||||
|
|
||||||
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
|
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
|
||||||
|
world.sync.setActive(false);
|
||||||
|
world.sync.setActive(true);
|
||||||
|
|
||||||
world.expectNoPendingMembership();
|
world.expectNoPendingMembership();
|
||||||
world.expectNoPendingFetch();
|
world.expectNoPendingFetch();
|
||||||
@@ -880,7 +854,7 @@ test("a manual retry that fails returns to the error state", async () => {
|
|||||||
|
|
||||||
const failed = await world.nextFetch("agent-a");
|
const failed = await world.nextFetch("agent-a");
|
||||||
failed.fail("timeline unavailable");
|
failed.fail("timeline unavailable");
|
||||||
await world.nextRetry();
|
await world.nextError();
|
||||||
|
|
||||||
world.sync.retryVisibleAgentTimeline("agent-a");
|
world.sync.retryVisibleAgentTimeline("agent-a");
|
||||||
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("retrying");
|
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("retrying");
|
||||||
@@ -943,20 +917,34 @@ test("repeated recovery for the same running gap reuses the in-flight fetch", as
|
|||||||
gapPage.respond({ hasNewer: false });
|
gapPage.respond({ hasNewer: false });
|
||||||
});
|
});
|
||||||
|
|
||||||
test("membership failure autonomously retries without another visibility declaration", async () => {
|
test("failed membership does not schedule a retry", async () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
const world = new TimelineWorld();
|
||||||
|
world.sync.setConnected(true);
|
||||||
|
world.show("workspace", ["agent-a"]);
|
||||||
|
(await world.nextMembership()).fail("unavailable");
|
||||||
|
await world.nextError();
|
||||||
|
expect(vi.getTimerCount()).toBe(0);
|
||||||
|
await vi.advanceTimersByTimeAsync(120_000);
|
||||||
|
world.expectNoPendingFetch();
|
||||||
|
world.expectNoPendingMembership();
|
||||||
|
vi.useRealTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("membership failure waits for manual retry", async () => {
|
||||||
const world = new TimelineWorld();
|
const world = new TimelineWorld();
|
||||||
world.sync.setConnected(true);
|
world.sync.setConnected(true);
|
||||||
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
|
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
|
||||||
const failed = await world.nextMembership();
|
const failed = await world.nextMembership();
|
||||||
failed.fail("subscription unavailable");
|
failed.fail("subscription unavailable");
|
||||||
const [error, retryMembership] = await Promise.all([world.nextError(), world.nextRetry()]);
|
const error = await world.nextError();
|
||||||
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error");
|
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error");
|
||||||
|
|
||||||
retryMembership();
|
world.sync.retryVisibleAgentTimeline("agent-a");
|
||||||
const retry = await world.nextMembership();
|
const retry = await world.nextMembership();
|
||||||
retry.succeed();
|
retry.succeed();
|
||||||
const catchUp = await world.nextFetch("agent-a");
|
const catchUp = await world.nextFetch("agent-a");
|
||||||
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error");
|
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("retrying");
|
||||||
catchUp.respond({ hasNewer: false });
|
catchUp.respond({ hasNewer: false });
|
||||||
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
|
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
|
||||||
|
|
||||||
@@ -967,44 +955,68 @@ test("membership failure autonomously retries without another visibility declara
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
test("membership failures retry with exponential backoff", async () => {
|
test("retrying membership restores a previously loaded chat", async () => {
|
||||||
const world = new TimelineWorld();
|
const world = new TimelineWorld();
|
||||||
world.sync.setConnected(true);
|
world.sync.setConnected(true);
|
||||||
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
|
world.show("workspace", ["agent-a"]);
|
||||||
|
(await world.nextMembership()).succeed();
|
||||||
const first = await world.nextMembership();
|
(await world.nextFetch("agent-a")).respond({ hasNewer: false });
|
||||||
first.fail("subscription unavailable");
|
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
|
||||||
const [firstError, retryAfterFirstFailure] = await Promise.all([
|
world.cursors.set("agent-a", { epoch: "epoch-agent-a", endSeq: 10 });
|
||||||
world.nextError(),
|
world.show("workspace", ["agent-b"]);
|
||||||
world.nextRetry(),
|
(await world.nextMembership()).fail("subscription unavailable");
|
||||||
]);
|
await world.nextError();
|
||||||
expect(firstError).toBe("subscription unavailable");
|
world.sync.retryVisibleAgentTimeline("agent-a");
|
||||||
|
(await world.nextMembership()).succeed();
|
||||||
retryAfterFirstFailure();
|
(await world.nextFetch("agent-b")).respond({ hasNewer: false });
|
||||||
const second = await world.nextMembership();
|
const resumed = await world.nextFetch("agent-a");
|
||||||
second.fail("subscription unavailable again");
|
expect(resumed.request).toMatchObject({
|
||||||
|
direction: "after",
|
||||||
const retryAfterSecondFailure = await world.nextRetry(2_000);
|
cursor: { epoch: "epoch-agent-a", seq: 10 },
|
||||||
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error");
|
});
|
||||||
|
resumed.respond({ hasNewer: false });
|
||||||
retryAfterSecondFailure();
|
|
||||||
const retry = await world.nextMembership();
|
|
||||||
retry.succeed();
|
|
||||||
const catchUp = await world.nextFetch("agent-a");
|
|
||||||
catchUp.respond({ hasNewer: false });
|
|
||||||
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
|
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
|
||||||
});
|
});
|
||||||
|
|
||||||
test("redeclaring unchanged visibility does not bypass membership backoff", async () => {
|
test("a fetch that finishes after membership failure cannot clear the error", async () => {
|
||||||
|
const world = new TimelineWorld();
|
||||||
|
world.sync.setConnected(true);
|
||||||
|
world.show("workspace", ["agent-a"]);
|
||||||
|
(await world.nextMembership()).succeed();
|
||||||
|
const inFlight = await world.nextFetch("agent-a");
|
||||||
|
world.show("workspace", ["agent-b"]);
|
||||||
|
(await world.nextMembership()).fail("subscription unavailable");
|
||||||
|
await world.nextError();
|
||||||
|
inFlight.respond({ hasNewer: false });
|
||||||
|
await Promise.resolve();
|
||||||
|
await Promise.resolve();
|
||||||
|
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a failed membership retry returns to error", async () => {
|
||||||
|
const world = new TimelineWorld();
|
||||||
|
world.sync.setConnected(true);
|
||||||
|
world.show("workspace", ["agent-a"]);
|
||||||
|
(await world.nextMembership()).fail("unavailable");
|
||||||
|
await world.nextError();
|
||||||
|
world.sync.retryVisibleAgentTimeline("agent-a");
|
||||||
|
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("retrying");
|
||||||
|
(await world.nextMembership()).fail("still unavailable");
|
||||||
|
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error"));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("redeclaring unchanged visibility does not bypass membership error", async () => {
|
||||||
const world = new TimelineWorld();
|
const world = new TimelineWorld();
|
||||||
world.sync.setConnected(true);
|
world.sync.setConnected(true);
|
||||||
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
|
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
|
||||||
|
|
||||||
const failed = await world.nextMembership();
|
const failed = await world.nextMembership();
|
||||||
failed.fail("subscription unavailable");
|
failed.fail("subscription unavailable");
|
||||||
await world.nextRetry();
|
await world.nextError();
|
||||||
|
|
||||||
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
|
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
|
||||||
|
world.sync.setActive(false);
|
||||||
|
world.sync.setActive(true);
|
||||||
|
|
||||||
world.expectNoPendingMembership();
|
world.expectNoPendingMembership();
|
||||||
world.expectNoPendingFetch();
|
world.expectNoPendingFetch();
|
||||||
@@ -1050,7 +1062,6 @@ test("backgrounding preserves subscriptions and returning verifies the visible c
|
|||||||
|
|
||||||
world.sync.setActive(false);
|
world.sync.setActive(false);
|
||||||
world.expectNoPendingMembership();
|
world.expectNoPendingMembership();
|
||||||
world.elapse(60_000);
|
|
||||||
world.sync.setActive(true);
|
world.sync.setActive(true);
|
||||||
|
|
||||||
world.expectNoPendingMembership();
|
world.expectNoPendingMembership();
|
||||||
@@ -1067,11 +1078,10 @@ test("stale membership retry cannot overwrite a newer effective set", async () =
|
|||||||
world.show("workspace", ["agent-a"]);
|
world.show("workspace", ["agent-a"]);
|
||||||
const failed = await world.nextMembership();
|
const failed = await world.nextMembership();
|
||||||
failed.fail("subscription unavailable");
|
failed.fail("subscription unavailable");
|
||||||
const staleRetry = await world.nextRetry();
|
await world.nextError();
|
||||||
|
|
||||||
world.show("workspace", ["agent-b"]);
|
world.show("workspace", ["agent-b"]);
|
||||||
const current = await world.nextMembership();
|
const current = await world.nextMembership();
|
||||||
staleRetry();
|
|
||||||
current.succeed();
|
current.succeed();
|
||||||
const agentB = await world.nextFetch("agent-b");
|
const agentB = await world.nextFetch("agent-b");
|
||||||
agentB.respond({ hasNewer: false });
|
agentB.respond({ hasNewer: false });
|
||||||
@@ -1088,10 +1098,9 @@ test("membership retry cannot run while disconnected", async () => {
|
|||||||
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
|
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
|
||||||
const failed = await world.nextMembership();
|
const failed = await world.nextMembership();
|
||||||
failed.fail("subscription unavailable");
|
failed.fail("subscription unavailable");
|
||||||
const disconnectedRetry = await world.nextRetry();
|
await world.nextError();
|
||||||
|
|
||||||
world.sync.setConnected(false);
|
world.sync.setConnected(false);
|
||||||
disconnectedRetry();
|
|
||||||
world.expectNoPendingMembership();
|
world.expectNoPendingMembership();
|
||||||
world.sync.setConnected(true);
|
world.sync.setConnected(true);
|
||||||
const restored = await world.nextMembership();
|
const restored = await world.nextMembership();
|
||||||
@@ -1118,7 +1127,6 @@ test("returning to an open hidden agent stays live after inactivity", async () =
|
|||||||
agentBCatchUp.respond({ hasNewer: false });
|
agentBCatchUp.respond({ hasNewer: false });
|
||||||
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-b")).toBe("ready"));
|
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-b")).toBe("ready"));
|
||||||
|
|
||||||
world.elapse(60_000);
|
|
||||||
world.show("workspace", ["agent-a"]);
|
world.show("workspace", ["agent-a"]);
|
||||||
|
|
||||||
world.expectNoPendingMembership();
|
world.expectNoPendingMembership();
|
||||||
|
|||||||
@@ -109,6 +109,15 @@ class TimelineReplicaOwner implements TimelineReplica {
|
|||||||
async prepare(agentId: string): Promise<void> {
|
async prepare(agentId: string): Promise<void> {
|
||||||
const existing = this.preparations.get(agentId);
|
const existing = this.preparations.get(agentId);
|
||||||
if (existing) return existing;
|
if (existing) return existing;
|
||||||
|
const timeline = selectAgentTimelineState(
|
||||||
|
useSessionStore.getState().sessions[this.serverId],
|
||||||
|
agentId,
|
||||||
|
);
|
||||||
|
// A route and the visible-chat owner can both prepare before catch-up finishes.
|
||||||
|
// Repainting that same cache would treat its history as a live head.
|
||||||
|
if (timeline.status !== "cold" && this.cachedRanges.has(agentId)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
const preparation = this.load(agentId).finally(() => {
|
const preparation = this.load(agentId).finally(() => {
|
||||||
if (this.preparations.get(agentId) === preparation) {
|
if (this.preparations.get(agentId) === preparation) {
|
||||||
this.preparations.delete(agentId);
|
this.preparations.delete(agentId);
|
||||||
@@ -320,7 +329,6 @@ export interface ViewedTimelineSyncPorts {
|
|||||||
*/
|
*/
|
||||||
onCatchUpEnded(agentId: string): void;
|
onCatchUpEnded(agentId: string): void;
|
||||||
reportError(error: unknown): void;
|
reportError(error: unknown): void;
|
||||||
schedule(task: () => void, delayMs: number): () => void;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ViewedTimelineStatus = "ready" | "pending" | "error" | "retrying";
|
export type ViewedTimelineStatus = "ready" | "pending" | "error" | "retrying";
|
||||||
@@ -414,26 +422,14 @@ export function createViewedTimelineOwner(input: {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const RETRY_DELAY_MS = 1_000;
|
|
||||||
const MAX_RETRY_DELAY_MS = 30_000;
|
|
||||||
|
|
||||||
type CatchUpStatus = "running" | "complete" | "error";
|
type CatchUpStatus = "running" | "complete" | "error";
|
||||||
|
|
||||||
interface CatchUpState {
|
interface CatchUpState {
|
||||||
generation: number;
|
generation: number;
|
||||||
status: CatchUpStatus;
|
status: CatchUpStatus;
|
||||||
request?: ProjectedTimelineForwardFetchPlan;
|
request?: ProjectedTimelineForwardFetchPlan;
|
||||||
cancelRetry?: () => void;
|
|
||||||
retryDelayMs?: number;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const getNextRetryDelayMs = (previousDelayMs: number | undefined): number => {
|
|
||||||
if (previousDelayMs == null) {
|
|
||||||
return RETRY_DELAY_MS;
|
|
||||||
}
|
|
||||||
return Math.min(previousDelayMs * 2, MAX_RETRY_DELAY_MS);
|
|
||||||
};
|
|
||||||
|
|
||||||
function isSameCatchUpRequest(
|
function isSameCatchUpRequest(
|
||||||
left: ProjectedTimelineForwardFetchPlan | undefined,
|
left: ProjectedTimelineForwardFetchPlan | undefined,
|
||||||
right: ProjectedTimelineForwardFetchPlan | undefined,
|
right: ProjectedTimelineForwardFetchPlan | undefined,
|
||||||
@@ -463,9 +459,7 @@ function decideCatchUp(input: {
|
|||||||
}
|
}
|
||||||
return "replace";
|
return "replace";
|
||||||
}
|
}
|
||||||
return input.current.status === "running" || input.current.status === "complete"
|
return "keep";
|
||||||
? "keep"
|
|
||||||
: "replace";
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function normalizeAgentIds(agentIds: string[]): string[] {
|
function normalizeAgentIds(agentIds: string[]): string[] {
|
||||||
@@ -485,8 +479,7 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
|||||||
const pendingCatchUps = new Map<string, ProjectedTimelineForwardFetchPlan>();
|
const pendingCatchUps = new Map<string, ProjectedTimelineForwardFetchPlan>();
|
||||||
const visibilityCatchUpPending = new Set<string>();
|
const visibilityCatchUpPending = new Set<string>();
|
||||||
const visibilityCatchUpErrors = new Map<string, string>();
|
const visibilityCatchUpErrors = new Map<string, string>();
|
||||||
// User-initiated retries only. Background retries stay silent; a retry the user asked for
|
// A user-initiated retry owes a pending state until it settles.
|
||||||
// owes them a pending state until it settles.
|
|
||||||
const manualRetries = new Set<string>();
|
const manualRetries = new Set<string>();
|
||||||
const loadedCache = new Set<string>();
|
const loadedCache = new Set<string>();
|
||||||
const cacheLoads = new Map<string, Promise<void>>();
|
const cacheLoads = new Map<string, Promise<void>>();
|
||||||
@@ -502,8 +495,6 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
|||||||
let acknowledged: string[] = [];
|
let acknowledged: string[] = [];
|
||||||
let membershipGeneration = 0;
|
let membershipGeneration = 0;
|
||||||
let membershipNeedsRetry = false;
|
let membershipNeedsRetry = false;
|
||||||
let membershipRetryDelayMs: number | undefined;
|
|
||||||
let cancelMembershipRetry: (() => void) | null = null;
|
|
||||||
// Chats this session has opened. Visibility is the only way in, so an agent is never
|
// Chats this session has opened. Visibility is the only way in, so an agent is never
|
||||||
// subscribed — and never resumed on the daemon — until the user actually opens it.
|
// subscribed — and never resumed on the daemon — until the user actually opens it.
|
||||||
// Membership then survives hiding, workspace switches, backgrounding and reconnect;
|
// Membership then survives hiding, workspace switches, backgrounding and reconnect;
|
||||||
@@ -554,7 +545,6 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
|||||||
|
|
||||||
const cancelCatchUp = (agentId: string) => {
|
const cancelCatchUp = (agentId: string) => {
|
||||||
catchUpGenerations.set(agentId, (catchUpGenerations.get(agentId) ?? 0) + 1);
|
catchUpGenerations.set(agentId, (catchUpGenerations.get(agentId) ?? 0) + 1);
|
||||||
catchUps.get(agentId)?.cancelRetry?.();
|
|
||||||
catchUps.delete(agentId);
|
catchUps.delete(agentId);
|
||||||
pendingCatchUps.delete(agentId);
|
pendingCatchUps.delete(agentId);
|
||||||
};
|
};
|
||||||
@@ -598,19 +588,7 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
|||||||
setVisibilityCatchUpReady(agentId);
|
setVisibilityCatchUpReady(agentId);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (catchUps.get(agentId)?.generation === generation) {
|
if (catchUps.get(agentId)?.generation === generation) {
|
||||||
const nextRetryDelayMs = getNextRetryDelayMs(catchUps.get(agentId)?.retryDelayMs);
|
catchUps.set(agentId, { generation, status: "error", request });
|
||||||
const cancelRetry = ports.schedule(() => {
|
|
||||||
const current = catchUps.get(agentId);
|
|
||||||
if (current?.generation !== generation || current.status !== "error") return;
|
|
||||||
startCatchUp(agentId);
|
|
||||||
}, nextRetryDelayMs);
|
|
||||||
catchUps.set(agentId, {
|
|
||||||
generation,
|
|
||||||
status: "error",
|
|
||||||
request,
|
|
||||||
cancelRetry,
|
|
||||||
retryDelayMs: nextRetryDelayMs,
|
|
||||||
});
|
|
||||||
setVisibilityCatchUpError([agentId], error);
|
setVisibilityCatchUpError([agentId], error);
|
||||||
ports.reportError(error);
|
ports.reportError(error);
|
||||||
}
|
}
|
||||||
@@ -677,17 +655,9 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
|||||||
if (decision === "keep") {
|
if (decision === "keep") {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
current?.cancelRetry?.();
|
|
||||||
const generation = (catchUpGenerations.get(agentId) ?? 0) + 1;
|
const generation = (catchUpGenerations.get(agentId) ?? 0) + 1;
|
||||||
catchUpGenerations.set(agentId, generation);
|
catchUpGenerations.set(agentId, generation);
|
||||||
const retryDelayMs =
|
catchUps.set(agentId, { generation, status: "running", request: nextRequest });
|
||||||
supersede || current?.status !== "error" ? undefined : current.retryDelayMs;
|
|
||||||
catchUps.set(agentId, {
|
|
||||||
generation,
|
|
||||||
status: "running",
|
|
||||||
request: nextRequest,
|
|
||||||
retryDelayMs,
|
|
||||||
});
|
|
||||||
pendingCatchUps.delete(agentId);
|
pendingCatchUps.delete(agentId);
|
||||||
void fetchUntilCurrent(
|
void fetchUntilCurrent(
|
||||||
agentId,
|
agentId,
|
||||||
@@ -706,7 +676,7 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
|||||||
for (const agentId of ordered) {
|
for (const agentId of ordered) {
|
||||||
const pendingCatchUp = pendingCatchUps.get(agentId);
|
const pendingCatchUp = pendingCatchUps.get(agentId);
|
||||||
const current = catchUps.get(agentId);
|
const current = catchUps.get(agentId);
|
||||||
// Completion of a different chat must not bypass a failed chat's backoff or
|
// Completion of a different chat must not bypass a failed chat's error or
|
||||||
// supersede an in-flight tail that owns its parked gap recovery.
|
// supersede an in-flight tail that owns its parked gap recovery.
|
||||||
if (current && !(current.status === "complete" && pendingCatchUp)) continue;
|
if (current && !(current.status === "complete" && pendingCatchUp)) continue;
|
||||||
startCatchUp(agentId, {
|
startCatchUp(agentId, {
|
||||||
@@ -732,42 +702,31 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (disposed || !connected || generation !== membershipGeneration) return;
|
if (disposed || !connected || generation !== membershipGeneration) return;
|
||||||
membershipNeedsRetry = true;
|
membershipNeedsRetry = true;
|
||||||
|
acknowledged = [];
|
||||||
|
for (const agentId of requested) cancelCatchUp(agentId);
|
||||||
setVisibilityCatchUpError(requested, error);
|
setVisibilityCatchUpError(requested, error);
|
||||||
cancelMembershipRetry?.();
|
|
||||||
const nextRetryDelayMs = getNextRetryDelayMs(membershipRetryDelayMs);
|
|
||||||
cancelMembershipRetry = ports.schedule(() => {
|
|
||||||
cancelMembershipRetry = null;
|
|
||||||
if (disposed || !connected || membershipGeneration !== generation) return;
|
|
||||||
void reconcileMembership();
|
|
||||||
}, nextRetryDelayMs);
|
|
||||||
membershipRetryDelayMs = nextRetryDelayMs;
|
|
||||||
ports.reportError(error);
|
ports.reportError(error);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (disposed || !connected || generation !== membershipGeneration) return;
|
if (disposed || !connected || generation !== membershipGeneration) return;
|
||||||
cancelMembershipRetry?.();
|
|
||||||
cancelMembershipRetry = null;
|
|
||||||
membershipRetryDelayMs = undefined;
|
|
||||||
acknowledged = requested;
|
acknowledged = requested;
|
||||||
startAcknowledgedCatchUps();
|
startAcknowledgedCatchUps();
|
||||||
};
|
};
|
||||||
|
|
||||||
const retryVisibleAgentTimeline = (agentId: string) => {
|
const retryVisibleAgentTimeline = (agentId: string) => {
|
||||||
if (!isDesired(agentId) || manualRetries.has(agentId)) return;
|
if (!connected || !isDesired(agentId) || manualRetries.has(agentId)) return;
|
||||||
const catchUp = catchUps.get(agentId);
|
const catchUp = catchUps.get(agentId);
|
||||||
const membershipRetryable = membershipNeedsRetry && connected;
|
const membershipRetryable = membershipNeedsRetry && connected;
|
||||||
if (catchUp?.status !== "error" && !membershipRetryable) return;
|
if (catchUp?.status !== "error" && !membershipRetryable) return;
|
||||||
manualRetries.add(agentId);
|
manualRetries.add(agentId);
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
if (catchUp?.status === "error") {
|
if (membershipRetryable) {
|
||||||
catchUp.cancelRetry?.();
|
void reconcileMembership();
|
||||||
startCatchUp(agentId, { request: catchUp.request, supersede: true });
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
cancelMembershipRetry?.();
|
if (catchUp?.status === "error") {
|
||||||
cancelMembershipRetry = null;
|
startCatchUp(agentId, { request: catchUp.request, supersede: true });
|
||||||
membershipRetryDelayMs = undefined;
|
}
|
||||||
void reconcileMembership();
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const commitDesiredMembership = (
|
const commitDesiredMembership = (
|
||||||
@@ -808,8 +767,6 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
|||||||
ensureCacheLoaded(agentId);
|
ensureCacheLoaded(agentId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
cancelMembershipRetry?.();
|
|
||||||
cancelMembershipRetry = null;
|
|
||||||
desired = nextDesired;
|
desired = nextDesired;
|
||||||
ports.replaceDemandedAgentIds(desired);
|
ports.replaceDemandedAgentIds(desired);
|
||||||
membershipGeneration += 1;
|
membershipGeneration += 1;
|
||||||
@@ -860,6 +817,7 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
for (const agentId of visibleAgentIds()) {
|
for (const agentId of visibleAgentIds()) {
|
||||||
|
if (visibilityCatchUpErrors.has(agentId)) continue;
|
||||||
visibilityCatchUpPending.add(agentId);
|
visibilityCatchUpPending.add(agentId);
|
||||||
visibilityCatchUpErrors.delete(agentId);
|
visibilityCatchUpErrors.delete(agentId);
|
||||||
startCatchUp(agentId, { supersede: true });
|
startCatchUp(agentId, { supersede: true });
|
||||||
@@ -871,9 +829,6 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
|||||||
connected = nextConnected;
|
connected = nextConnected;
|
||||||
if (!connected) {
|
if (!connected) {
|
||||||
commitDesiredMembership(desired, { resetCatchUpStatus: true });
|
commitDesiredMembership(desired, { resetCatchUpStatus: true });
|
||||||
cancelMembershipRetry?.();
|
|
||||||
cancelMembershipRetry = null;
|
|
||||||
membershipRetryDelayMs = undefined;
|
|
||||||
void observation?.handle.release().catch(ports.reportError);
|
void observation?.handle.release().catch(ports.reportError);
|
||||||
observation = null;
|
observation = null;
|
||||||
acknowledged = [];
|
acknowledged = [];
|
||||||
@@ -885,7 +840,7 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
|||||||
void reconcileMembership();
|
void reconcileMembership();
|
||||||
},
|
},
|
||||||
recoverGap(agentId, cursor) {
|
recoverGap(agentId, cursor) {
|
||||||
if (!isDesired(agentId)) return;
|
if (!isDesired(agentId) || catchUps.get(agentId)?.status === "error") return;
|
||||||
startCatchUp(agentId, {
|
startCatchUp(agentId, {
|
||||||
request: planTimelineCatchUpAfter({ epoch: cursor.epoch, seq: cursor.endSeq }),
|
request: planTimelineCatchUpAfter({ epoch: cursor.epoch, seq: cursor.endSeq }),
|
||||||
supersede: true,
|
supersede: true,
|
||||||
@@ -895,10 +850,7 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
|||||||
disposed = true;
|
disposed = true;
|
||||||
void observation?.handle.release().catch(ports.reportError);
|
void observation?.handle.release().catch(ports.reportError);
|
||||||
observation = null;
|
observation = null;
|
||||||
cancelMembershipRetry?.();
|
|
||||||
cancelMembershipRetry = null;
|
|
||||||
membershipNeedsRetry = false;
|
membershipNeedsRetry = false;
|
||||||
membershipRetryDelayMs = undefined;
|
|
||||||
sources.clear();
|
sources.clear();
|
||||||
membershipGeneration += 1;
|
membershipGeneration += 1;
|
||||||
for (const agentId of desired) cancelCatchUp(agentId);
|
for (const agentId of desired) cancelCatchUp(agentId);
|
||||||
|
|||||||
@@ -1,10 +1,16 @@
|
|||||||
import { useMemo } from "react";
|
|
||||||
import type { TFunction } from "i18next";
|
import type { TFunction } from "i18next";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { Text, View, type StyleProp, type ViewStyle } from "react-native";
|
import { Text, View } from "react-native";
|
||||||
import { StyleSheet } from "react-native-unistyles";
|
import { StyleSheet } from "react-native-unistyles";
|
||||||
import { clampPct, formatAmount, formatProviderUsageLabel, formatResetLabel } from "./format";
|
import {
|
||||||
import type { UsageBalance, UsageTone } from "./types";
|
formatAmount,
|
||||||
|
formatProviderUsageLabel,
|
||||||
|
formatResetLabel,
|
||||||
|
formatResetTime,
|
||||||
|
} from "./format";
|
||||||
|
import { UsageMeter } from "./meter";
|
||||||
|
import { UsageResetLine } from "./reset-line";
|
||||||
|
import type { UsageBalance } from "./types";
|
||||||
import { useRelativeTimeTick } from "./use-relative-time-tick";
|
import { useRelativeTimeTick } from "./use-relative-time-tick";
|
||||||
|
|
||||||
interface ResolvedBalance {
|
interface ResolvedBalance {
|
||||||
@@ -41,19 +47,6 @@ function resolveBalance({
|
|||||||
return { amountText: "—", usedPct: null };
|
return { amountText: "—", usedPct: null };
|
||||||
}
|
}
|
||||||
|
|
||||||
function fillToneStyle(tone: UsageTone) {
|
|
||||||
switch (tone) {
|
|
||||||
case "ok":
|
|
||||||
return styles.fillOk;
|
|
||||||
case "warning":
|
|
||||||
return styles.fillWarning;
|
|
||||||
case "danger":
|
|
||||||
return styles.fillDanger;
|
|
||||||
default:
|
|
||||||
return styles.fillDefault;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function UsageBalanceBar({
|
export function UsageBalanceBar({
|
||||||
balance,
|
balance,
|
||||||
retained = false,
|
retained = false,
|
||||||
@@ -66,11 +59,7 @@ export function UsageBalanceBar({
|
|||||||
const { amountText, usedPct } = resolveBalance({ balance, t, locale: i18n.resolvedLanguage });
|
const { amountText, usedPct } = resolveBalance({ balance, t, locale: i18n.resolvedLanguage });
|
||||||
const tone = balance.tone ?? "default";
|
const tone = balance.tone ?? "default";
|
||||||
const resetLabel = formatResetLabel(balance.resetsAt, retained, now, t);
|
const resetLabel = formatResetLabel(balance.resetsAt, retained, now, t);
|
||||||
|
const resetTime = formatResetTime(balance.resetsAt, now, t);
|
||||||
const fillStyle = useMemo<StyleProp<ViewStyle>>(
|
|
||||||
() => [styles.fill, fillToneStyle(tone), { width: `${clampPct(usedPct ?? 0)}%` }],
|
|
||||||
[usedPct, tone],
|
|
||||||
);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<View style={styles.container}>
|
<View style={styles.container}>
|
||||||
@@ -78,22 +67,21 @@ export function UsageBalanceBar({
|
|||||||
<Text style={styles.label} numberOfLines={1}>
|
<Text style={styles.label} numberOfLines={1}>
|
||||||
{formatProviderUsageLabel(balance.id, balance.label, t)}
|
{formatProviderUsageLabel(balance.id, balance.label, t)}
|
||||||
</Text>
|
</Text>
|
||||||
<View style={styles.value} testID={`provider-usage-balance-${balance.id}-value`}>
|
<Text
|
||||||
<Text style={styles.amount} numberOfLines={1} ellipsizeMode="tail">
|
style={styles.amount}
|
||||||
{amountText}
|
numberOfLines={1}
|
||||||
</Text>
|
ellipsizeMode="tail"
|
||||||
{resetLabel ? (
|
testID={`provider-usage-balance-${balance.id}-value`}
|
||||||
<Text style={styles.reset} testID={`provider-usage-balance-${balance.id}-reset`}>
|
>
|
||||||
{resetLabel}
|
{amountText}
|
||||||
</Text>
|
</Text>
|
||||||
) : null}
|
|
||||||
</View>
|
|
||||||
</View>
|
</View>
|
||||||
{usedPct != null ? (
|
{usedPct != null ? <UsageMeter percent={usedPct} tone={tone} /> : null}
|
||||||
<View style={styles.track}>
|
<UsageResetLine
|
||||||
<View style={fillStyle} />
|
countdown={resetLabel}
|
||||||
</View>
|
exactTime={resetTime}
|
||||||
) : null}
|
testID={`provider-usage-balance-${balance.id}-reset`}
|
||||||
|
/>
|
||||||
</View>
|
</View>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -110,44 +98,13 @@ const styles = StyleSheet.create((theme) => ({
|
|||||||
},
|
},
|
||||||
label: {
|
label: {
|
||||||
flexShrink: 1,
|
flexShrink: 1,
|
||||||
color: theme.colors.foregroundMuted,
|
|
||||||
fontSize: theme.fontSize.sm,
|
|
||||||
},
|
|
||||||
value: {
|
|
||||||
flexShrink: 1,
|
|
||||||
alignItems: "flex-end",
|
|
||||||
},
|
|
||||||
amount: {
|
|
||||||
color: theme.colors.foreground,
|
color: theme.colors.foreground,
|
||||||
fontSize: theme.fontSize.sm,
|
fontSize: theme.fontSize.sm,
|
||||||
fontWeight: theme.fontWeight.medium,
|
fontWeight: theme.fontWeight.medium,
|
||||||
},
|
},
|
||||||
reset: {
|
amount: {
|
||||||
color: theme.colors.foregroundMuted,
|
flexShrink: 1,
|
||||||
|
color: theme.colors.foreground,
|
||||||
fontSize: theme.fontSize.sm,
|
fontSize: theme.fontSize.sm,
|
||||||
fontWeight: theme.fontWeight.normal,
|
|
||||||
textAlign: "right",
|
|
||||||
},
|
|
||||||
track: {
|
|
||||||
height: 4,
|
|
||||||
borderRadius: 2,
|
|
||||||
backgroundColor: theme.colors.surface3,
|
|
||||||
overflow: "hidden",
|
|
||||||
},
|
|
||||||
fill: {
|
|
||||||
height: 4,
|
|
||||||
borderRadius: 2,
|
|
||||||
},
|
|
||||||
fillDefault: {
|
|
||||||
backgroundColor: theme.colors.foregroundMuted,
|
|
||||||
},
|
|
||||||
fillOk: {
|
|
||||||
backgroundColor: theme.colors.statusSuccess,
|
|
||||||
},
|
|
||||||
fillWarning: {
|
|
||||||
backgroundColor: theme.colors.statusWarning,
|
|
||||||
},
|
|
||||||
fillDanger: {
|
|
||||||
backgroundColor: theme.colors.statusDanger,
|
|
||||||
},
|
},
|
||||||
}));
|
}));
|
||||||
|
|||||||
@@ -21,10 +21,12 @@ export interface UsageHostSelection {
|
|||||||
*/
|
*/
|
||||||
export function UsageControls({
|
export function UsageControls({
|
||||||
view,
|
view,
|
||||||
|
serverId,
|
||||||
onRefresh,
|
onRefresh,
|
||||||
hostSelection,
|
hostSelection,
|
||||||
}: {
|
}: {
|
||||||
view: UsageView;
|
view: UsageView;
|
||||||
|
serverId: string;
|
||||||
onRefresh: () => void;
|
onRefresh: () => void;
|
||||||
hostSelection?: UsageHostSelection;
|
hostSelection?: UsageHostSelection;
|
||||||
}) {
|
}) {
|
||||||
@@ -43,8 +45,8 @@ export function UsageControls({
|
|||||||
) : null}
|
) : null}
|
||||||
{view.kind === "unavailable" ? null : (
|
{view.kind === "unavailable" ? null : (
|
||||||
<>
|
<>
|
||||||
<UsageRefreshButton busy={busy} onRefresh={onRefresh} />
|
{view.kind === "off" ? null : <UsageRefreshButton busy={busy} onRefresh={onRefresh} />}
|
||||||
<UsageOptions />
|
<UsageOptions serverId={serverId} />
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</View>
|
</View>
|
||||||
@@ -84,7 +86,12 @@ export function useHostUsageWithControls(hostSelection: UsageHostSelection): {
|
|||||||
const controls = useMemo(
|
const controls = useMemo(
|
||||||
() =>
|
() =>
|
||||||
hasControls ? (
|
hasControls ? (
|
||||||
<UsageControls view={view} onRefresh={refresh} hostSelection={hostSelection} />
|
<UsageControls
|
||||||
|
serverId={hostSelection.serverId}
|
||||||
|
view={view}
|
||||||
|
onRefresh={refresh}
|
||||||
|
hostSelection={hostSelection}
|
||||||
|
/>
|
||||||
) : null,
|
) : null,
|
||||||
[hasControls, hostSelection, refresh, view],
|
[hasControls, hostSelection, refresh, view],
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,7 +1,5 @@
|
|||||||
import { useCallback, useMemo } from "react";
|
import { useCallback, useMemo } from "react";
|
||||||
import { useAppSettings } from "@/hooks/use-settings";
|
import { useAppSettings } from "@/hooks/use-settings";
|
||||||
import { useUsageHostId } from "./hosts";
|
|
||||||
import { useUsageHostReports } from "./queries";
|
|
||||||
import {
|
import {
|
||||||
isUsagePinned,
|
isUsagePinned,
|
||||||
setUsageDisplayAs,
|
setUsageDisplayAs,
|
||||||
@@ -25,12 +23,6 @@ interface UsagePreferencesState {
|
|||||||
display: UsageDisplay;
|
display: UsageDisplay;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The device's usage preferences, with pins resolved against a host's reports. */
|
|
||||||
export function useUsagePreferences(serverId?: string): UsagePreferencesState {
|
|
||||||
const defaultServerId = useUsageHostId();
|
|
||||||
return useUsageDisplay(useUsageHostReports(serverId ?? defaultServerId));
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The device's usage preferences, with pins resolved against the given reports. */
|
/** The device's usage preferences, with pins resolved against the given reports. */
|
||||||
export function useUsageDisplay(reports: readonly UsageReportEntry[]): UsagePreferencesState {
|
export function useUsageDisplay(reports: readonly UsageReportEntry[]): UsagePreferencesState {
|
||||||
const { settings, updateSettings } = useAppSettings();
|
const { settings, updateSettings } = useAppSettings();
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import {
|
|||||||
formatPct,
|
formatPct,
|
||||||
formatProviderUsageLabel,
|
formatProviderUsageLabel,
|
||||||
formatResetLabel,
|
formatResetLabel,
|
||||||
|
formatResetTime,
|
||||||
formatRunsOutLabel,
|
formatRunsOutLabel,
|
||||||
} from "./format";
|
} from "./format";
|
||||||
|
|
||||||
@@ -36,8 +37,8 @@ describe("formatAmount", () => {
|
|||||||
const threeDaysAgo = new Date(NOW - 3 * 24 * 60 * 60 * 1000).toISOString();
|
const threeDaysAgo = new Date(NOW - 3 * 24 * 60 * 60 * 1000).toISOString();
|
||||||
|
|
||||||
expect(formatPct(7, "en")).toBe("7%");
|
expect(formatPct(7, "en")).toBe("7%");
|
||||||
expect(formatResetLabel(twoHoursFromNow, false, NOW)).toBe("resets 2h");
|
expect(formatResetLabel(twoHoursFromNow, false, NOW)).toBe("resets in 2h");
|
||||||
expect(formatRunsOutLabel(twoHoursFromNow, NOW)).toBe("runs out 2h");
|
expect(formatRunsOutLabel(twoHoursFromNow, NOW)).toBe("runs out in 2h");
|
||||||
|
|
||||||
await i18n.changeLanguage("ja");
|
await i18n.changeLanguage("ja");
|
||||||
expect(formatResetLabel(twoHoursFromNow, false, NOW)).toBe("2時間後にリセット");
|
expect(formatResetLabel(twoHoursFromNow, false, NOW)).toBe("2時間後にリセット");
|
||||||
@@ -94,6 +95,70 @@ describe("formatAmount", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("reset countdown", () => {
|
||||||
|
const MINUTE = 60_000;
|
||||||
|
const HOUR = 60 * MINUTE;
|
||||||
|
const DAY = 24 * HOUR;
|
||||||
|
const countdown = (ms: number) => formatResetLabel(new Date(NOW + ms).toISOString(), false, NOW);
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
await i18n.changeLanguage("en");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps counting down inside a day instead of sitting on the rounded-down day", () => {
|
||||||
|
expect(countdown(2 * DAY + 23 * HOUR + 10 * MINUTE)).toBe("resets in 2d 23h");
|
||||||
|
expect(countdown(2 * DAY + 22 * HOUR + 10 * MINUTE)).toBe("resets in 2d 22h");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("says two units, dropping a unit that is zero", () => {
|
||||||
|
expect(countdown(DAY + 30 * MINUTE)).toBe("resets in 1d");
|
||||||
|
expect(countdown(4 * HOUR + 59 * MINUTE)).toBe("resets in 4h 59m");
|
||||||
|
expect(countdown(HOUR)).toBe("resets in 1h");
|
||||||
|
expect(countdown(37 * MINUTE)).toBe("resets in 37m");
|
||||||
|
expect(countdown(59 * 1000)).toBe("resets in 0m");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("joins the at-risk countdown the same way", () => {
|
||||||
|
const iso = new Date(NOW + 3 * HOUR + 5 * MINUTE).toISOString();
|
||||||
|
expect(formatRunsOutLabel(iso, NOW)).toBe("runs out in 3h 5m");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("exact reset time", () => {
|
||||||
|
// Local-time dates, so the thresholds hold in any timezone the tests run in.
|
||||||
|
const now = new Date(2026, 9, 29, 12, 0).getTime();
|
||||||
|
const at = (...args: [number, number, number, number, number]) =>
|
||||||
|
formatResetTime(new Date(...args).toISOString(), now)?.replace(/\s/g, " ");
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
await i18n.changeLanguage("en");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows only the time within 24 hours", () => {
|
||||||
|
expect(at(2026, 9, 29, 15, 0)).toMatch(/^(3:00 PM|15:00)$/);
|
||||||
|
expect(at(2026, 9, 30, 11, 59)).toMatch(/^(11:59 AM|11:59)$/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("adds the weekday within 7 days", () => {
|
||||||
|
expect(at(2026, 9, 30, 12, 0)).toMatch(/^Fri (12:00 PM|12:00)$/);
|
||||||
|
expect(at(2026, 10, 5, 11, 59)).toMatch(/^Thu (11:59 AM|11:59)$/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("adds the date after 7 days", () => {
|
||||||
|
expect(at(2026, 10, 5, 12, 0)).toMatch(/^Nov 5, (12:00 PM|12:00)$/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("names the weekday in the app language", async () => {
|
||||||
|
await i18n.changeLanguage("fr");
|
||||||
|
expect(at(2026, 9, 31, 15, 0)).toMatch(/^sam\.? /);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("says nothing for a time that has passed", () => {
|
||||||
|
expect(formatResetTime(new Date(now - 1).toISOString(), now)).toBeNull();
|
||||||
|
expect(formatResetTime(null, now)).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
it("retained reset times that have passed do not claim the quota is resetting", () => {
|
it("retained reset times that have passed do not claim the quota is resetting", () => {
|
||||||
const past = "2000-01-01T00:00:00.000Z";
|
const past = "2000-01-01T00:00:00.000Z";
|
||||||
expect(formatResetLabel(past, true)).toBe("Reset time passed");
|
expect(formatResetLabel(past, true)).toBe("Reset time passed");
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import type { TFunction } from "i18next";
|
import type { TFunction } from "i18next";
|
||||||
import { i18n } from "@/i18n/i18next";
|
import { i18n } from "@/i18n/i18next";
|
||||||
|
import { formatTimeOfDay } from "@/utils/time";
|
||||||
import type { UsageDisplayAs } from "./preferences";
|
import type { UsageDisplayAs } from "./preferences";
|
||||||
import type { UsageBalanceUnit } from "./types";
|
import type { UsageBalanceUnit } from "./types";
|
||||||
|
|
||||||
@@ -50,7 +51,17 @@ export function formatDisplayPct(
|
|||||||
: t("providerUsage.values.remaining", { amount: percentage });
|
: t("providerUsage.values.remaining", { amount: percentage });
|
||||||
}
|
}
|
||||||
|
|
||||||
type RelativeDuration = { unit: "now" } | { unit: "minutes" | "hours" | "days"; count: number };
|
type DurationUnit = "minutes" | "hours" | "days";
|
||||||
|
interface DurationPart {
|
||||||
|
unit: DurationUnit;
|
||||||
|
count: number;
|
||||||
|
}
|
||||||
|
/** Two units, floored, so a countdown keeps moving: "2d 23h", "4h 59m", "37m". */
|
||||||
|
type RelativeDuration = { kind: "now" } | { kind: "remaining"; parts: DurationPart[] };
|
||||||
|
|
||||||
|
const MINUTE_MS = 60_000;
|
||||||
|
const HOUR_MS = 60 * MINUTE_MS;
|
||||||
|
const DAY_MS = 24 * HOUR_MS;
|
||||||
|
|
||||||
function formatCount(value: number): string {
|
function formatCount(value: number): string {
|
||||||
return new Intl.NumberFormat(i18n.resolvedLanguage).format(value);
|
return new Intl.NumberFormat(i18n.resolvedLanguage).format(value);
|
||||||
@@ -59,35 +70,34 @@ function formatCount(value: number): string {
|
|||||||
function relativeDuration(iso: string, now: number): RelativeDuration | null {
|
function relativeDuration(iso: string, now: number): RelativeDuration | null {
|
||||||
const diffMs = new Date(iso).getTime() - now;
|
const diffMs = new Date(iso).getTime() - now;
|
||||||
if (!Number.isFinite(diffMs)) return null;
|
if (!Number.isFinite(diffMs)) return null;
|
||||||
if (diffMs <= 0) return { unit: "now" };
|
if (diffMs <= 0) return { kind: "now" };
|
||||||
const diffMinutes = Math.floor(diffMs / 60_000);
|
const days = Math.floor(diffMs / DAY_MS);
|
||||||
const diffHours = Math.floor(diffMinutes / 60);
|
const hours = Math.floor((diffMs % DAY_MS) / HOUR_MS);
|
||||||
const diffDays = Math.floor(diffHours / 24);
|
const minutes = Math.floor((diffMs % HOUR_MS) / MINUTE_MS);
|
||||||
if (diffDays > 0) return { unit: "days", count: diffDays };
|
if (days > 0) return remaining({ unit: "days", count: days }, { unit: "hours", count: hours });
|
||||||
if (diffHours > 0) return { unit: "hours", count: diffHours };
|
if (hours > 0)
|
||||||
return { unit: "minutes", count: diffMinutes };
|
return remaining({ unit: "hours", count: hours }, { unit: "minutes", count: minutes });
|
||||||
|
return remaining({ unit: "minutes", count: minutes });
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatRelativeDuration(duration: RelativeDuration, t: TFunction): string | null {
|
/** The major unit, plus the minor one unless it is zero. */
|
||||||
switch (duration.unit) {
|
function remaining(major: DurationPart, minor?: DurationPart): RelativeDuration {
|
||||||
case "now":
|
return { kind: "remaining", parts: minor && minor.count > 0 ? [major, minor] : [major] };
|
||||||
return null;
|
}
|
||||||
case "days":
|
|
||||||
return t("providerUsage.duration.days", {
|
function formatDurationPart(part: DurationPart, t: TFunction): string {
|
||||||
count: duration.count,
|
return t(`providerUsage.duration.${part.unit}`, {
|
||||||
value: formatCount(duration.count),
|
count: part.count,
|
||||||
});
|
value: formatCount(part.count),
|
||||||
case "hours":
|
});
|
||||||
return t("providerUsage.duration.hours", {
|
}
|
||||||
count: duration.count,
|
|
||||||
value: formatCount(duration.count),
|
function formatRelativeDuration(
|
||||||
});
|
duration: Extract<RelativeDuration, { kind: "remaining" }>,
|
||||||
case "minutes":
|
t: TFunction,
|
||||||
return t("providerUsage.duration.minutes", {
|
): string {
|
||||||
count: duration.count,
|
const [first, second] = duration.parts.map((part) => formatDurationPart(part, t));
|
||||||
value: formatCount(duration.count),
|
return second ? t("providerUsage.duration.pair", { first, second }) : first;
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function formatResetLabel(
|
export function formatResetLabel(
|
||||||
@@ -99,10 +109,34 @@ export function formatResetLabel(
|
|||||||
if (!iso) return null;
|
if (!iso) return null;
|
||||||
const rel = relativeDuration(iso, now);
|
const rel = relativeDuration(iso, now);
|
||||||
if (!rel) return null;
|
if (!rel) return null;
|
||||||
if (rel.unit === "now" && retained) return t("providerUsage.timing.resetTimePassed");
|
if (rel.kind === "now" && retained) return t("providerUsage.timing.resetTimePassed");
|
||||||
if (rel.unit === "now") return t("providerUsage.timing.resettingNow");
|
if (rel.kind === "now") return t("providerUsage.timing.resettingNow");
|
||||||
const duration = formatRelativeDuration(rel, t);
|
return t("providerUsage.timing.resetsIn", { duration: formatRelativeDuration(rel, t) });
|
||||||
return duration ? t("providerUsage.timing.resetsIn", { duration }) : null;
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* When a window resets on the clock: "3:00 PM" within a day, "Fri 3:00 PM" within a week,
|
||||||
|
* "Oct 31, 3:00 PM" after that. Names follow the app language; 12/24h follows the device.
|
||||||
|
* Nothing for a time that has passed, where the countdown already says so.
|
||||||
|
*/
|
||||||
|
export function formatResetTime(
|
||||||
|
iso: string | null | undefined,
|
||||||
|
now = Date.now(),
|
||||||
|
t: TFunction = i18n.t,
|
||||||
|
): string | null {
|
||||||
|
if (!iso) return null;
|
||||||
|
const at = new Date(iso);
|
||||||
|
const diffMs = at.getTime() - now;
|
||||||
|
if (!Number.isFinite(diffMs) || diffMs <= 0) return null;
|
||||||
|
const time = formatTimeOfDay(at);
|
||||||
|
const locale = i18n.resolvedLanguage;
|
||||||
|
if (diffMs < DAY_MS) return time;
|
||||||
|
if (diffMs < 7 * DAY_MS) {
|
||||||
|
const weekday = at.toLocaleDateString(locale, { weekday: "short" });
|
||||||
|
return t("providerUsage.timing.resetsAtWeekday", { weekday, time });
|
||||||
|
}
|
||||||
|
const date = at.toLocaleDateString(locale, { month: "short", day: "numeric" });
|
||||||
|
return t("providerUsage.timing.resetsAtDate", { date, time });
|
||||||
}
|
}
|
||||||
|
|
||||||
export function formatRunsOutLabel(
|
export function formatRunsOutLabel(
|
||||||
@@ -113,9 +147,8 @@ export function formatRunsOutLabel(
|
|||||||
if (!iso) return null;
|
if (!iso) return null;
|
||||||
const rel = relativeDuration(iso, now);
|
const rel = relativeDuration(iso, now);
|
||||||
if (!rel) return null;
|
if (!rel) return null;
|
||||||
if (rel.unit === "now") return t("providerUsage.timing.runsOutNow");
|
if (rel.kind === "now") return t("providerUsage.timing.runsOutNow");
|
||||||
const duration = formatRelativeDuration(rel, t);
|
return t("providerUsage.timing.runsOutIn", { duration: formatRelativeDuration(rel, t) });
|
||||||
return duration ? t("providerUsage.timing.runsOutIn", { duration }) : null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function formatAgo(
|
export function formatAgo(
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { useUsagePreferences } from "./display";
|
import { useUsageDisplay } from "./display";
|
||||||
import { useHostUsage } from "./queries";
|
import { useHostUsage } from "./queries";
|
||||||
import { UsageSection } from "./usage-section";
|
import { UsageSection } from "./usage-section";
|
||||||
|
|
||||||
@@ -7,7 +7,7 @@ import { UsageSection } from "./usage-section";
|
|||||||
export function HostUsageSection({ serverId }: { serverId: string }) {
|
export function HostUsageSection({ serverId }: { serverId: string }) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const { view, refresh } = useHostUsage(serverId);
|
const { view, refresh } = useHostUsage(serverId);
|
||||||
const { display } = useUsagePreferences(serverId);
|
const { display } = useUsageDisplay(view.kind === "ready" ? view.reports : []);
|
||||||
return (
|
return (
|
||||||
<UsageSection
|
<UsageSection
|
||||||
serverId={serverId}
|
serverId={serverId}
|
||||||
|
|||||||
@@ -4,6 +4,6 @@ export { useHostReportsUsage } from "./queries";
|
|||||||
export {
|
export {
|
||||||
UsageSidebarItem,
|
UsageSidebarItem,
|
||||||
UsageSidebarRoot,
|
UsageSidebarRoot,
|
||||||
useHasUsageSummary,
|
useUsageSummary,
|
||||||
useOpenSidebarUsage,
|
useOpenSidebarUsage,
|
||||||
} from "./sidebar-item";
|
} from "./sidebar-item";
|
||||||
|
|||||||
@@ -46,8 +46,8 @@ export function UsageMeter({
|
|||||||
|
|
||||||
const styles = StyleSheet.create((theme) => ({
|
const styles = StyleSheet.create((theme) => ({
|
||||||
track: {
|
track: {
|
||||||
height: 4,
|
height: 6,
|
||||||
borderRadius: 2,
|
borderRadius: 3,
|
||||||
backgroundColor: theme.colors.surface3,
|
backgroundColor: theme.colors.surface3,
|
||||||
overflow: "hidden",
|
overflow: "hidden",
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -405,3 +405,15 @@ it("available and retained usage show the same successful completion time", () =
|
|||||||
);
|
);
|
||||||
expect(upsertReport([failure], success)).toEqual([failure]);
|
expect(upsertReport([failure], success)).toEqual([failure]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("disabled host shows off even with cached reports", () => {
|
||||||
|
expect(
|
||||||
|
resolveUsageView({
|
||||||
|
hostLabel: "Laptop",
|
||||||
|
isConnected: true,
|
||||||
|
supportsUsage: true,
|
||||||
|
enabled: false,
|
||||||
|
query: { data: [], error: null, isFetching: false },
|
||||||
|
}),
|
||||||
|
).toMatchObject({ kind: "off" });
|
||||||
|
});
|
||||||
|
|||||||
@@ -106,6 +106,7 @@ export interface UsageQueryState {
|
|||||||
|
|
||||||
export function resolveUsageView(
|
export function resolveUsageView(
|
||||||
input: {
|
input: {
|
||||||
|
enabled?: boolean;
|
||||||
hostLabel: string;
|
hostLabel: string;
|
||||||
isConnected: boolean;
|
isConnected: boolean;
|
||||||
supportsUsage: boolean;
|
supportsUsage: boolean;
|
||||||
@@ -125,6 +126,8 @@ export function resolveUsageView(
|
|||||||
message: t("providerUsage.hostUpgradeRequired", { host: hostLabel }),
|
message: t("providerUsage.hostUpgradeRequired", { host: hostLabel }),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
if (input.enabled === false)
|
||||||
|
return { kind: "off", message: t("providerUsage.off", { host: hostLabel }) };
|
||||||
if (query?.data) {
|
if (query?.data) {
|
||||||
return { kind: "ready", reports: query.data, isRefreshing: query.isFetching };
|
return { kind: "ready", reports: query.data, isRefreshing: query.isFetching };
|
||||||
}
|
}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user