mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-25 09:46:05 +00:00
Compare commits
59
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ddd23f4cf9 | ||
|
|
13734eeba9 | ||
|
|
51f04592d5 | ||
|
|
2dd7bf6525 | ||
|
|
393d0608dd | ||
|
|
aa0a91ff6c | ||
|
|
a99a731430 | ||
|
|
201972f548 | ||
|
|
270f25458a | ||
|
|
b7af3da71f | ||
|
|
2789421fbd | ||
|
|
b7b5acf086 | ||
|
|
8b2e14f3d2 | ||
|
|
da74f7de1f | ||
|
|
767c1efa03 | ||
|
|
e03fe0d8e7 | ||
|
|
ff27da07bf | ||
|
|
1fea66215d | ||
|
|
ecb2501458 | ||
|
|
065e4a95b1 | ||
|
|
309a44c480 | ||
|
|
5f424e2e94 | ||
|
|
4d472c2804 | ||
|
|
182c1aa192 | ||
|
|
8fa709532c | ||
|
|
6e4f2ef8da | ||
|
|
34abe8f08f | ||
|
|
3389138eb7 | ||
|
|
eedb6ff675 | ||
|
|
cd66d8fd18 | ||
|
|
a48e9edce5 | ||
|
|
df9886b2f1 | ||
|
|
8fa22b39eb | ||
|
|
80c44321cc | ||
|
|
576b9b552b | ||
|
|
175d858e05 | ||
|
|
112c4b78e1 | ||
|
|
8d287e5f56 | ||
|
|
bf83a03ce9 | ||
|
|
80240eb851 | ||
|
|
0c11263d4d | ||
|
|
28c9806da8 | ||
|
|
a0add767c0 | ||
|
|
25f637e57c | ||
|
|
53fa9524cf | ||
|
|
5a8383d237 | ||
|
|
cf3caefa14 | ||
|
|
c747a58871 | ||
|
|
c36d398829 | ||
|
|
183bc736ec | ||
|
|
c4ce21a237 | ||
|
|
9a2236dac3 | ||
|
|
ecd0dd083e | ||
|
|
10c443a32b | ||
|
|
457d8d6ec5 | ||
|
|
80879eaf7c | ||
|
|
dc85c2bfbc | ||
|
|
5ed1f8d108 | ||
|
|
4178497d3d |
@@ -50,6 +50,7 @@ desktop:
|
||||
app:
|
||||
- "packages/app/**"
|
||||
- "packages/expo-two-way-audio/**"
|
||||
- "packages/react-native-enriched-markdown/**"
|
||||
|
||||
sdk:
|
||||
- "packages/plugin/**"
|
||||
@@ -80,6 +81,7 @@ browser:
|
||||
- "packages/app/index.ts"
|
||||
- "packages/app/*config.{cjs,js,ts}"
|
||||
- "packages/app/package.json"
|
||||
- "packages/react-native-enriched-markdown/**"
|
||||
|
||||
relay:
|
||||
- "packages/relay/**"
|
||||
|
||||
@@ -299,10 +299,7 @@ jobs:
|
||||
run: npm run test:integration --workspace=@getpaseo/server
|
||||
env: *server_test_env
|
||||
|
||||
# native-recursive.ts serves darwin and win32, but windows-latest above is the only
|
||||
# runner that exercises it. macOS — the platform the reported watcher bug was on —
|
||||
# otherwise has no server-test coverage. Keep this job scoped to regressions
|
||||
# reported on macOS.
|
||||
# Keep this job scoped to regressions reported on macOS.
|
||||
server-tests-macos:
|
||||
name: server-tests (macos-latest, file observation)
|
||||
needs: changes
|
||||
@@ -330,12 +327,24 @@ jobs:
|
||||
src/server/workspace-git-service.observation.integration.test.ts \
|
||||
--bail=1
|
||||
|
||||
- name: Verify path casing on macOS
|
||||
run: |
|
||||
npm run test:unit --workspace=@getpaseo/server -- \
|
||||
src/server/agent/agent-storage.test.ts \
|
||||
src/utils/directory-suggestions.test.ts \
|
||||
--bail=1
|
||||
|
||||
- name: Verify plugin compiler children are reaped
|
||||
run: |
|
||||
npm run test:unit --workspace=@getpaseo/server -- \
|
||||
src/server/plugins/index.posix.test.ts \
|
||||
-t "reaps compiler children" --bail=1
|
||||
|
||||
- name: Verify plugin session sockets survive a dead plugin child
|
||||
run: |
|
||||
npm run test:unit --workspace=@getpaseo/server -- \
|
||||
src/server/plugins/session-socket.posix.test.ts --bail=1
|
||||
|
||||
desktop-tests-ubuntu:
|
||||
name: desktop-tests (ubuntu-latest)
|
||||
needs: changes
|
||||
|
||||
+6
-1
@@ -11,5 +11,10 @@
|
||||
"arrowParens": "always",
|
||||
"bracketSameLine": false,
|
||||
"bracketSpacing": true,
|
||||
"ignorePatterns": ["*.lock", "**/*.gen.ts", "**/*.gen.tsx"]
|
||||
"ignorePatterns": [
|
||||
"*.lock",
|
||||
"**/*.gen.ts",
|
||||
"**/*.gen.tsx",
|
||||
"packages/react-native-enriched-markdown/**"
|
||||
]
|
||||
}
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@
|
||||
"options": {
|
||||
"typeAware": false
|
||||
},
|
||||
"ignorePatterns": [".dev/**"],
|
||||
"ignorePatterns": [".dev/**", "packages/react-native-enriched-markdown/**"],
|
||||
"plugins": ["react", "react-perf", "unicorn", "typescript", "oxc", "import", "promise"],
|
||||
"jsPlugins": ["./scripts/oxlint/paseo-plugin.mjs"],
|
||||
"categories": {
|
||||
|
||||
@@ -1,5 +1,25 @@
|
||||
# Changelog
|
||||
|
||||
## 0.17.4 - 2026-11-23
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed numbered sublists overlapping their text and quotes inside lists overlapping later messages on Android ([#10499](https://github.com/getpaseo/paseo/pull/10499))
|
||||
- Fixed Android terminal input so it asks the keyboard to exclude typed text from personalized learning ([#10586](https://github.com/getpaseo/paseo/pull/10586))
|
||||
- Fixed conversations disappearing when directory capitalization differs on a case-insensitive file system ([#10555](https://github.com/getpaseo/paseo/pull/10555) by [@yzim](https://github.com/yzim))
|
||||
- Fixed interrupt and steer messages to archived agents being queued without starting a turn ([#10611](https://github.com/getpaseo/paseo/pull/10611) by [@thomasvan](https://github.com/thomasvan))
|
||||
- Fixed Hermes Shell rows omitting part of the command ([#10614](https://github.com/getpaseo/paseo/pull/10614))
|
||||
- Fixed OpenCode Go usage for logins stored in the OpenCode 2 database, including Console sign-ins and API keys ([#8729](https://github.com/getpaseo/paseo/pull/8729), [#10612](https://github.com/getpaseo/paseo/pull/10612))
|
||||
- Fixed existing OpenCode sessions failing to reopen after Paseo tool definitions change ([#10533](https://github.com/getpaseo/paseo/pull/10533) by [@Peanut-HZM](https://github.com/Peanut-HZM))
|
||||
- Fixed Paseo tools missing from agents that use MCP protocol version `2026-07-28` ([#10558](https://github.com/getpaseo/paseo/pull/10558) by [@apple-ouyang](https://github.com/apple-ouyang))
|
||||
- Fixed Codex MCP startup failures missing from daemon warning logs ([#10566](https://github.com/getpaseo/paseo/pull/10566))
|
||||
- Fixed the daemon exiting when it closes a session after the plugin process has stopped ([#10585](https://github.com/getpaseo/paseo/pull/10585))
|
||||
- Fixed Git commands selecting the wrong repository when a directory has the layout of a bare repository ([#10587](https://github.com/getpaseo/paseo/pull/10587))
|
||||
- Fixed Claude Auto permission mode being unavailable on Bedrock and Vertex ([#6904](https://github.com/getpaseo/paseo/pull/6904))
|
||||
- Fixed the sidebar host settings button requiring two clicks to open settings ([#10562](https://github.com/getpaseo/paseo/pull/10562) by [@ShalokShalom](https://github.com/ShalokShalom))
|
||||
- Fixed the Changes pane not offering Push for a new branch that was never pushed in a regular checkout ([#10631](https://github.com/getpaseo/paseo/pull/10631))
|
||||
- Fixed the daemon using the wrong model catalog when Hub sends a workspace directory for trigger validation ([#10582](https://github.com/getpaseo/paseo/pull/10582))
|
||||
|
||||
## 0.17.3 - 2026-11-22
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -1,5 +1,25 @@
|
||||
# Changelog
|
||||
|
||||
## 0.17.4 - 2026-11-23
|
||||
|
||||
### 修复
|
||||
|
||||
- 修复 Android 上嵌套编号列表的编号与正文重叠,以及列表中的引用与后续消息重叠的问题 ([#10499](https://github.com/getpaseo/paseo/pull/10499))
|
||||
- 修复 Android 终端输入,要求键盘不将输入内容用于个性化学习 ([#10586](https://github.com/getpaseo/paseo/pull/10586))
|
||||
- 修复在不区分大小写的文件系统上,目录路径大小写不一致导致对话消失的问题 ([#10555](https://github.com/getpaseo/paseo/pull/10555),贡献者:[@yzim](https://github.com/yzim))
|
||||
- 修复发给已归档 Agent 的中断和引导消息进入队列后未启动新轮次的问题 ([#10611](https://github.com/getpaseo/paseo/pull/10611),贡献者:[@thomasvan](https://github.com/thomasvan))
|
||||
- 修复 Hermes 的 Shell 工具行只显示命令摘要的问题,现在会显示完整命令 ([#10614](https://github.com/getpaseo/paseo/pull/10614))
|
||||
- 修复使用 OpenCode 2 数据库中保存的登录凭据时的 Go 用量显示,涵盖 Console 登录和 API 密钥 ([#8729](https://github.com/getpaseo/paseo/pull/8729), [#10612](https://github.com/getpaseo/paseo/pull/10612))
|
||||
- 修复 Paseo 工具定义变更后无法重新打开已有 OpenCode 会话的问题 ([#10533](https://github.com/getpaseo/paseo/pull/10533),贡献者:[@Peanut-HZM](https://github.com/Peanut-HZM))
|
||||
- 修复使用 MCP 协议版本 `2026-07-28` 的 Agent 缺少 Paseo 工具的问题 ([#10558](https://github.com/getpaseo/paseo/pull/10558),贡献者:[@apple-ouyang](https://github.com/apple-ouyang))
|
||||
- 修复 Codex MCP 启动失败时 daemon 未记录警告的问题 ([#10566](https://github.com/getpaseo/paseo/pull/10566))
|
||||
- 修复插件进程停止后 daemon 在关闭会话时退出的问题 ([#10585](https://github.com/getpaseo/paseo/pull/10585))
|
||||
- 修复目录结构与裸仓库相同时 Git 命令选错仓库的问题 ([#10587](https://github.com/getpaseo/paseo/pull/10587))
|
||||
- 修复在 Bedrock 和 Vertex 上无法选择 Claude Auto 权限模式的问题 ([#6904](https://github.com/getpaseo/paseo/pull/6904))
|
||||
- 修复侧边栏的主机设置按钮需要点击两次才能打开设置的问题 ([#10562](https://github.com/getpaseo/paseo/pull/10562),贡献者:[@ShalokShalom](https://github.com/ShalokShalom))
|
||||
- 修复普通检出中从未推送过的新分支在“变更”面板中不显示“推送”的问题 ([#10631](https://github.com/getpaseo/paseo/pull/10631))
|
||||
- 修复 Hub 在验证触发器时传入工作区目录后,daemon 使用错误模型目录的问题 ([#10582](https://github.com/getpaseo/paseo/pull/10582))
|
||||
|
||||
## 0.17.3 - 2026-11-22
|
||||
|
||||
### 修复
|
||||
|
||||
@@ -54,9 +54,10 @@ At the start of non-trivial work, list `docs/` and skim anything relevant to the
|
||||
| [docs/permissions.md](docs/permissions.md) | Semantic daemon permissions, principals, credentials, pairing invitations, and Hub authority |
|
||||
| [docs/terminal-performance.md](docs/terminal-performance.md) | Terminal latency pipeline, coalescing/backpressure invariants, benchmark + perf spec usage |
|
||||
| [docs/terminal-rendering.md](docs/terminal-rendering.md) | Native terminal view: xterm owns the grid, cluster placement, emoji widths, mixed-direction limits, render regression |
|
||||
| [docs/timeline-sync.md](docs/timeline-sync.md) | Owned agent history, rewind retirements, live stream vs authoritative fetch, paged catch-up, client replica |
|
||||
| [docs/agent-stream-performance.md](docs/agent-stream-performance.md) | Assistant text pipeline — coalescing window, paced reveal, why arrival lumps are smoothed at render |
|
||||
| [docs/agent-stream-disclosure.md](docs/agent-stream-disclosure.md) | Expand/collapse in the chat timeline — hold contract, native anchor sequence, frame spacing, render-window cost |
|
||||
| [docs/markdown-renderer.md](docs/markdown-renderer.md) | Shared Markdown engine, native selection, links, images and library constraints |
|
||||
| [docs/markdown-renderer.md](docs/markdown-renderer.md) | Shared Markdown engine, the vendored library fork, native selection, links, images and library constraints |
|
||||
| [docs/native-text-selection.md](docs/native-text-selection.md) | Native diagram grouping, selection boundaries and leading inline image limitations |
|
||||
| [docs/file-observation.md](docs/file-observation.md) | Recursive watcher ownership, Linux constraints, teardown invariants, and Parcel comparison |
|
||||
| [docs/testing.md](docs/testing.md) | TDD workflow, determinism, real dependencies over mocks, test organization |
|
||||
|
||||
@@ -39,8 +39,8 @@ An unarchived agent may be `closed` without being deleted or archived. Closing r
|
||||
processes and subscriptions while retaining its Paseo identity, persistence handle, timeline,
|
||||
workspace, labels, title, usage, attention, timestamps, and parent relationship. Opening or prompting
|
||||
the agent runs through `ensureAgentLoaded()`, which resumes the durable provider session under the
|
||||
same Paseo agent ID. Provider history is not appended again when the canonical timeline is already
|
||||
primed.
|
||||
same Paseo agent ID. Resume does not read provider history when the agent already has a timeline;
|
||||
see [owned history](timeline-sync.md#owned-history).
|
||||
|
||||
Reload releases the old runtime before resuming its durable session: an idle provider process can
|
||||
still own an exclusive writer. A close failure retains that runtime for cleanup and blocks the
|
||||
@@ -256,7 +256,8 @@ lifecycle is separate from public workspace visibility and is not a public creat
|
||||
Archive is a **soft delete**: the agent record stays on disk with `archivedAt` set, the runtime is closed, and the agent disappears from active lists. Archive is **global** — it lives on the server and propagates to every connected client.
|
||||
|
||||
Archive sets `archivedAt`, invokes the provider's native archive hook, and cascades to managed
|
||||
children.
|
||||
children. The timeline and the provider children stay, so an archived chat reads them without its
|
||||
provider; deleting the agent removes them.
|
||||
|
||||
`create_agent_request` can opt an agent into `autoArchive`. In that mode the daemon archives the agent after the first terminal turn event (`turn_completed`, `turn_failed`, or `turn_canceled`). When the agent owns an isolated workspace, auto-archive archives that workspace too; the managed worktree is removed when its final workspace reference is gone.
|
||||
|
||||
@@ -352,6 +353,8 @@ Workspace status is an aggregate activity signal computed **per `workspaceId`**.
|
||||
|
||||
Running provider-native subagents contribute `running` to the workspace owned by their parent agent. Their completed, failed, and canceled states stay in the parent's subagents track.
|
||||
|
||||
Only the parent's current runtime makes a provider child running. A child's stored status is the last report about it, and that report can come from provider history or from a runtime an earlier daemon ran, so a stored `running` child does not make the workspace running or keep the parent's runtime alive. It counts again once the live session reports it running. Closing a runtime cancels the children that runtime reported running; children it never reported keep their stored status.
|
||||
|
||||
A finished or failed workspace can be marked unread after it has been reviewed. The daemon restores
|
||||
attention on its newest eligible workspace-root agent, `error` for an agent whose lifecycle is
|
||||
`error` and `finished` otherwise, without sending a new notification. Opening a workspace restores
|
||||
|
||||
@@ -121,6 +121,12 @@ from `packages/app/android`:
|
||||
|
||||
These check terminal arrow ownership, held-key repeats and modifiers, and ordinary text-field editing.
|
||||
|
||||
Run the terminal module's tests the same way with `:paseo-terminal:connectedDebugAndroidTest`. Besides
|
||||
row layout, they check that the terminal input asks the keyboard not to learn what is typed
|
||||
(`IME_FLAG_NO_PERSONALIZED_LEARNING`), so passwords typed at a prompt stay out of Gboard's
|
||||
suggestions in other apps. React Native's TextInput has no prop for that flag, and it replaces
|
||||
`imeOptions` when `returnKeyType` or `disableFullscreenUI` is set, so the terminal input sets neither.
|
||||
|
||||
Run the display density regression tests the same way:
|
||||
|
||||
```bash
|
||||
|
||||
@@ -94,6 +94,7 @@ workspace for a directory clears it. The store lives in memory and resets on dae
|
||||
| `server/directory-sync/` | Daemon-global latest-state sequences for projects, workspaces, and agents |
|
||||
| `server/workspace-labels/` | Host-local label catalog, assignment mutations, and explicit subscriptions |
|
||||
| `server/agent/agent-manager.ts` | Agent lifecycle state machine, timeline tracking, subscriber management |
|
||||
| `server/agent/timeline/` | Owned agent history, provider children, rewind retirements, behind a backend |
|
||||
| `server/agent/agent-storage.ts` | File-backed JSON persistence at `$PASEO_HOME/agents/` |
|
||||
| `server/agent/tools/` | Transport-neutral catalog for workspaces, agents, permissions, and automation |
|
||||
| `server/agent/mcp-server.ts` | Thin MCP adapter that registers the Paseo tool catalog with the MCP SDK |
|
||||
@@ -402,7 +403,7 @@ initializing → idle ⇄ running
|
||||
client-side dedup; the default fetch page is 200 items.
|
||||
- Timeline row `timestamp` values are canonical daemon-owned timestamps. Providers may supply original replay timestamps, but clients must not guess timestamp trust or hide time UI based on local clock heuristics.
|
||||
- Events stream to connected clients in real time; correctness is backed by authoritative timeline fetches and paged-to-completion catch-up.
|
||||
- Agent state persists to `$PASEO_HOME/agents/{cwd-with-dashes}/{agent-id}.json`. Timeline rows are runtime memory; provider history is the durable transcript authority and resumed agents rebuild from it. That storage path is derived from `cwd`, not from workspace id.
|
||||
- Agent state persists to `$PASEO_HOME/agents/{cwd-with-dashes}/{agent-id}.json`. That storage path is derived from `cwd`, not from workspace id. Timeline rows persist in the daemon database, `$PASEO_HOME/paseo.db`. They are the transcript authority after the first import of provider history. See [owned history](timeline-sync.md#owned-history).
|
||||
|
||||
## Right-sidebar boundary: directory-backed vs workspace-owned
|
||||
|
||||
@@ -478,6 +479,7 @@ Providers that can accept native tool definitions should set `supportsNativePase
|
||||
```
|
||||
$PASEO_HOME/
|
||||
├── agents/{cwd-with-dashes}/{agent-id}.json # Agent record
|
||||
├── paseo.db # Daemon database (SQLite): agent timelines
|
||||
├── projects/projects.json # Project registry
|
||||
├── projects/workspaces.json # Workspace registry
|
||||
├── projects/icons/ # Custom project icon images
|
||||
|
||||
@@ -514,7 +514,7 @@ The [Agent Client Protocol (ACP)](https://agentclientprotocol.com) is an open st
|
||||
|
||||
ACP agents communicate over JSON-RPC 2.0 on stdio. Paseo spawns the agent process and talks to it through stdin/stdout.
|
||||
|
||||
Paseo also ships an in-app ACP provider catalog for common agents, including CodeWhale, Cursor, DeepAgents, DimCode, Gemini CLI, Hermes, Qwen Code, and Kimi Code. Most catalog entries create the same `extends: "acp"` provider config shown below. Hoplite activates its [bundled provider](plugins.md#built-in-plugins) instead.
|
||||
Paseo also ships an in-app ACP provider catalog for common agents, including CodeWhale, Cursor, DeepAgents, DimCode, Gemini CLI, Hermes, Qwen Code, and Kimi Code. Most catalog entries create the same `extends: "acp"` provider config shown below. Goose, Hermes, and Hoplite activate their [bundled providers](plugins.md#built-in-plugins) instead. An existing `extends: "acp"` entry for goose or Hermes migrates to the bundled provider on load and keeps a custom command. Hermes agents saved with the old adapter resume with their mode translated (`plugins/hermes-provider/server/legacy-modes.ts`).
|
||||
|
||||
### Adding a generic ACP provider
|
||||
|
||||
@@ -627,32 +627,6 @@ ACP probes use short timeouts and browser-suppression environment variables so a
|
||||
|
||||
Ref: [Gemini CLI ACP mode docs](https://github.com/google-gemini/gemini-cli/blob/main/docs/cli/acp-mode.md)
|
||||
|
||||
### Example: Hermes (Nous Research)
|
||||
|
||||
[Hermes](https://github.com/NousResearch/hermes-agent) is an open-source coding agent by Nous Research with persistent memory and multi-provider LLM support. It supports ACP via the `acp` subcommand.
|
||||
|
||||
1. Install: `curl -fsSL https://raw.githubusercontent.com/NousResearch/hermes-agent/main/scripts/install.sh | bash`
|
||||
2. Install ACP support: `pip install -e '.[acp]'`
|
||||
3. Configure Hermes credentials in `~/.hermes/`
|
||||
4. Add to config.json:
|
||||
|
||||
```json
|
||||
{
|
||||
"agents": {
|
||||
"providers": {
|
||||
"hermes": {
|
||||
"extends": "acp",
|
||||
"label": "Hermes",
|
||||
"description": "Nous Research self-improving AI agent",
|
||||
"command": ["hermes", "acp"]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Ref: [Hermes ACP docs](https://hermes-agent.nousresearch.com/docs/user-guide/features/acp)
|
||||
|
||||
### How ACP providers work in Paseo
|
||||
|
||||
When you launch an agent with an ACP provider:
|
||||
@@ -853,12 +827,6 @@ A config.json with multiple custom providers:
|
||||
"extends": "acp",
|
||||
"label": "Google Gemini",
|
||||
"command": ["gemini", "--acp"]
|
||||
},
|
||||
|
||||
"hermes": {
|
||||
"extends": "acp",
|
||||
"label": "Hermes",
|
||||
"command": ["hermes", "acp"]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+41
-1
@@ -34,7 +34,7 @@ Workspace archive runs lifecycle teardown from the exact `cwd` but removes only
|
||||
`worktreeRoot` after its last active reference disappears. Worktree recovery recreates that backing
|
||||
checkout from `mainRepoRoot`, then restores the relative path from `worktreeRoot` to `cwd`.
|
||||
|
||||
Paseo uses **file-based JSON persistence** instead of a traditional database. All data is validated at runtime with Zod schemas. Most stores write atomically (write to temp file, then rename); a few still use plain `writeFile` — see each section. There is no schema-versioning/migration framework — schemas rely on optional fields with defaults for forward compatibility, with a small amount of inline normalization in `persisted-config.ts` for legacy provider/speech entries.
|
||||
Paseo persists most stores as JSON files, and agent timelines in the [daemon database](#daemon-database). JSON data is validated at runtime with Zod schemas. Most JSON stores write atomically (write to temp file, then rename); a few still use plain `writeFile` — see each section. JSON stores have no schema-versioning/migration framework — schemas rely on optional fields with defaults for forward compatibility, with a small amount of inline normalization in `persisted-config.ts` for legacy provider/speech entries.
|
||||
|
||||
All server-side stores live under `$PASEO_HOME` (defaults to `~/.paseo`).
|
||||
|
||||
@@ -53,6 +53,7 @@ $PASEO_HOME/
|
||||
├── daemon-keypair.json # E2EE keypair for relay (mode 0600)
|
||||
├── paseo.pid # Daemon PID lock file
|
||||
├── local-credential # Per-run local client credential (mode 0600)
|
||||
├── paseo.db # Daemon database (SQLite, with -wal and -shm files)
|
||||
├── daemon.log # Default log file (path configurable)
|
||||
├── agents/
|
||||
│ └── {sanitized-cwd}/
|
||||
@@ -181,6 +182,45 @@ Terminal activity contributes to the workspace status bucket **per `workspaceId`
|
||||
|
||||
---
|
||||
|
||||
## Daemon database
|
||||
|
||||
`$PASEO_HOME/paseo.db` is one SQLite file that the daemon opens at startup with `node:sqlite`
|
||||
(`packages/server/src/server/database/`). Agent timelines are its only store today. Each store is a
|
||||
`SchemaModule`: its own table-name prefix and an append-only list of migrations.
|
||||
|
||||
- **Migrations.** Startup runs every module's pending migrations in one transaction, so a failed
|
||||
migration leaves the file as it was. `schema_versions` records each module's version and
|
||||
`min_reader_version`. Mark a migration `breaking` when an older daemon cannot read the result,
|
||||
for example a dropped or renamed column. An older daemon then refuses to start with
|
||||
`DatabaseSchemaTooNewError`. Additive migrations leave older daemons working, and they ignore
|
||||
modules they do not know. This matters because the app and the daemon update separately, and a
|
||||
user can run an older daemon on the same `$PASEO_HOME`.
|
||||
- **Failure.** A file that SQLite cannot open stops the daemon with `DatabaseOpenError`, which
|
||||
names the path. The daemon does not delete or recreate the file.
|
||||
- **Access.** The file holds every prompt and reply, so the daemon sets it and its `-wal` and `-shm`
|
||||
files to mode `0600` on every open. SQLite gives the WAL files it creates the mode of the database
|
||||
file.
|
||||
- **Durability.** The database uses WAL with `synchronous = NORMAL`. A power loss can drop the
|
||||
last commits but does not corrupt the file.
|
||||
- **Checkpoints.** A checkpoint syncs the file to disk and takes up to 100 ms. SQLite's
|
||||
auto-checkpoint runs it on the committing thread, which stalled the event loop during streaming.
|
||||
The daemon turns it off and checkpoints from a worker thread with its own connection. If the
|
||||
worker exits, the daemon turns auto-checkpoint back on.
|
||||
- **Transactions.** `write` and `read` callbacks are synchronous, so a transaction never spans an
|
||||
`await` and transactions never interleave.
|
||||
- **Node.** `node:sqlite` needs Node 22.16 or later. Node 22 prints an experimental warning once,
|
||||
when the daemon opens the database.
|
||||
|
||||
### Agent timelines
|
||||
|
||||
`AgentTimeline` owns each agent's history, and its SQLite backend stores the projected rows, the
|
||||
source ranges, retirements, the open rewind, and provider children in `timeline_*` tables. The text
|
||||
of a streamed assistant or reasoning message is stored as one chunk per source event, beside its
|
||||
row, so a chunk never rewrites the message. An earlier file store rewrote the whole transcript on
|
||||
every update. See [owned history](timeline-sync.md#owned-history).
|
||||
|
||||
---
|
||||
|
||||
## 2. Daemon Configuration
|
||||
|
||||
**Path:** `$PASEO_HOME/config.json`
|
||||
|
||||
@@ -14,19 +14,38 @@ Workspace file links use the shared file-link resolver. The workspace supplies i
|
||||
|
||||
Pass `external` for author-controlled Markdown from outside the host, such as a plugin README. It follows the registry's overview contract in `packages/protocol/src/plugin-overview.ts`, which the website also uses: only absolute https links and images work, and any other destination renders as its label or alt text. The parser still autolinks bare `http://`, `www.` and email text, so a link press checks the URL again and opens only https. None of the workspace recognition above applies, so `Node.js` is prose, not a file. The lines of a paragraph join, as they do on the README's forge.
|
||||
|
||||
Resolve workspace image paths over the existing session RPC, then give the library a cached native file URL or web blob URL. HTTP(S) images pass through unchanged. This preserves relay, SSH and local socket connections, which do not expose a daemon HTTP endpoint. Each mounted renderer owns its image acquisition identity, so a later reply reads a rewritten path again while the earlier mounted reply retains its snapshot. Image taps open the attachment lightbox. File previews resolve relative images against the Markdown file's directory. An image alone on its line becomes its own paragraph before the library sees it, so it renders as a block on every platform; the library only treats sole-child paragraph images as blocks, and with hard soft breaks every newline is a break node, which left own-line images inline on iOS and web. Images that share a line with text stay inline at line height and keep their aspect ratio. A linked image counts as an image, so review-bot badges such as `[](url) Confidence` stay inline on web; the library's web renderer only checked direct paragraph children, so it rendered them as full-width block images (local patch in `patches/react-native-enriched-markdown+*.patch`).
|
||||
Resolve workspace image paths over the existing session RPC, then give the library a cached native file URL or web blob URL. HTTP(S) images pass through unchanged. This preserves relay, SSH and local socket connections, which do not expose a daemon HTTP endpoint. Each mounted renderer owns its image acquisition identity, so a later reply reads a rewritten path again while the earlier mounted reply retains its snapshot. Image taps open the attachment lightbox. File previews resolve relative images against the Markdown file's directory. An image alone on its line becomes its own paragraph before the library sees it, so it renders as a block on every platform; the library only treats sole-child paragraph images as blocks, and with hard soft breaks every newline is a break node, which left own-line images inline on iOS and web. Images that share a line with text stay inline at line height and keep their aspect ratio. A linked image counts as an image, so review-bot badges such as `[](url) Confidence` stay inline on web; the library's web renderer only checked direct paragraph children, so it rendered them as full-width block images (fixed in the fork).
|
||||
|
||||
## The fork
|
||||
|
||||
The library is a private workspace, `packages/react-native-enriched-markdown`. It is upstream [enriched-markdown](https://github.com/software-mansion/enriched-markdown) at npm `1.2.0-nightly-20261014-766fc0e67` (upstream commit `766fc0e67`) plus Paseo's changes, which lived in a `patch-package` patch until the package moved into the repository. It is never published. Keep the name `react-native-enriched-markdown`: autolinking, the Gradle project `:react-native-enriched-markdown`, the CocoaPods spec and app imports all use it.
|
||||
|
||||
The package keeps the npm tarball's layout, including its build output:
|
||||
|
||||
- Metro, Vitest and TypeScript load `lib/`, not `src/`. A JavaScript change edits `src/` and the matching `lib/module` and `lib/typescript` files.
|
||||
- `android/generated` and `ios/generated` are checked-in codegen output (`includesGeneratedCode`). A change to a native component spec regenerates both; `scripts/postinstall-patches.test.mjs` compares them against the specs.
|
||||
- `src/web/wasm/md4c.js` and `lib/module/web/wasm/md4c.js` are an Emscripten build of `cpp/md4c`. A parser change rebuilds them with upstream's `packages/core/cpp/wasm/build.sh`.
|
||||
- Upstream's Gradle, CMake and CocoaPods scripts detect upstream's own monorepo by the paths `packages/core` and a root `vendor/`. Do not add either path to this repository.
|
||||
- `postinstall.mjs` downloads the tree-sitter grammars into the ignored `cpp/highlight/vendor/grammars` and `vendor/tree-sitter`. The `enriched-markdown` block in `packages/app/package.json` chooses the languages.
|
||||
|
||||
CI does not build native code or run the fork's Robolectric suites. Run `npm run test:android --workspace=@getpaseo/app` for Android changes. Native changes require a client rebuild; JavaScript refresh cannot enable compiled grammars.
|
||||
|
||||
Some fork changes are backports. A sync past the upstream version drops them in favour of upstream's code:
|
||||
|
||||
| Fork change | Upstream | Released in |
|
||||
| ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------- |
|
||||
| Android measurements survive parent clones | [#924](https://github.com/software-mansion/enriched-markdown/pull/924) | after `1.2.0-nightly-20261019-926ef06f0` |
|
||||
| Android nested list items start their text after their own marker | [#1015](https://github.com/software-mansion/enriched-markdown/pull/1015), [#1023](https://github.com/software-mansion/enriched-markdown/pull/1023) (Android) | `1.2.0` |
|
||||
|
||||
## Engine constraints
|
||||
|
||||
The pinned nightly has the same React Native package and core source trees as upstream commit `73ac5085eb1fdc743973b3473d4dba65abad5261`. Compatibility was checked with React Native 0.81.5. Native dependencies must be rebuilt when changing the highlighting configuration; JavaScript refresh cannot enable compiled grammars.
|
||||
|
||||
Math and video are disabled. Task lists and admonitions are enabled; task checkboxes are read-only. Source adaptation spaces adjacent empty GFM table delimiters before escaping prose spoiler delimiters and decodes entity text before the engine can discard it. Code spans and fences keep their literal source. Comment HTML is normalized to Markdown before parsing; details show their summary and body expanded.
|
||||
|
||||
Mermaid fences use the existing isolated diagram runtime and fullscreen viewer. Web dispatches them through the library’s code-block override. Native has no block-renderer hook, so the renderer extracts only Mermaid fences and places the existing WebView host between library-rendered segments. This is the only block exception; see [native selection limitations](native-text-selection.md) for diagram grouping and leading inline images. Streaming keeps the last valid diagram visible while the next revision renders.
|
||||
|
||||
Native code blocks use the library's copy control and compiled grammars. Web code blocks use `HighlightedCodeBlock` through the library's `renderers.codeBlock` override. Selection copy has to tell links Paseo recognized in the text (paths, forge references, code spans) from links in the Markdown, so the web link renderer marks the recognized ones. Plain-text paste carries them as the text the reply showed, and rich paste keeps them as links only when they point to an `http` or `https` URL. Authored links and parser autolinks such as a bare `www.example.com` copy as links. The patch also keeps the library's block spacing around the web code block override, preserves web list numbering and link titles, marks pending parses with `aria-busy` so Find waits for rendered text, and carries link syntax through native and web tap events. Web inline code inside a link inherits only the link colour; its code font, size and background stay intact. Keep link variants colour-only: native pills replace text runs and prevent paths from wrapping; Android pills also use the surrounding block’s font size. The package patch is tracked by [upstream PR #997](https://github.com/software-mansion/enriched-markdown/pull/997); remove the patch when the pinned release includes it.
|
||||
Native code blocks use the library's copy control and compiled grammars. Web code blocks use `HighlightedCodeBlock` through the library's `renderers.codeBlock` override. Selection copy has to tell links Paseo recognized in the text (paths, forge references, code spans) from links in the Markdown, so the web link renderer marks the recognized ones. Plain-text paste carries them as the text the reply showed, and rich paste keeps them as links only when they point to an `http` or `https` URL. Authored links and parser autolinks such as a bare `www.example.com` copy as links. The fork also keeps the library's block spacing around the web code block override, preserves web list numbering and link titles, marks pending parses with `aria-busy` so Find waits for rendered text, and carries link syntax through native and web tap events. Web inline code inside a link inherits only the link colour; its code font, size and background stay intact. Keep link variants colour-only: native pills replace text runs and prevent paths from wrapping; Android pills also use the surrounding block’s font size. [Upstream PR #997](https://github.com/software-mansion/enriched-markdown/pull/997) tracks these changes.
|
||||
|
||||
The package patch also keeps overflowing native horizontal blocks in control of their drags: Android claims parent interception at touch-down and releases it for vertical drags so the chat list can scroll; iOS keeps its scroll recognizer active for outward drags at the leading edge. This prevents compact sidebar pans from taking block scrolling without changing sidebar swipes on prose or non-overflowing blocks. Native changes require a client rebuild.
|
||||
The fork also keeps overflowing native horizontal blocks in control of their drags: Android claims parent interception at touch-down and releases it for vertical drags so the chat list can scroll; iOS keeps its scroll recognizer active for outward drags at the leading edge. This prevents compact sidebar pans from taking block scrolling without changing sidebar swipes on prose or non-overflowing blocks. Native changes require a client rebuild.
|
||||
|
||||
On iOS a newly mounted Markdown view paints empty for a frame or more after it is laid out at its measured height: the library parses even a view's first content on a background queue and applies it in a later main-queue turn. Expanding a turn in chat therefore shows its rows in place with the text arriving a frame later (165 ms when the mount keeps the main thread busy). Android paints the text in the first frame. Rendering a view's first content synchronously fixes the frame but costs frame time when a fling mounts history rows, so the app keeps the library's behavior until [enriched-markdown #1131](https://github.com/software-mansion/enriched-markdown/issues/1131) is resolved.
|
||||
|
||||
|
||||
+7
-3
@@ -118,7 +118,7 @@ appear in the plugin catalog. Editing one in development requires a daemon resta
|
||||
Directory, Git, and npm installs cannot use a built-in ID.
|
||||
|
||||
A provider registration with `requiresConfiguration: true` participates only while its ID exists
|
||||
under `agents.providers`. Hoplite and fx use this for catalog opt-in. Add writes `{ "enabled": true }`
|
||||
under `agents.providers`. Hoplite, fx, goose, and Hermes use this for catalog opt-in. Add writes `{ "enabled": true }`
|
||||
without `extends`, so it selects the bundled adapter. Remove deletes the config entry; setting
|
||||
`enabled: false` keeps the entry. The bundled JavaScript still loads at startup, but an absent
|
||||
provider does not enter executable resolution or catalog discovery.
|
||||
@@ -583,8 +583,12 @@ daemon launch from `connect` and the per-session env and MCP servers from `sessi
|
||||
no provider reload input.
|
||||
|
||||
For an ACP command, register `runAcpProvider({ id, label, command })` from
|
||||
`@getpaseo/plugin/server/acp`. Its transformer hooks cover narrow vendor differences; do not translate the
|
||||
whole provider event stream. The shim uses the resolved launch for every probe and session, overlaying
|
||||
`@getpaseo/plugin/server/acp`. The shim builds the standard row for each ACP tool `kind`
|
||||
(`acp-internal/tool-call-detail.ts`). Its transformer hooks cover narrow vendor differences; do not translate the
|
||||
whole provider event stream. A `toolCall` transformer sees the raw `input`, `output` and `content`, and a
|
||||
`detail` it sets replaces the standard row. Parse vendor display text defensively and return the call
|
||||
unchanged when the shape does not match, so an upstream format change falls back to the standard row
|
||||
(`plugins/hermes-provider/server/terminal-command.ts`). The shim uses the resolved launch for every probe and session, overlaying
|
||||
only the supplied per-session env for sessions. The direct and ACP examples live in
|
||||
`plugin-examples/provider-direct`
|
||||
and `plugin-examples/provider-acp-transformer`.
|
||||
|
||||
+68
-11
@@ -5,15 +5,9 @@ Agent chat delivery has two paths:
|
||||
1. **Live stream** — `agent_stream` WebSocket messages for immediacy. These may be delta-shaped lifecycle updates.
|
||||
2. **Authoritative history** — `fetch_agent_timeline_request` for correctness. This always returns full projected timeline items, never lifecycle deltas.
|
||||
|
||||
The daemon retains projected items in memory. Each source event advances the stream sequence,
|
||||
then replaces the previous tool state or merges into the current text item. Intermediate payloads
|
||||
are never retained for history or catch-up. Provider history is the durable transcript authority
|
||||
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.
|
||||
Pagination bounds each read, not total resident history. Streaming overhead must remain
|
||||
proportional to the retained transcript. Cumulative text snapshots must be released after their
|
||||
deltas have been consumed.
|
||||
|
||||
The invariants are:
|
||||
|
||||
@@ -32,6 +26,50 @@ bounded item is used for runtime timeline rows and live stream events. Provider
|
||||
applies the same rule so reopening an agent cannot restore an oversized payload. Fetches apply it
|
||||
again to assistant and reasoning rows the projection merges from many chunks.
|
||||
|
||||
## Owned history
|
||||
|
||||
The daemon owns each agent's history in `AgentTimeline`
|
||||
(`packages/server/src/server/agent/timeline/`): one ordered history per agent, with each provider
|
||||
child's descriptor and history in a child scope of the same agent. Each source event advances the
|
||||
stream sequence, then replaces the previous tool state or merges into the current text item.
|
||||
Intermediate payloads are never retained for history or catch-up.
|
||||
|
||||
History is append-only: rewind, import, reload and archive never delete or rewrite a row. Only
|
||||
deleting the agent, or a provider removing one of its own children, deletes history.
|
||||
|
||||
- **Rewind** retires a range of rows. They leave the conversation and stay stored, in the same
|
||||
epoch. See [Rewind retires rows](#rewind-retires-rows).
|
||||
- **Provider history** is imported only into an agent that has no history. After that, resume
|
||||
does not read it. Reload agent and Unarchive require the provider history to start with the
|
||||
same prompt IDs and text in order. They then append whole new turns, starting at the next
|
||||
prompt. Existing replies, including partial replies, stay as recorded. If the prompts differ,
|
||||
for example because the provider stored expanded attachment text, the chat stays unchanged and
|
||||
Paseo reports a mismatch. A provider child Paseo already holds, listed or retired, is never imported again.
|
||||
- **Archive and reload** keep the history and the provider children. An archived chat reads them
|
||||
without its provider. Opening a stored agent that has no provider session to resume starts its
|
||||
first session on the same history.
|
||||
- **Delete** removes the agent's history and every child's, retired ones included, before the
|
||||
agent record. If the history cannot be removed, the request fails and the agent stays listed. The
|
||||
user can keep using it and delete it again.
|
||||
|
||||
`epoch` is the stored history's identity, minted once when the history is created.
|
||||
|
||||
`AgentTimeline` serializes every operation of one agent, child scopes included, and keeps its
|
||||
state in an `AgentTimelineBackend`: the sequence, the rows and retirements, prompt identities, the
|
||||
open rewind, and the children. The backend contract suite is `agent-timeline.test.ts`, run over
|
||||
`TIMELINE_CONTRACT_BACKENDS` in `timeline/testing.ts`. The daemon uses the SQLite backend in the
|
||||
[daemon database](data-model.md#daemon-database). History, retirements, the open rewind, and
|
||||
provider children survive a daemon restart in the same epoch, so clients keep their cursors. A
|
||||
closed or archived agent holds no history in memory. Each fetch reads the page from the database
|
||||
and starts no provider. An internal agent, such as the one that writes a commit message, keeps its
|
||||
history in a memory backend instead, so it leaves nothing on disk. The memory backend also serves
|
||||
tests.
|
||||
|
||||
An open rewind is stored with the history. Resuming an agent whose history holds one settles it
|
||||
before the agent takes prompts: a recorded provider cut is committed, and an unknown outcome is
|
||||
judged from the resumed provider history. When that history proves nothing, the rewind stays open
|
||||
and the agent refuses prompts with the unknown-outcome error.
|
||||
|
||||
## Presence is not delivery
|
||||
|
||||
Client heartbeat reports presence:
|
||||
@@ -168,7 +206,7 @@ or retry backoff. This cannot keep a mobile socket alive after the operating sys
|
||||
bookkeeping without replacing timeline arrays, preserving an upward-scrolled viewport.
|
||||
- When the page overlaps or is adjacent to the local end cursor, only projected items newer than
|
||||
that cursor are applied. Already-covered rows are not replayed.
|
||||
- A true middle gap, epoch change, or rewind atomically replaces stale canonical history with the
|
||||
- A true middle gap or epoch change atomically replaces stale canonical history with the
|
||||
latest tail. The replacement reconciles positioned live rows beyond its coverage and unresolved
|
||||
local submissions; it never retains two discontiguous canonical ranges.
|
||||
|
||||
@@ -181,6 +219,24 @@ history replay. The pending approval UI can hide that tool from presentation, bu
|
||||
must retain its position. Creating a new history card on rejection places it after the prompt that
|
||||
rejected it; changing steer-event ordering would also put new assistant output before that prompt.
|
||||
|
||||
## Rewind retires rows
|
||||
|
||||
A conversation rewind commits a retirement `{ seq, retireFromSeq }`: active rows anchored in
|
||||
`[retireFromSeq, seq)` leave the conversation, and `seq` is the retirement's own position in the
|
||||
sequence. The provider children spawned by retired tool calls, and their descendants, are retired
|
||||
in the same commit. They leave the listing, keep their history, and drop late provider events.
|
||||
|
||||
Clients learn of a retirement live through `agent.timeline.rewind`, and on pages through
|
||||
`retirements`, which lists the retirements whose `seq` lies inside the page's span. The client
|
||||
drops the rows it holds in that range; rows without a timeline position are unechoed local sends
|
||||
and stay. Retired ranges and the retirement's `seq` count as covered, so forward cursors advance
|
||||
through them. Tail, before and prompt-jump pages are served from active rows, so one served before
|
||||
a retirement the client already applied is stale and is refetched (`viewed-timeline-sync.ts`).
|
||||
|
||||
Clients without `timeline_rewind_operations` cannot drop retired rows. For them the session derives
|
||||
a wire epoch that changes with each retirement, so they take the destructive replacement they
|
||||
always took on rewind. The shim is tagged `COMPAT(timelineRewindOperations)`.
|
||||
|
||||
## Provider child history
|
||||
|
||||
Child transcripts use the same projected-page reconciliation as the main conversation. The client
|
||||
@@ -345,7 +401,7 @@ the draft-create handoff is the one boundary that also permits the legacy canoni
|
||||
arrived first. Generic reducers and consumers do not reimplement message identity matching.
|
||||
|
||||
Ordinary bootstrap, same-epoch reset, and catch-up replacement preserve unmatched locally submitted
|
||||
rows because a provider may never echo them. A known epoch change or rewind replaces history and
|
||||
rows because a provider may never echo them. A known epoch change replaces history and
|
||||
drops acknowledged local rows omitted by the new canonical epoch; every transaction not yet
|
||||
acknowledged by the provider, and no other local row, crosses that destructive boundary. A cold
|
||||
reset without an existing epoch is destructive because the client has no continuity anchor.
|
||||
@@ -361,6 +417,7 @@ canonical assistant prefix, it stays in the head lane. No row may be returned in
|
||||
|
||||
## Relevant code
|
||||
|
||||
- Server owned history: `packages/server/src/server/agent/timeline/`
|
||||
- Server live stream forwarding: `packages/server/src/server/session.ts`
|
||||
- App sync planning: `packages/app/src/timeline/timeline-sync-plan.ts`
|
||||
- App viewed-agent synchronization: `packages/app/src/timeline/viewed-timeline-sync.ts`
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
Fixed
|
||||
- Fixed numbered sublists overlapping their text and quotes inside lists overlapping later messages on Android
|
||||
- Fixed Android terminal input so it asks the keyboard to exclude typed text from personalized learning
|
||||
- Fixed conversations disappearing when directory capitalization differs on a case-insensitive file system
|
||||
- Fixed interrupt and steer messages to archived agents being queued without starting a turn
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -0,0 +1,7 @@
|
||||
Fixed
|
||||
- Fixed numbered sublists overlapping their text and quotes inside lists overlapping later messages on Android
|
||||
- Fixed Android terminal input so it asks the keyboard to exclude typed text from personalized learning
|
||||
- Fixed conversations disappearing when directory capitalization differs on a case-insensitive file system
|
||||
- Fixed interrupt and steer messages to archived agents being queued without starting a turn
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -0,0 +1,7 @@
|
||||
Fixed
|
||||
- Fixed numbered sublists overlapping their text and quotes inside lists overlapping later messages on Android
|
||||
- Fixed Android terminal input so it asks the keyboard to exclude typed text from personalized learning
|
||||
- Fixed conversations disappearing when directory capitalization differs on a case-insensitive file system
|
||||
- Fixed interrupt and steer messages to archived agents being queued without starting a turn
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -0,0 +1,7 @@
|
||||
Fixed
|
||||
- Fixed numbered sublists overlapping their text and quotes inside lists overlapping later messages on Android
|
||||
- Fixed Android terminal input so it asks the keyboard to exclude typed text from personalized learning
|
||||
- Fixed conversations disappearing when directory capitalization differs on a case-insensitive file system
|
||||
- Fixed interrupt and steer messages to archived agents being queued without starting a turn
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -72,6 +72,7 @@
|
||||
"project": ["src/**/*.ts"]
|
||||
}
|
||||
},
|
||||
"ignoreWorkspaces": ["packages/react-native-enriched-markdown"],
|
||||
"ignoreDependencies": [
|
||||
"sherpa-onnx-node",
|
||||
"@playwright/test",
|
||||
|
||||
@@ -30,6 +30,8 @@ buildNpmPackage {
|
||||
# Exclude mobile-only platform code (we only need the web/electron build)
|
||||
!(lib.hasPrefix "/packages/app/android" relPath)
|
||||
&& !(lib.hasPrefix "/packages/app/ios" relPath)
|
||||
&& !(lib.hasPrefix "/packages/react-native-enriched-markdown/android" relPath)
|
||||
&& !(lib.hasPrefix "/packages/react-native-enriched-markdown/ios" relPath)
|
||||
# Website is unrelated to the desktop app
|
||||
&& !(lib.hasPrefix "/packages/website" relPath)
|
||||
# Documentation, CI definitions and agent/editor configuration. None of
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
sha256-f2/UslxzI8mmz0rl9c1bQ0P2H6zbq96u5NEuao5u1fI=
|
||||
sha256-IAhKhkolW4xvFvMaAEFdhYvPAhTm2azsqbGMKCKL3q0=
|
||||
|
||||
Generated
+134
-50
@@ -1,17 +1,18 @@
|
||||
{
|
||||
"name": "paseo",
|
||||
"version": "0.17.3",
|
||||
"version": "0.17.4",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "paseo",
|
||||
"version": "0.17.3",
|
||||
"version": "0.17.4",
|
||||
"hasInstallScript": true,
|
||||
"license": "Apache-2.0",
|
||||
"workspaces": [
|
||||
"plugins",
|
||||
"packages/expo-two-way-audio",
|
||||
"packages/react-native-enriched-markdown",
|
||||
"packages/highlight",
|
||||
"packages/plugin",
|
||||
"packages/protocol",
|
||||
@@ -44,6 +45,9 @@
|
||||
"react-dom": "19.2.3",
|
||||
"typescript": "^5.9.3",
|
||||
"ws": "^8.20.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.16.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@0no-co/graphql.web": {
|
||||
@@ -8519,6 +8523,52 @@
|
||||
"integrity": "sha512-Y28PR25bHXUg88kCV7nivXrP2Nj2RueZ3/l/jdx6J9f8J4nsEGcgX0Qe6lt7Pa+J79+kPiJU3LguR6O/6zrLOw==",
|
||||
"license": "BSD-2-Clause"
|
||||
},
|
||||
"node_modules/@modelcontextprotocol/client": {
|
||||
"version": "2.4.0",
|
||||
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/client/-/client-2.4.0.tgz",
|
||||
"integrity": "sha512-LgrD2OphHuG12vfKFKz6SOnq7bKHQmhGJIAYdD+MZBn2npHEyry6uD8zvktodtl5CQM85MO0anUyD9JwmUmxww==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@modelcontextprotocol/core": "2.4.0",
|
||||
"cross-spawn": "^7.0.5",
|
||||
"eventsource": "^3.0.2",
|
||||
"eventsource-parser": "^3.0.8",
|
||||
"jose": "^6.1.3",
|
||||
"pkce-challenge": "^5.0.0",
|
||||
"zod": "^4.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/@modelcontextprotocol/core": {
|
||||
"version": "2.4.0",
|
||||
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.4.0.tgz",
|
||||
"integrity": "sha512-z8QBKqdfXLPzkLQuG4xp8hrVEMm1PZ1IgxMN2sMbJiFiAKOWXnAzogXn2W4aqIBlP1ea6U5yiqVquvUNM1Cj6Q==",
|
||||
"dependencies": {
|
||||
"zod": "^4.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/@modelcontextprotocol/node": {
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/node/-/node-2.1.2.tgz",
|
||||
"integrity": "sha512-IIcIqBpr6NCQQs5DgJTgvbSOAw+3iaR/uquqg+e0nXCdudfjPg/80x0TseUnQx14AUAtE4fsJCEpJKPyb6WPVA==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@hono/node-server": "^1.19.9 || ^2.1.3",
|
||||
"hono": "^4.11.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@modelcontextprotocol/server": "^2.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@modelcontextprotocol/sdk": {
|
||||
"version": "1.29.0",
|
||||
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.29.0.tgz",
|
||||
@@ -8905,6 +8955,19 @@
|
||||
"url": "https://opencollective.com/express"
|
||||
}
|
||||
},
|
||||
"node_modules/@modelcontextprotocol/server": {
|
||||
"version": "2.4.0",
|
||||
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/server/-/server-2.4.0.tgz",
|
||||
"integrity": "sha512-rgR9yxSaAJ+bcsi/XroT/S2AfPiIWloXAnrdfYSCms9ivVju0ishu/wW0J21Ho6+ZOR1r7RyeRbjiRuF87ix5Q==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@modelcontextprotocol/core": "2.4.0",
|
||||
"zod": "^4.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/@msgpackr-extract/msgpackr-extract-darwin-arm64": {
|
||||
"version": "3.0.4",
|
||||
"resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-darwin-arm64/-/msgpackr-extract-darwin-arm64-3.0.4.tgz",
|
||||
@@ -20578,9 +20641,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/eventsource-parser": {
|
||||
"version": "3.0.6",
|
||||
"resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.0.6.tgz",
|
||||
"integrity": "sha512-Vo1ab+QXPzZ4tCa8SwIHJFaSzy4R6SHf7BY79rFBDf0idraZWAkYrDjDj8uWaSm3S2TK+hJ7/t1CEmZ7jXw+pg==",
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.1.tgz",
|
||||
"integrity": "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
@@ -31902,6 +31965,10 @@
|
||||
"react-native": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/react-native-enriched-markdown": {
|
||||
"resolved": "packages/react-native-enriched-markdown",
|
||||
"link": true
|
||||
},
|
||||
"node_modules/react-native-gesture-handler": {
|
||||
"version": "2.32.0",
|
||||
"resolved": "https://registry.npmjs.org/react-native-gesture-handler/-/react-native-gesture-handler-2.32.0.tgz",
|
||||
@@ -37477,7 +37544,7 @@
|
||||
},
|
||||
"packages/app": {
|
||||
"name": "@getpaseo/app",
|
||||
"version": "0.17.3",
|
||||
"version": "0.17.4",
|
||||
"dependencies": {
|
||||
"@codemirror/commands": "6.10.4",
|
||||
"@codemirror/language": "6.12.4",
|
||||
@@ -37561,7 +37628,7 @@
|
||||
"react-native": "0.86.3",
|
||||
"react-native-draggable-flatlist": "^4.0.3",
|
||||
"react-native-edge-to-edge": "^1.7.0",
|
||||
"react-native-enriched-markdown": "1.2.0-nightly-20261014-766fc0e67",
|
||||
"react-native-enriched-markdown": "*",
|
||||
"react-native-gesture-handler": "~2.32.0",
|
||||
"react-native-keyboard-controller": "1.21.12",
|
||||
"react-native-nitro-modules": "0.35.5",
|
||||
@@ -39474,23 +39541,6 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"packages/app/node_modules/react-native-enriched-markdown": {
|
||||
"version": "1.2.0-nightly-20261014-766fc0e67",
|
||||
"resolved": "https://registry.npmjs.org/react-native-enriched-markdown/-/react-native-enriched-markdown-1.2.0-nightly-20261014-766fc0e67.tgz",
|
||||
"integrity": "sha512-PyYAAVJAyjlcqHXgSnzxok13MDmyxs/nt46hHIOBdCc0prfaL2Ef6nYkZu7fFCeaETOJXd/xQr4n2/79I+gvdA==",
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"katex": ">=0.16.0",
|
||||
"react": "*",
|
||||
"react-native": "*"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"katex": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"packages/app/node_modules/react-native-keyboard-controller": {
|
||||
"version": "1.21.12",
|
||||
"resolved": "https://registry.npmjs.org/react-native-keyboard-controller/-/react-native-keyboard-controller-1.21.12.tgz",
|
||||
@@ -39647,13 +39697,13 @@
|
||||
},
|
||||
"packages/cli": {
|
||||
"name": "@getpaseo/cli",
|
||||
"version": "0.17.3",
|
||||
"version": "0.17.4",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@clack/prompts": "^1.0.0",
|
||||
"@getpaseo/client": "0.17.3",
|
||||
"@getpaseo/protocol": "0.17.3",
|
||||
"@getpaseo/server": "0.17.3",
|
||||
"@getpaseo/client": "0.17.4",
|
||||
"@getpaseo/protocol": "0.17.4",
|
||||
"@getpaseo/server": "0.17.4",
|
||||
"chalk": "^5.3.0",
|
||||
"commander": "^12.0.0",
|
||||
"mime-types": "^2.1.35",
|
||||
@@ -39672,6 +39722,9 @@
|
||||
"typescript": "^5.2.2",
|
||||
"vitest": "^4.1.6",
|
||||
"zx": "^8.8.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.16.0"
|
||||
}
|
||||
},
|
||||
"packages/cli/node_modules/@vitest/expect": {
|
||||
@@ -39900,11 +39953,11 @@
|
||||
},
|
||||
"packages/client": {
|
||||
"name": "@getpaseo/client",
|
||||
"version": "0.17.3",
|
||||
"version": "0.17.4",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@getpaseo/protocol": "0.17.3",
|
||||
"@getpaseo/relay": "0.17.3",
|
||||
"@getpaseo/protocol": "0.17.4",
|
||||
"@getpaseo/relay": "0.17.4",
|
||||
"ws": "^8.20.0",
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
@@ -39916,7 +39969,7 @@
|
||||
},
|
||||
"packages/desktop": {
|
||||
"name": "@getpaseo/desktop",
|
||||
"version": "0.17.3",
|
||||
"version": "0.17.4",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@getpaseo/cli": "*",
|
||||
@@ -40159,7 +40212,7 @@
|
||||
},
|
||||
"packages/expo-two-way-audio": {
|
||||
"name": "@getpaseo/expo-two-way-audio",
|
||||
"version": "0.17.3",
|
||||
"version": "0.17.4",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@types/jest": "^29.5.14",
|
||||
@@ -40205,7 +40258,7 @@
|
||||
},
|
||||
"packages/highlight": {
|
||||
"name": "@getpaseo/highlight",
|
||||
"version": "0.17.3",
|
||||
"version": "0.17.4",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@codemirror/language": "6.12.4",
|
||||
@@ -40235,7 +40288,7 @@
|
||||
},
|
||||
"packages/plugin": {
|
||||
"name": "@getpaseo/plugin",
|
||||
"version": "0.17.3",
|
||||
"version": "0.17.4",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "^1.4.0",
|
||||
@@ -40243,8 +40296,8 @@
|
||||
"use-sync-external-store": "^1.6.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@getpaseo/client": "0.17.3",
|
||||
"@getpaseo/protocol": "0.17.3",
|
||||
"@getpaseo/client": "0.17.4",
|
||||
"@getpaseo/protocol": "0.17.4",
|
||||
"@types/node": "^20.9.0",
|
||||
"@types/react": "~19.2.0",
|
||||
"react": "19.2.3",
|
||||
@@ -40254,8 +40307,8 @@
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@getpaseo/client": "0.17.3",
|
||||
"@getpaseo/protocol": "0.17.3",
|
||||
"@getpaseo/client": "0.17.4",
|
||||
"@getpaseo/protocol": "0.17.4",
|
||||
"react": ">=19.1.0 <20",
|
||||
"react-native": ">=0.81.5",
|
||||
"zod": "^4.4.3"
|
||||
@@ -40277,7 +40330,7 @@
|
||||
},
|
||||
"packages/protocol": {
|
||||
"name": "@getpaseo/protocol",
|
||||
"version": "0.17.3",
|
||||
"version": "0.17.4",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"semver": "^7.8.5",
|
||||
@@ -40303,9 +40356,24 @@
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"packages/react-native-enriched-markdown": {
|
||||
"version": "0.17.4",
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"katex": ">=0.16.0",
|
||||
"react": "*",
|
||||
"react-native": "*"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"katex": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"packages/relay": {
|
||||
"name": "@getpaseo/relay",
|
||||
"version": "0.17.3",
|
||||
"version": "0.17.4",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@noble/ciphers": "^2.4.0",
|
||||
@@ -40527,19 +40595,21 @@
|
||||
},
|
||||
"packages/server": {
|
||||
"name": "@getpaseo/server",
|
||||
"version": "0.17.3",
|
||||
"version": "0.17.4",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "^0.17.1",
|
||||
"@anthropic-ai/claude-agent-sdk": "0.3.326",
|
||||
"@anthropic-ai/sdk": "^0.104.2",
|
||||
"@getpaseo/client": "0.17.3",
|
||||
"@getpaseo/highlight": "0.17.3",
|
||||
"@getpaseo/plugin": "0.17.3",
|
||||
"@getpaseo/protocol": "0.17.3",
|
||||
"@getpaseo/relay": "0.17.3",
|
||||
"@getpaseo/client": "0.17.4",
|
||||
"@getpaseo/highlight": "0.17.4",
|
||||
"@getpaseo/plugin": "0.17.4",
|
||||
"@getpaseo/protocol": "0.17.4",
|
||||
"@getpaseo/relay": "0.17.4",
|
||||
"@isaacs/ttlcache": "^2.1.4",
|
||||
"@modelcontextprotocol/node": "2.1.2",
|
||||
"@modelcontextprotocol/sdk": "1.29.0",
|
||||
"@modelcontextprotocol/server": "2.4.0",
|
||||
"@opencode-ai/sdk": "1.14.46",
|
||||
"@opencode/client": "2.0.10",
|
||||
"@xterm/addon-serialize": "0.14.0",
|
||||
@@ -40578,10 +40648,11 @@
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@modelcontextprotocol/client": "2.4.0",
|
||||
"@playwright/test": "^1.56.1",
|
||||
"@types/express": "^4.17.20",
|
||||
"@types/markdown-it": "^14.2.0",
|
||||
"@types/node": "^20.9.0",
|
||||
"@types/node": "^22.16.0",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@types/uuid": "^9.0.7",
|
||||
"@types/ws": "^8.5.8",
|
||||
@@ -40589,6 +40660,9 @@
|
||||
"cross-env": "^10.1.0",
|
||||
"tsx": "^4.6.0",
|
||||
"vitest": "^4.1.6"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.16.0"
|
||||
}
|
||||
},
|
||||
"packages/server/node_modules/@esbuild/aix-ppc64": {
|
||||
@@ -41036,6 +41110,16 @@
|
||||
"@types/mdurl": "^2"
|
||||
}
|
||||
},
|
||||
"packages/server/node_modules/@types/node": {
|
||||
"version": "22.20.5",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz",
|
||||
"integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"undici-types": "~6.21.0"
|
||||
}
|
||||
},
|
||||
"packages/server/node_modules/@vitest/expect": {
|
||||
"version": "4.1.6",
|
||||
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.6.tgz",
|
||||
@@ -41484,7 +41568,7 @@
|
||||
},
|
||||
"packages/website": {
|
||||
"name": "@getpaseo/website",
|
||||
"version": "0.17.3",
|
||||
"version": "0.17.4",
|
||||
"dependencies": {
|
||||
"@cloudflare/vite-plugin": "^1.29.1",
|
||||
"@cloudflare/workers-types": "^4.20260317.1",
|
||||
@@ -43095,7 +43179,7 @@
|
||||
},
|
||||
"plugins": {
|
||||
"name": "@getpaseo/builtin-plugins",
|
||||
"version": "0.17.3",
|
||||
"version": "0.17.4",
|
||||
"dependencies": {
|
||||
"@getpaseo/plugin": "*",
|
||||
"zod": "^4.4.3"
|
||||
|
||||
+5
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "paseo",
|
||||
"version": "0.17.3",
|
||||
"version": "0.17.4",
|
||||
"private": true,
|
||||
"description": "Paseo: voice-controlled development environment for local AI coding agents",
|
||||
"keywords": [
|
||||
@@ -23,6 +23,7 @@
|
||||
"workspaces": [
|
||||
"plugins",
|
||||
"packages/expo-two-way-audio",
|
||||
"packages/react-native-enriched-markdown",
|
||||
"packages/highlight",
|
||||
"packages/plugin",
|
||||
"packages/protocol",
|
||||
@@ -168,5 +169,8 @@
|
||||
"tiny-async-pool": {
|
||||
"semver@^5": "5.7.2"
|
||||
}
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.16.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,13 @@ import {
|
||||
import { expectNearBottom, scrollChatAwayFromBottom } from "../support/helpers/agent-bottom-anchor";
|
||||
import { holdRewindCompletion } from "../support/helpers/agent-timeline-gate";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
import { userScrollsTimelineToHistoryStart } from "../support/helpers/timeline-pagination";
|
||||
import {
|
||||
closeWorkspaceAgentTab,
|
||||
fetchAgentArchivedAt,
|
||||
primeAdditionalPage,
|
||||
resetSeededPageState,
|
||||
} from "../support/helpers/archive-tab";
|
||||
|
||||
async function completeSubmittedTurn(
|
||||
page: Page,
|
||||
@@ -48,26 +55,102 @@ async function expectTurnCompletesNormally(
|
||||
await expectAgentIdle(page);
|
||||
}
|
||||
|
||||
async function openAgentOnAnotherClient(
|
||||
page: Page,
|
||||
agent: Awaited<ReturnType<typeof seedMockAgentWorkspace>>,
|
||||
): Promise<void> {
|
||||
await primeAdditionalPage(page);
|
||||
await resetSeededPageState(page);
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
}
|
||||
|
||||
/** The prompts the chat shows, in order, each exactly once. */
|
||||
async function expectPrompts(page: Page, prompts: string[]): Promise<void> {
|
||||
const messages = page.getByTestId("user-message");
|
||||
await expect(messages).toHaveCount(prompts.length);
|
||||
await expect(messages).toContainText(prompts);
|
||||
}
|
||||
|
||||
async function reloadAgentFromTabMenu(page: Page, agentId: string): Promise<void> {
|
||||
const tabId = `workspace-tab-agent_${agentId}`;
|
||||
await page.getByTestId(tabId).filter({ visible: true }).first().click({ button: "right" });
|
||||
await page.getByTestId(`workspace-tab-context-agent_${agentId}-reload-agent`).click();
|
||||
}
|
||||
|
||||
async function archiveAgentByClosingTab(
|
||||
page: Page,
|
||||
agent: Awaited<ReturnType<typeof seedMockAgentWorkspace>>,
|
||||
): Promise<void> {
|
||||
await closeWorkspaceAgentTab(page, agent.agentId);
|
||||
await expect.poll(() => fetchAgentArchivedAt(agent.client, agent.agentId)).not.toBeNull();
|
||||
}
|
||||
|
||||
async function unarchiveAgent(page: Page): Promise<void> {
|
||||
await page.getByRole("button", { name: "Unarchive", exact: true }).click();
|
||||
await expect(page.getByText("This agent is archived", { exact: true })).toHaveCount(0, {
|
||||
timeout: 30_000,
|
||||
});
|
||||
}
|
||||
|
||||
async function expectToast(page: Page, message: string): Promise<void> {
|
||||
await expect(page.getByTestId("app-toast-message")).toHaveText(message, { timeout: 30_000 });
|
||||
}
|
||||
|
||||
// The mock provider's resumed session holds no history, so it never matches what Paseo shows.
|
||||
const UNSYNCED_RELOAD =
|
||||
"Reloaded agent, but the provider's history doesn't match this chat, so it wasn't synced";
|
||||
|
||||
/** The prompts of the whole conversation, after scrolling up through its older pages. */
|
||||
async function expectConversationPrompts(page: Page, prompts: string[]): Promise<void> {
|
||||
const messages = page.getByTestId("user-message");
|
||||
await expect
|
||||
.poll(async () => {
|
||||
await userScrollsTimelineToHistoryStart(page);
|
||||
return await messages.count();
|
||||
})
|
||||
.toBe(prompts.length);
|
||||
await expect(messages).toContainText(prompts);
|
||||
}
|
||||
|
||||
// A row React remounts loses this attribute; one that stays mounted keeps it.
|
||||
async function markMounted(row: Locator): Promise<void> {
|
||||
await row.evaluate((element) => element.setAttribute("data-e2e-mounted", "before-rewind"));
|
||||
}
|
||||
|
||||
async function expectStillMounted(row: Locator): Promise<void> {
|
||||
await expect(row).toHaveAttribute("data-e2e-mounted", "before-rewind");
|
||||
}
|
||||
|
||||
test.describe("Agent message rewind", () => {
|
||||
test("rewinds a submitted prompt without replaying history and preserves a human draft", async ({
|
||||
test("rewinds a prompt in place on every open client and keeps a human draft", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(90_000);
|
||||
test.setTimeout(150_000);
|
||||
const retainedPrompt = "Keep this completed turn after rewind.";
|
||||
const rewoundPrompt = "Remove this completed turn after rewind.";
|
||||
const nextPrompt = "Continue after the rewind.";
|
||||
const preservedDraft = "Keep this human draft after rewind.";
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "message-rewind-roundtrip-",
|
||||
title: "Message rewind roundtrip",
|
||||
model: "ten-second-stream",
|
||||
});
|
||||
const otherClient = await page.context().newPage();
|
||||
|
||||
try {
|
||||
const rewindCompletion = await holdRewindCompletion(page, agent.agentId);
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
await completeSubmittedTurn(page, agent, retainedPrompt);
|
||||
const retainedMessage = await completeSubmittedTurn(page, agent, retainedPrompt);
|
||||
const userMessage = await completeSubmittedTurn(page, agent, rewoundPrompt);
|
||||
|
||||
await test.step("a second client opens the same chat", async () => {
|
||||
await openAgentOnAnotherClient(otherClient, agent);
|
||||
await expectPrompts(otherClient, [retainedPrompt, rewoundPrompt]);
|
||||
});
|
||||
|
||||
await markMounted(retainedMessage);
|
||||
await scrollChatAwayFromBottom(page, {
|
||||
deltaY: -900,
|
||||
minDistanceFromBottom: 300,
|
||||
@@ -76,19 +159,92 @@ test.describe("Agent message rewind", () => {
|
||||
await blurComposerInput(page);
|
||||
rewindCompletion.clearTimelineStreamCount();
|
||||
|
||||
const rewind = rewindConversation(page, userMessage, rewoundPrompt);
|
||||
await rewindCompletion.waitForDelayedResponse();
|
||||
await expect(page.getByTestId("rewind-menu-conversation")).toBeDisabled();
|
||||
expect(rewindCompletion.timelineStreamCount()).toBe(0);
|
||||
rewindCompletion.release();
|
||||
await rewind;
|
||||
await test.step("the rewind stays pending until the daemon answers", async () => {
|
||||
const rewind = rewindConversation(page, userMessage, rewoundPrompt);
|
||||
await rewindCompletion.waitForDelayedResponse();
|
||||
await expect(page.getByTestId("rewind-menu-conversation")).toBeDisabled();
|
||||
expect(rewindCompletion.timelineStreamCount()).toBe(0);
|
||||
rewindCompletion.release();
|
||||
await rewind;
|
||||
});
|
||||
|
||||
await expect(page.getByTestId("user-message").filter({ hasText: rewoundPrompt })).toHaveCount(
|
||||
0,
|
||||
);
|
||||
await expectComposerDraft(page, preservedDraft);
|
||||
await expectComposerNotFocused(page);
|
||||
await expectNearBottom(page);
|
||||
await test.step("the rewound turn leaves without reloading the chat", async () => {
|
||||
await expectPrompts(page, [retainedPrompt]);
|
||||
await expectStillMounted(retainedMessage);
|
||||
expect(rewindCompletion.timelineFetchCount()).toBe(0);
|
||||
await expectComposerDraft(page, preservedDraft);
|
||||
await expectComposerNotFocused(page);
|
||||
await expectNearBottom(page);
|
||||
await expectPrompts(otherClient, [retainedPrompt]);
|
||||
});
|
||||
|
||||
await test.step("the next prompt appears once on both clients", async () => {
|
||||
await completeSubmittedTurn(otherClient, agent, nextPrompt);
|
||||
await expectPrompts(otherClient, [retainedPrompt, nextPrompt]);
|
||||
await expectPrompts(page, [retainedPrompt, nextPrompt]);
|
||||
});
|
||||
|
||||
await test.step("a reconnecting client loads the rewound conversation", async () => {
|
||||
await otherClient.reload();
|
||||
await expectPrompts(otherClient, [retainedPrompt, nextPrompt]);
|
||||
});
|
||||
} finally {
|
||||
await otherClient.close();
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps the rewound conversation through Reload agent, archive and unarchive", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(150_000);
|
||||
const keptPrompt = "Keep this turn through reload and archive.";
|
||||
const rewoundPrompt = "Rewind this turn before reloading.";
|
||||
const nextPrompt = "Continue after the rewind, then reload.";
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "message-rewind-reload-archive-",
|
||||
title: "Message rewind reload archive",
|
||||
model: "ten-second-stream",
|
||||
});
|
||||
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
await completeSubmittedTurn(page, agent, keptPrompt);
|
||||
const rewound = await completeSubmittedTurn(page, agent, rewoundPrompt);
|
||||
await rewindConversation(page, rewound, rewoundPrompt);
|
||||
await expectPrompts(page, [keptPrompt]);
|
||||
await completeSubmittedTurn(page, agent, nextPrompt);
|
||||
await expectPrompts(page, [keptPrompt, nextPrompt]);
|
||||
|
||||
await test.step("Reload agent keeps the chat and says the provider's history was not synced", async () => {
|
||||
await reloadAgentFromTabMenu(page, agent.agentId);
|
||||
await expectToast(page, UNSYNCED_RELOAD);
|
||||
await expectPrompts(page, [keptPrompt, nextPrompt]);
|
||||
await expectComposerVisible(page);
|
||||
});
|
||||
|
||||
await test.step("the archived chat shows the rewound conversation", async () => {
|
||||
await archiveAgentByClosingTab(page, agent);
|
||||
await openAgentRoute(page, agent);
|
||||
await expect(page.getByText("This agent is archived", { exact: true })).toBeVisible({
|
||||
timeout: 30_000,
|
||||
});
|
||||
await expectConversationPrompts(page, [keptPrompt, nextPrompt]);
|
||||
});
|
||||
|
||||
await test.step("unarchiving keeps the rewound conversation", async () => {
|
||||
await unarchiveAgent(page);
|
||||
await expectToast(page, UNSYNCED_RELOAD);
|
||||
await expectComposerVisible(page);
|
||||
await expectConversationPrompts(page, [keptPrompt, nextPrompt]);
|
||||
});
|
||||
|
||||
await test.step("a reconnecting client loads the same conversation", async () => {
|
||||
await page.reload();
|
||||
await expectComposerVisible(page);
|
||||
await expectConversationPrompts(page, [keptPrompt, nextPrompt]);
|
||||
});
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { mkdir, readFile, unlink, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { type Locator, type Page } from "@playwright/test";
|
||||
@@ -471,6 +472,83 @@ test("All changes combines committed and pending edits and preserves an unfinish
|
||||
});
|
||||
});
|
||||
|
||||
test("Changes offers Push for a branch that was never pushed and the push sets its upstream", async ({
|
||||
page,
|
||||
}) => {
|
||||
const workspace = await createWorkspaceWithRemote((repoPath) => {
|
||||
execFileSync("git", ["checkout", "-b", "feature"], { cwd: repoPath });
|
||||
});
|
||||
await openWorkspaceChangesSurface(page, workspace);
|
||||
const primary = page.getByTestId("changes-primary-cta");
|
||||
|
||||
await test.step("committing the edit makes Push the primary action", async () => {
|
||||
await expect(primary).toHaveAccessibleName("Commit", { timeout: 30_000 });
|
||||
commitAllWithGit(workspace.repoPath, "Feature work");
|
||||
await expect(primary).toHaveAccessibleName("Push", { timeout: 30_000 });
|
||||
});
|
||||
await test.step("Push sends the branch and sets its upstream", async () => {
|
||||
await primary.click();
|
||||
await expect
|
||||
.poll(() => remoteBranchHead(workspace, "feature"), { timeout: 30_000 })
|
||||
.toBe(localHead(workspace));
|
||||
// git writes the upstream after the remote has the branch, so wait for it too.
|
||||
await expect
|
||||
.poll(() => branchUpstream(workspace, "feature"), { timeout: 30_000 })
|
||||
.toBe("origin/feature");
|
||||
await expect(primary).not.toHaveAccessibleName("Push", { timeout: 30_000 });
|
||||
});
|
||||
});
|
||||
|
||||
test("Changes pushes and pulls a branch whose only remote is not named origin", async ({
|
||||
page,
|
||||
}) => {
|
||||
const workspace = await createWorkspaceWithRemote((repoPath) => {
|
||||
execFileSync("git", ["remote", "rename", "origin", "doras-mono"], { cwd: repoPath });
|
||||
// git pull stops on a branch that is both ahead and behind until it is told how to combine them.
|
||||
execFileSync("git", ["config", "pull.rebase", "false"], { cwd: repoPath });
|
||||
});
|
||||
await openWorkspaceChangesSurface(page, workspace);
|
||||
const primary = page.getByTestId("changes-primary-cta");
|
||||
|
||||
await test.step("a branch that is ahead offers Push and the push updates the remote", async () => {
|
||||
await expect(primary).toHaveAccessibleName("Commit", { timeout: 30_000 });
|
||||
commitAllWithGit(workspace.repoPath, "Local work");
|
||||
expect(trackingStatus(workspace)).toBe("## main...doras-mono/main [ahead 1]");
|
||||
await expect(primary).toHaveAccessibleName("Push", { timeout: 30_000 });
|
||||
await primary.click();
|
||||
await expectInSyncWithRemote(workspace);
|
||||
expect(remoteBranchSubjects(workspace, "main")).toContain("Local work");
|
||||
await expectNoGitActionLeft(page);
|
||||
});
|
||||
await test.step("a branch that is behind offers Pull and the pull brings the commits in", async () => {
|
||||
pushTeammateCommits(workspace, ["Teammate one", "Teammate two"]);
|
||||
fetchRemote(workspace, "doras-mono");
|
||||
expect(trackingStatus(workspace)).toBe("## main...doras-mono/main [behind 2]");
|
||||
await expect(primary).toHaveAccessibleName("Pull", { timeout: 30_000 });
|
||||
await primary.click();
|
||||
await expectInSyncWithRemote(workspace);
|
||||
expect(localBranchSubjects(workspace)).toEqual(
|
||||
expect.arrayContaining(["Local work", "Teammate one", "Teammate two"]),
|
||||
);
|
||||
await expectNoGitActionLeft(page);
|
||||
});
|
||||
await test.step("a branch that is ahead and behind pulls and then pushes", async () => {
|
||||
await writeFile(path.join(workspace.repoPath, "tracked.ts"), "export const tracked = 3;\n");
|
||||
commitAllWithGit(workspace.repoPath, "More local work");
|
||||
pushTeammateCommits(workspace, ["Teammate three", "Teammate four"]);
|
||||
fetchRemote(workspace, "doras-mono");
|
||||
expect(trackingStatus(workspace)).toBe("## main...doras-mono/main [ahead 1, behind 2]");
|
||||
await expect(primary).toHaveAccessibleName("Pull", { timeout: 30_000 });
|
||||
await page.getByTestId("changes-primary-cta-caret").click();
|
||||
await page.getByTestId("changes-menu-pull-and-push").click();
|
||||
await expectInSyncWithRemote(workspace);
|
||||
expect(remoteBranchSubjects(workspace, "main")).toEqual(
|
||||
expect.arrayContaining(["More local work", "Teammate three", "Teammate four"]),
|
||||
);
|
||||
await expectNoGitActionLeft(page);
|
||||
});
|
||||
});
|
||||
|
||||
test("Changes selects exact local and remote bases and retains the selection after reload", async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
@@ -2122,6 +2200,141 @@ async function createWorkspaceWithMountedTabDiff(
|
||||
return { id: createdWorkspace.workspace.id, repoPath: repo.path };
|
||||
}
|
||||
|
||||
interface RemoteWorkspace extends DirtyWorkspace {
|
||||
remotePath: string;
|
||||
}
|
||||
|
||||
// A regular checkout with a local bare remote and one uncommitted edit.
|
||||
async function createWorkspaceWithRemote(
|
||||
prepare: (repoPath: string) => void,
|
||||
): Promise<RemoteWorkspace> {
|
||||
const repo = await createTempGitRepo("changes-push-", {
|
||||
withRemote: true,
|
||||
files: [{ path: "tracked.ts", content: "export const tracked = 1;\n" }],
|
||||
});
|
||||
const client = await connectSeedClient();
|
||||
cleanupTasks.push({
|
||||
run: async () => {
|
||||
await client.close();
|
||||
await repo.cleanup();
|
||||
},
|
||||
});
|
||||
// The helper keeps the bare remote inside the checkout; keep it out of the status.
|
||||
await writeFile(path.join(repo.path, ".git/info/exclude"), "remote.git/\n");
|
||||
prepare(repo.path);
|
||||
await writeFile(path.join(repo.path, "tracked.ts"), "export const tracked = 2;\n");
|
||||
const created = await client.createWorkspace({ source: { kind: "directory", path: repo.path } });
|
||||
if (!created.workspace) {
|
||||
throw new Error(created.error ?? `Failed to create workspace ${repo.path}`);
|
||||
}
|
||||
return {
|
||||
id: created.workspace.id,
|
||||
repoPath: repo.path,
|
||||
remotePath: path.join(repo.path, "remote.git"),
|
||||
};
|
||||
}
|
||||
|
||||
// The app's Commit asks an agent provider for a message, and this harness has none.
|
||||
function commitAllWithGit(repoPath: string, message: string): void {
|
||||
execFileSync("git", ["commit", "-am", message], { cwd: repoPath, stdio: "ignore" });
|
||||
}
|
||||
|
||||
function localHead(workspace: RemoteWorkspace): string {
|
||||
return execFileSync("git", ["rev-parse", "HEAD"], {
|
||||
cwd: workspace.repoPath,
|
||||
encoding: "utf8",
|
||||
}).trim();
|
||||
}
|
||||
|
||||
function remoteBranchHead(workspace: RemoteWorkspace, branch: string): string | null {
|
||||
const line = execFileSync("git", ["ls-remote", "--heads", workspace.remotePath, branch], {
|
||||
encoding: "utf8",
|
||||
}).trim();
|
||||
return line ? (line.split("\t")[0] ?? null) : null;
|
||||
}
|
||||
|
||||
// The branch line of `git status -sb`, such as "## main...origin/main [ahead 1, behind 2]".
|
||||
function trackingStatus(workspace: RemoteWorkspace): string {
|
||||
const status = execFileSync("git", ["status", "-sb"], {
|
||||
cwd: workspace.repoPath,
|
||||
encoding: "utf8",
|
||||
});
|
||||
return status.split("\n")[0] ?? "";
|
||||
}
|
||||
|
||||
// Neither ahead nor behind, which a push reaches only after the remote accepted it.
|
||||
async function expectInSyncWithRemote(workspace: RemoteWorkspace): Promise<void> {
|
||||
await expect
|
||||
.poll(() => trackingStatus(workspace), { timeout: 30_000 })
|
||||
.toMatch(/^## [^ ]+\.\.\.[^ ]+$/);
|
||||
}
|
||||
|
||||
// A clean main that is in sync with its remote has no git action, so the button is gone.
|
||||
async function expectNoGitActionLeft(page: Page): Promise<void> {
|
||||
await expect(page.getByTestId("changes-primary-cta")).toBeHidden({ timeout: 30_000 });
|
||||
}
|
||||
|
||||
function localBranchSubjects(workspace: RemoteWorkspace): string[] {
|
||||
return commitSubjects(workspace.repoPath, "HEAD");
|
||||
}
|
||||
|
||||
function remoteBranchSubjects(workspace: RemoteWorkspace, branch: string): string[] {
|
||||
return commitSubjects(workspace.remotePath, branch);
|
||||
}
|
||||
|
||||
function commitSubjects(repoPath: string, revision: string): string[] {
|
||||
const log = execFileSync("git", ["log", "--format=%s", revision], {
|
||||
cwd: repoPath,
|
||||
encoding: "utf8",
|
||||
});
|
||||
return log.trim().split("\n");
|
||||
}
|
||||
|
||||
// Paseo fetches only origin in the background, so the checkout learns about another remote's
|
||||
// commits when the user fetches it.
|
||||
function fetchRemote(workspace: RemoteWorkspace, remoteName: string): void {
|
||||
execFileSync("git", ["fetch", "--quiet", remoteName], { cwd: workspace.repoPath });
|
||||
}
|
||||
|
||||
// Lands commits on the remote's main from a second clone, as a teammate's push does.
|
||||
function pushTeammateCommits(workspace: RemoteWorkspace, subjects: string[]): void {
|
||||
const clonePath = mkdtempSync(path.join(path.dirname(workspace.repoPath), "changes-teammate-"));
|
||||
try {
|
||||
execFileSync("git", ["clone", "--quiet", workspace.remotePath, clonePath]);
|
||||
for (const subject of subjects) {
|
||||
execFileSync(
|
||||
"git",
|
||||
[
|
||||
"-c",
|
||||
"user.name=Teammate",
|
||||
"-c",
|
||||
"user.email=teammate@paseo.test",
|
||||
"-c",
|
||||
"commit.gpgsign=false",
|
||||
"commit",
|
||||
"--quiet",
|
||||
"--allow-empty",
|
||||
"-m",
|
||||
subject,
|
||||
],
|
||||
{ cwd: clonePath },
|
||||
);
|
||||
}
|
||||
execFileSync("git", ["push", "--quiet", "origin", "HEAD:main"], { cwd: clonePath });
|
||||
} finally {
|
||||
rmSync(clonePath, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
// Empty until the branch has an upstream.
|
||||
function branchUpstream(workspace: RemoteWorkspace, branch: string): string {
|
||||
return execFileSync(
|
||||
"git",
|
||||
["for-each-ref", "--format=%(upstream:short)", `refs/heads/${branch}`],
|
||||
{ cwd: workspace.repoPath, encoding: "utf8" },
|
||||
).trim();
|
||||
}
|
||||
|
||||
async function createWorkspaceWithNetDiff(): Promise<DirtyWorkspace> {
|
||||
const repo = await createTempGitRepo("changes-net-", {
|
||||
files: [{ path: "a-tracked.ts", content: "base\n" }],
|
||||
|
||||
@@ -235,7 +235,7 @@ test.describe("Rewind sheet", () => {
|
||||
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
|
||||
await expect(userMessage(page, secondPrompt)).toHaveCount(0);
|
||||
await expect(page.getByText("Cycle 1", { exact: true })).toHaveCount(0);
|
||||
await expectUserMessageCount(page, 1);
|
||||
await expectUserMessageCount(page, 0);
|
||||
await expectComposerDraft(page, firstPrompt);
|
||||
await expectComposerFocused(page);
|
||||
|
||||
@@ -243,7 +243,7 @@ test.describe("Rewind sheet", () => {
|
||||
await expectUserMessageVisible(page, replacementPrompt);
|
||||
await expect(userMessage(page, secondPrompt)).toHaveCount(0);
|
||||
await expect(page.getByText("Cycle 1", { exact: true })).toHaveCount(0);
|
||||
await expectUserMessageCount(page, 2);
|
||||
await expectUserMessageCount(page, 1);
|
||||
|
||||
await fillComposerDraft(page, "");
|
||||
await composerLocator(page).evaluate((element) => element.blur());
|
||||
@@ -254,7 +254,19 @@ test.describe("Rewind sheet", () => {
|
||||
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
|
||||
await expectComposerDraft(page, "");
|
||||
await expectComposerNotFocused(page);
|
||||
await expectUserMessageCount(page, 2);
|
||||
await expectUserMessageCount(page, 1);
|
||||
|
||||
const preservedDraft = "Keep this human draft after rewind.";
|
||||
await fillComposerDraft(page, preservedDraft);
|
||||
await composerLocator(page).evaluate((element) => element.blur());
|
||||
await userMessage(page, replacementPrompt).hover();
|
||||
await page.getByTestId("rewind-menu-trigger").last().click();
|
||||
await expect(page.getByTestId("rewind-menu-content")).toBeVisible();
|
||||
await selectRewindOption(page, "Rewind files");
|
||||
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
|
||||
await expectComposerDraft(page, preservedDraft);
|
||||
await expectComposerNotFocused(page);
|
||||
await expectUserMessageCount(page, 1);
|
||||
|
||||
await fillComposerDraft(page, "");
|
||||
await composerLocator(page).evaluate((element) => element.blur());
|
||||
@@ -265,7 +277,7 @@ test.describe("Rewind sheet", () => {
|
||||
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
|
||||
await expectComposerDraft(page, replacementPrompt);
|
||||
await expectComposerFocused(page);
|
||||
await expectUserMessageCount(page, 1);
|
||||
await expectUserMessageCount(page, 0);
|
||||
} finally {
|
||||
await session.cleanup();
|
||||
}
|
||||
|
||||
@@ -64,6 +64,11 @@ import {
|
||||
expectSettingsHostPickerLabel,
|
||||
openSettingsHostSection,
|
||||
removeCurrentHostFromSettings,
|
||||
openSidebarHostPicker,
|
||||
sidebarHostSettingsButton,
|
||||
expectStandaloneSidebarHostSettingsButton,
|
||||
activateSidebarHostSettingsWithKeyboard,
|
||||
bindCommandCenterToEnter,
|
||||
} from "../support/helpers/settings";
|
||||
import { getServerId } from "../support/helpers/server-id";
|
||||
import { expectAppRoute } from "../support/helpers/route-assertions";
|
||||
@@ -187,6 +192,26 @@ test.describe("Settings sidebar scroll position", () => {
|
||||
});
|
||||
|
||||
test.describe("Settings sidebar navigation", () => {
|
||||
test("the sidebar host gear opens Overview in one click", async ({ page, withWorkspace }) => {
|
||||
const workspace = await withWorkspace({ prefix: "sidebar-host-settings-" });
|
||||
await openWorkspace(page, workspace);
|
||||
await openSidebarHostPicker(page);
|
||||
await expectStandaloneSidebarHostSettingsButton(page);
|
||||
await sidebarHostSettingsButton(page).click();
|
||||
|
||||
await expectAppRoute(page, buildSettingsHostSectionRoute(getServerId(), "host"));
|
||||
});
|
||||
|
||||
test("Enter opens the focused sidebar host gear", async ({ page, withWorkspace }) => {
|
||||
await bindCommandCenterToEnter(page);
|
||||
const workspace = await withWorkspace({ prefix: "keyboard-host-settings-" });
|
||||
await openWorkspace(page, workspace);
|
||||
await openSidebarHostPicker(page);
|
||||
await activateSidebarHostSettingsWithKeyboard(page);
|
||||
|
||||
await expectAppRoute(page, buildSettingsHostSectionRoute(getServerId(), "host"));
|
||||
});
|
||||
|
||||
test("opening Settings closes the composer model selector until it is opened again", async ({
|
||||
page,
|
||||
withWorkspace,
|
||||
|
||||
@@ -28,12 +28,13 @@ bounds cannot establish measurement parity.
|
||||
compares them with the shipped headers. This catches missing C++ fields in the
|
||||
measurement path, which the Kotlin tests cannot exercise.
|
||||
|
||||
The package patch contains `InlineCodeFormattingTest`, which exercises actual
|
||||
Android spans in Robolectric native graphics mode, covering draw and measurement,
|
||||
span order, code inside paragraph/heading sizes, bold/italic composition, and
|
||||
links preserving code and emphasized prose fonts.
|
||||
It runs in the existing `test:android` CI job. To run only this regression locally,
|
||||
from `packages/app/android` after Expo prebuild:
|
||||
The vendored library (`packages/react-native-enriched-markdown`) contains
|
||||
`InlineCodeFormattingTest`, which exercises actual Android spans in Robolectric
|
||||
native graphics mode, covering draw and measurement, span order, code inside
|
||||
paragraph/heading sizes, bold/italic composition, and links preserving code and
|
||||
emphasized prose fonts. It runs in `npm run test:android`; CI does not run it.
|
||||
To run only this regression locally, from `packages/app/android` after Expo
|
||||
prebuild:
|
||||
|
||||
```sh
|
||||
./gradlew :react-native-enriched-markdown:testDebugUnitTest \
|
||||
|
||||
@@ -31,6 +31,8 @@ export interface RewindCompletionGate {
|
||||
clearTimelineStreamCount(): void;
|
||||
release(): void;
|
||||
timelineStreamCount(): number;
|
||||
/** Timeline reads this page sent since the last clear. */
|
||||
timelineFetchCount(): number;
|
||||
waitForDelayedResponse(): Promise<void>;
|
||||
}
|
||||
|
||||
@@ -186,12 +188,20 @@ export async function holdDaemonHydration(page: Page): Promise<DaemonHydrationGa
|
||||
};
|
||||
}
|
||||
|
||||
// The rewind response and the timeline change it causes; the change removes the rewound row too.
|
||||
const REWIND_COMPLETION_MESSAGES = new Set([
|
||||
"agent.rewind.response",
|
||||
"agent.timeline.rewind",
|
||||
"agent.timeline.replacement",
|
||||
]);
|
||||
|
||||
export async function holdRewindCompletion(
|
||||
page: Page,
|
||||
agentId: string,
|
||||
): Promise<RewindCompletionGate> {
|
||||
let released = false;
|
||||
let timelineStreamCount = 0;
|
||||
let timelineFetchCount = 0;
|
||||
const delayedForwards: Array<() => void> = [];
|
||||
let resolveDelayedResponse: (() => void) | null = null;
|
||||
const delayedResponse = new Promise<void>((resolve) => {
|
||||
@@ -200,7 +210,16 @@ export async function holdRewindCompletion(
|
||||
|
||||
await page.routeWebSocket(daemonWsRoutePattern(), (ws) => {
|
||||
const server = ws.connectToServer();
|
||||
ws.onMessage((message) => server.send(message));
|
||||
ws.onMessage((message) => {
|
||||
const sessionMessage = getSessionMessage(message);
|
||||
if (
|
||||
sessionMessage?.type === "fetch_agent_timeline_request" &&
|
||||
sessionMessage.agentId === agentId
|
||||
) {
|
||||
timelineFetchCount += 1;
|
||||
}
|
||||
server.send(message);
|
||||
});
|
||||
server.onMessage((message) => {
|
||||
const sessionMessage = getSessionMessage(message);
|
||||
const payload = sessionMessage ? getPayload(sessionMessage) : null;
|
||||
@@ -216,11 +235,11 @@ export async function holdRewindCompletion(
|
||||
}
|
||||
if (
|
||||
!released &&
|
||||
(sessionMessage?.type === "agent.rewind.response" ||
|
||||
sessionMessage?.type === "agent.timeline.replacement") &&
|
||||
sessionMessage &&
|
||||
REWIND_COMPLETION_MESSAGES.has(String(sessionMessage.type)) &&
|
||||
payload?.agentId === agentId
|
||||
) {
|
||||
// The replacement also signals completion and removes the rewound row/menu.
|
||||
// The rewind also signals completion and removes the rewound row/menu.
|
||||
// Hold it with the response so the pending-state assertion observes a pending rewind.
|
||||
delayedForwards.push(() => ws.send(message));
|
||||
if (sessionMessage.type === "agent.rewind.response") resolveDelayedResponse?.();
|
||||
@@ -233,6 +252,7 @@ export async function holdRewindCompletion(
|
||||
return {
|
||||
clearTimelineStreamCount() {
|
||||
timelineStreamCount = 0;
|
||||
timelineFetchCount = 0;
|
||||
},
|
||||
release() {
|
||||
released = true;
|
||||
@@ -241,6 +261,7 @@ export async function holdRewindCompletion(
|
||||
}
|
||||
},
|
||||
timelineStreamCount: () => timelineStreamCount,
|
||||
timelineFetchCount: () => timelineFetchCount,
|
||||
waitForDelayedResponse: () => delayedResponse,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -12,6 +12,43 @@ const DISABLE_DEFAULT_SEED_ONCE_KEY = "@paseo:e2e-disable-default-seed-once";
|
||||
const SEED_NONCE_KEY = "@paseo:e2e-seed-nonce";
|
||||
const REGISTRY_KEY = "@paseo:daemon-registry";
|
||||
|
||||
export async function openSidebarHostPicker(page: Page) {
|
||||
await page.getByRole("button", { name: "Hosts", exact: true }).click();
|
||||
}
|
||||
|
||||
export function sidebarHostSettingsButton(page: Page) {
|
||||
return page.getByRole("button", { name: `Open ${TEST_HOST_LABEL} settings`, exact: true });
|
||||
}
|
||||
|
||||
export async function bindCommandCenterToEnter(page: Page) {
|
||||
await page.addInitScript(() => {
|
||||
localStorage.setItem(
|
||||
"@paseo:keyboard-shortcut-overrides",
|
||||
JSON.stringify({
|
||||
"command-center-toggle-cmd-k-mac": "Enter",
|
||||
"command-center-toggle-ctrl-k-non-mac": "Enter",
|
||||
}),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export async function expectStandaloneSidebarHostSettingsButton(page: Page) {
|
||||
const gear = sidebarHostSettingsButton(page);
|
||||
await expect(gear).toBeVisible();
|
||||
expect(await gear.evaluate((button) => button.parentElement?.closest("button") === null)).toBe(
|
||||
true,
|
||||
);
|
||||
}
|
||||
|
||||
export async function activateSidebarHostSettingsWithKeyboard(page: Page) {
|
||||
const host = page.getByRole("button", { name: TEST_HOST_LABEL, exact: true });
|
||||
await expect(host).toBeFocused();
|
||||
await page.keyboard.press("ArrowDown");
|
||||
await page.keyboard.press("Tab");
|
||||
await expect(sidebarHostSettingsButton(page)).toBeFocused();
|
||||
await page.keyboard.press("Enter");
|
||||
}
|
||||
|
||||
interface SavedSettingsHostInput {
|
||||
serverId: string;
|
||||
label: string;
|
||||
|
||||
@@ -19,6 +19,7 @@ android {
|
||||
|
||||
dependencies {
|
||||
implementation "androidx.customview:customview:1.1.0"
|
||||
implementation "com.facebook.react:react-android"
|
||||
testImplementation "junit:junit:4.13.2"
|
||||
androidTestImplementation "androidx.test:runner:1.6.2"
|
||||
androidTestImplementation "androidx.test.ext:junit:1.2.1"
|
||||
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package sh.paseo.terminal
|
||||
|
||||
import android.text.InputType
|
||||
import android.view.inputmethod.EditorInfo
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import com.facebook.react.bridge.BridgeReactContext
|
||||
import com.facebook.react.uimanager.DisplayMetricsHolder
|
||||
import com.facebook.react.uimanager.ThemedReactContext
|
||||
import com.facebook.react.views.textinput.ReactEditText
|
||||
import com.facebook.react.views.textinput.ReactTextInputManager
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotEquals
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
|
||||
/**
|
||||
* Builds React Native's own text input and applies `nativeID` through its view manager, which is
|
||||
* how Fabric mounts the hidden terminal input. The app runs bridgeless, so the context is too.
|
||||
*/
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class TerminalInputKeyboardTest {
|
||||
private val instrumentation = InstrumentationRegistry.getInstrumentation()
|
||||
|
||||
@Test fun terminalInputAsksTheKeyboardNotToLearnWhatIsTyped() {
|
||||
onInput("paseo-terminal-input") { input, editorInfo ->
|
||||
assertNotEquals(
|
||||
"The keyboard must not learn passwords typed at a terminal prompt",
|
||||
0,
|
||||
editorInfo.imeOptions and EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING,
|
||||
)
|
||||
assertEquals(
|
||||
"Suggestions stay off and the input stays multiline",
|
||||
InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS or InputType.TYPE_TEXT_FLAG_MULTI_LINE,
|
||||
editorInfo.inputType and (InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS or InputType.TYPE_TEXT_FLAG_MULTI_LINE),
|
||||
)
|
||||
val connection = checkNotNull(input.onCreateInputConnection(EditorInfo()))
|
||||
connection.setComposingText("su", 1)
|
||||
connection.commitText("sudo ls", 1)
|
||||
connection.deleteSurroundingText(1, 0)
|
||||
assertEquals("sudo l", input.text.toString())
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun otherInputsKeepPersonalizedLearning() {
|
||||
onInput("message-composer") { _, editorInfo ->
|
||||
assertEquals(0, editorInfo.imeOptions and EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING)
|
||||
}
|
||||
}
|
||||
|
||||
private fun onInput(nativeId: String, check: (ReactEditText, EditorInfo) -> Unit) {
|
||||
TerminalInputKeyboard.install()
|
||||
instrumentation.runOnMainSync {
|
||||
val app = instrumentation.targetContext
|
||||
DisplayMetricsHolder.initDisplayMetricsIfNotInitialized(app)
|
||||
val react = object : BridgeReactContext(app) {
|
||||
override fun isBridgeless() = true
|
||||
}
|
||||
val input = ReactEditText(ThemedReactContext(react, app, null, -1))
|
||||
input.inputType = InputType.TYPE_CLASS_TEXT or
|
||||
InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS or
|
||||
InputType.TYPE_TEXT_FLAG_MULTI_LINE
|
||||
ReactTextInputManager().setNativeId(input, nativeId)
|
||||
val editorInfo = EditorInfo()
|
||||
input.onCreateInputConnection(editorInfo)
|
||||
check(input, editorInfo)
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
@@ -7,6 +7,8 @@ class PaseoTerminalModule : Module() {
|
||||
override fun definition() = ModuleDefinition {
|
||||
Name("PaseoTerminal")
|
||||
|
||||
OnCreate { TerminalInputKeyboard.install() }
|
||||
|
||||
View(PaseoTerminalView::class) {
|
||||
Events("onCellMetrics")
|
||||
|
||||
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package sh.paseo.terminal
|
||||
|
||||
import android.view.View
|
||||
import android.view.inputmethod.EditorInfo
|
||||
import android.widget.TextView
|
||||
import com.facebook.react.bridge.UiThreadUtil
|
||||
import com.facebook.react.uimanager.util.ReactFindViewUtil
|
||||
|
||||
// Matched against the hidden terminal input's `nativeID`
|
||||
// (TERMINAL_INPUT_NATIVE_ID in terminal-input.native.tsx).
|
||||
private const val TERMINAL_INPUT_NATIVE_ID = "paseo-terminal-input"
|
||||
|
||||
/**
|
||||
* Keeps what is typed at a terminal prompt, such as a `sudo` password, out of the keyboard's
|
||||
* learned words. React Native's TextInput has no prop for IME_FLAG_NO_PERSONALIZED_LEARNING, so the
|
||||
* flag is added when the input receives its `nativeID`, before it can take focus.
|
||||
*
|
||||
* React Native replaces `imeOptions` when `returnKeyType` or `disableFullscreenUI` is set, so the
|
||||
* terminal input sets neither.
|
||||
*/
|
||||
internal object TerminalInputKeyboard : ReactFindViewUtil.OnMultipleViewsFoundListener {
|
||||
fun install() {
|
||||
UiThreadUtil.runOnUiThread {
|
||||
ReactFindViewUtil.addViewsListener(this, setOf(TERMINAL_INPUT_NATIVE_ID))
|
||||
}
|
||||
}
|
||||
|
||||
override fun onViewFound(view: View, nativeId: String) {
|
||||
val input = view as? TextView ?: return
|
||||
input.imeOptions = input.imeOptions or EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/app",
|
||||
"version": "0.17.3",
|
||||
"version": "0.17.4",
|
||||
"private": true,
|
||||
"main": "index.ts",
|
||||
"scripts": {
|
||||
@@ -40,7 +40,7 @@
|
||||
"dev:ios": "npm --prefix ../.. run build:client && cross-env APP_VARIANT=development expo run:ios",
|
||||
"build:apk": "npm --prefix ../.. run build:apk",
|
||||
"build:apk:arm64": "npm --prefix ../.. run build:apk:arm64",
|
||||
"test:android": "expo prebuild --platform android --no-install && cd android && ./gradlew :paseo-native-trace:testReleaseUnitTest :paseo-hardware-keyboard:testReleaseUnitTest :react-native-enriched-markdown:testReleaseUnitTest --tests '*InlineCodeFormattingTest' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
|
||||
"test:android": "expo prebuild --platform android --no-install && cd android && ./gradlew :paseo-native-trace:testReleaseUnitTest :paseo-hardware-keyboard:testReleaseUnitTest :react-native-enriched-markdown:testReleaseUnitTest --tests '*InlineCodeFormattingTest' --tests '*ListRenderingTest' --tests '*TaskListInteractionTest' --tests '*ListBlockquoteMeasurementTest' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
|
||||
},
|
||||
"dependencies": {
|
||||
"@codemirror/commands": "6.10.4",
|
||||
@@ -125,7 +125,7 @@
|
||||
"react-native": "0.86.3",
|
||||
"react-native-draggable-flatlist": "^4.0.3",
|
||||
"react-native-edge-to-edge": "^1.7.0",
|
||||
"react-native-enriched-markdown": "1.2.0-nightly-20261014-766fc0e67",
|
||||
"react-native-enriched-markdown": "*",
|
||||
"react-native-gesture-handler": "~2.32.0",
|
||||
"react-native-keyboard-controller": "1.21.12",
|
||||
"react-native-nitro-modules": "0.35.5",
|
||||
|
||||
@@ -56,6 +56,7 @@ export function ChatFind({
|
||||
agentId,
|
||||
serverId,
|
||||
epoch,
|
||||
rewindSeq,
|
||||
items,
|
||||
viewportRef,
|
||||
revealLoadedMessage,
|
||||
@@ -95,8 +96,8 @@ export function ChatFind({
|
||||
);
|
||||
const state = useSyncExternalStore(model.subscribe, model.getSnapshot, model.getSnapshot);
|
||||
useEffect(() => {
|
||||
model.updateHistory(epoch, items);
|
||||
}, [model, epoch, items]);
|
||||
model.updateHistory(epoch, items, rewindSeq);
|
||||
}, [model, epoch, items, rewindSeq]);
|
||||
useEffect(() => () => model.close(), [model]);
|
||||
useEffect(() => {
|
||||
if (!active) model.close();
|
||||
|
||||
@@ -18,7 +18,7 @@ function message(seq: number, text = "target"): StreamItem {
|
||||
kind: "assistant_message",
|
||||
text,
|
||||
timestamp: new Date(0),
|
||||
timelineCursor: { epoch: "epoch", seq },
|
||||
timelineCursor: { epoch: "epoch", seq, anchorSeq: seq },
|
||||
};
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ it("loads an older location and searches a response merged across suppressed tas
|
||||
source.map((item, index) => ({
|
||||
event: { type: "timeline" as const, provider: "claude" as const, item },
|
||||
timestamp: new Date(0),
|
||||
timelineCursor: { epoch: "epoch", seq: index + 1 },
|
||||
timelineCursor: { epoch: "epoch", seq: index + 1, anchorSeq: index + 1 },
|
||||
})),
|
||||
{ source: "canonical" },
|
||||
);
|
||||
@@ -55,7 +55,7 @@ it("loads an older location and searches a response merged across suppressed tas
|
||||
},
|
||||
async load(_epoch, seq) {
|
||||
loaded.push(seq);
|
||||
model.updateHistory("epoch", history);
|
||||
model.updateHistory("epoch", history, null);
|
||||
},
|
||||
async reveal(_id, _query, occurrence) {
|
||||
revealed.push(occurrence);
|
||||
@@ -64,7 +64,7 @@ it("loads an older location and searches a response merged across suppressed tas
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", []);
|
||||
model.updateHistory("epoch", [], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
@@ -99,7 +99,7 @@ it("skips a source-only candidate and highlights a displayed match", async () =>
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)]);
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().selectedItemId).toBe("row-2");
|
||||
@@ -129,7 +129,7 @@ it("ignores replies after closing and does not navigate", async () => {
|
||||
},
|
||||
clear() {},
|
||||
});
|
||||
model.updateHistory("epoch", [message(1)]);
|
||||
model.updateHistory("epoch", [message(1)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => calls).toEqual(["search"]);
|
||||
@@ -155,7 +155,7 @@ it("retains a failed search for retry and distinguishes failure from zero matche
|
||||
};
|
||||
const model = new ChatFindModel(operations);
|
||||
try {
|
||||
model.updateHistory("epoch", []);
|
||||
model.updateHistory("epoch", [], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("error");
|
||||
@@ -185,7 +185,7 @@ it("reports a failed timeline load as a connection failure", async () => {
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", []);
|
||||
model.updateHistory("epoch", [], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("error");
|
||||
@@ -207,24 +207,160 @@ it("reports a search result that outlived its epoch as a changed history", async
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1)]);
|
||||
model.updateHistory("epoch", [message(1)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
model.updateHistory("epoch-2", [message(1)]);
|
||||
model.updateHistory("epoch-2", [message(1)], null);
|
||||
expect(model.getSnapshot()).toMatchObject({ phase: "error", failure: "historyChanged" });
|
||||
} finally {
|
||||
model.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("reports results that a rewind took messages from as a changed history", async () => {
|
||||
const model = new ChatFindModel({
|
||||
async search() {
|
||||
return response([{ seq: 2, role: "assistant" }]);
|
||||
},
|
||||
async load() {},
|
||||
async reveal() {
|
||||
return { count: 1, occurrence: 0 };
|
||||
},
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
expect(model.getSnapshot()).toMatchObject({ selectedItemId: "row-2", count: 1 });
|
||||
// Another client rewinds the turn holding the match; the epoch stays.
|
||||
model.updateHistory("epoch", [message(1)], 3);
|
||||
expect(model.getSnapshot()).toMatchObject({
|
||||
phase: "error",
|
||||
failure: "historyChanged",
|
||||
selectedItemId: null,
|
||||
});
|
||||
} finally {
|
||||
model.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("stops a search still receiving pages when a rewind lands between them", async () => {
|
||||
let pages = 0;
|
||||
let releaseSecondPage!: () => void;
|
||||
const secondPage = new Promise<void>((resolve) => {
|
||||
releaseSecondPage = resolve;
|
||||
});
|
||||
const model = new ChatFindModel({
|
||||
async search(_query, cursor) {
|
||||
pages += 1;
|
||||
if (cursor === undefined)
|
||||
return { ...response([{ seq: 2, role: "assistant" }]), nextCursor: 2 };
|
||||
await secondPage;
|
||||
return response([{ seq: 1, role: "assistant" }]);
|
||||
},
|
||||
async load() {},
|
||||
async reveal() {
|
||||
return { count: 1, occurrence: 0 };
|
||||
},
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => pages).toBe(2);
|
||||
model.updateHistory("epoch", [message(1)], 3);
|
||||
releaseSecondPage();
|
||||
await expect.poll(() => model.getSnapshot().failure).toBe("historyChanged");
|
||||
expect(model.getSnapshot()).toMatchObject({ phase: "error", selectedItemId: null });
|
||||
} finally {
|
||||
model.close();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
["Next", "next"],
|
||||
["Previous", "previous"],
|
||||
] as const)("reports a rewind after %s as a changed history", async (_label, step) => {
|
||||
const model = new ChatFindModel({
|
||||
async search() {
|
||||
return response([
|
||||
{ seq: 1, role: "assistant" },
|
||||
{ seq: 2, role: "assistant" },
|
||||
]);
|
||||
},
|
||||
async load() {},
|
||||
async reveal() {
|
||||
return { count: 1, occurrence: 0 };
|
||||
},
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
model[step]();
|
||||
await expect.poll(() => model.getSnapshot().selectedItemId).toBe("row-2");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
model.updateHistory("epoch", [message(1)], 3);
|
||||
expect(model.getSnapshot()).toMatchObject({
|
||||
phase: "error",
|
||||
failure: "historyChanged",
|
||||
selectedItemId: null,
|
||||
});
|
||||
} finally {
|
||||
model.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("stops a pending Next when a rewind lands before it reveals", async () => {
|
||||
let reveals = 0;
|
||||
let revealSecond!: () => void;
|
||||
const secondReveal = new Promise<void>((resolve) => {
|
||||
revealSecond = resolve;
|
||||
});
|
||||
const model = new ChatFindModel({
|
||||
async search() {
|
||||
return response([
|
||||
{ seq: 1, role: "assistant" },
|
||||
{ seq: 2, role: "assistant" },
|
||||
]);
|
||||
},
|
||||
async load() {},
|
||||
async reveal() {
|
||||
reveals += 1;
|
||||
if (reveals > 1) await secondReveal;
|
||||
return { count: 1, occurrence: 0 };
|
||||
},
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
model.next();
|
||||
await expect.poll(() => reveals).toBe(2);
|
||||
model.updateHistory("epoch", [message(1)], 3);
|
||||
revealSecond();
|
||||
await expect.poll(() => model.getSnapshot().failure).toBe("historyChanged");
|
||||
expect(model.getSnapshot()).toMatchObject({ phase: "error", selectedItemId: null });
|
||||
} finally {
|
||||
model.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("can load a search location before the initial chat history has arrived", async () => {
|
||||
const model = new ChatFindModel({
|
||||
async search() {
|
||||
return response([{ seq: 1, role: "assistant" }]);
|
||||
},
|
||||
async load() {
|
||||
model.updateHistory("epoch", [message(1)]);
|
||||
model.updateHistory("epoch", [message(1)], null);
|
||||
},
|
||||
async reveal() {
|
||||
return { count: 1, occurrence: 0 };
|
||||
@@ -232,7 +368,7 @@ it("can load a search location before the initial chat history has arrived", asy
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory(null, []);
|
||||
model.updateHistory(null, [], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
@@ -260,7 +396,7 @@ it("reports the position across the whole chat and corrects it with rendered cou
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)]);
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
@@ -297,7 +433,7 @@ it("counts one match per message from a host that reports no counts", async () =
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)]);
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
|
||||
@@ -76,6 +76,10 @@ export class ChatFindModel {
|
||||
private items: StreamItem[] = [];
|
||||
private epoch: string | null = null;
|
||||
private resultEpoch: string | null = null;
|
||||
/** The latest rewind applied to the history. A rewind keeps the epoch and retires messages. */
|
||||
private rewindSeq: number | null = null;
|
||||
/** The latest rewind when the current result set's search started; undefined until a search starts. */
|
||||
private searchedRewindSeq: number | null | undefined = undefined;
|
||||
private locations: Location[] = [];
|
||||
private resolved = new Map<Location, Target>();
|
||||
private current = -1;
|
||||
@@ -113,6 +117,7 @@ export class ChatFindModel {
|
||||
this.cancel();
|
||||
this.locations = [];
|
||||
this.resultEpoch = null;
|
||||
this.searchedRewindSeq = undefined;
|
||||
this.resolved.clear();
|
||||
this.current = -1;
|
||||
this.inMessage = { occurrence: 0, count: 0 };
|
||||
@@ -144,6 +149,7 @@ export class ChatFindModel {
|
||||
});
|
||||
}
|
||||
private async search(signal: AbortSignal) {
|
||||
this.searchedRewindSeq = this.rewindSeq;
|
||||
try {
|
||||
let cursor: number | undefined;
|
||||
do {
|
||||
@@ -168,15 +174,14 @@ export class ChatFindModel {
|
||||
this.fail(error, signal);
|
||||
}
|
||||
}
|
||||
updateHistory(epoch: string | null, items: StreamItem[]) {
|
||||
if (
|
||||
this.resultEpoch !== null &&
|
||||
epoch !== null &&
|
||||
epoch !== this.resultEpoch &&
|
||||
this.state.open
|
||||
) {
|
||||
/** `rewindSeq` is the sequence number of the latest rewind applied to this history. */
|
||||
updateHistory(epoch: string | null, items: StreamItem[], rewindSeq: number | null) {
|
||||
const replaced = this.resultEpoch !== null && epoch !== null && epoch !== this.resultEpoch;
|
||||
const rewound = this.searchedRewindSeq !== undefined && rewindSeq !== this.searchedRewindSeq;
|
||||
if ((replaced || rewound) && this.state.open) {
|
||||
this.fail(new ChatFindFailureError("historyChanged"), this.abort.signal);
|
||||
}
|
||||
this.rewindSeq = rewindSeq;
|
||||
this.epoch = epoch;
|
||||
this.items = items;
|
||||
this.historyListeners.forEach((listener) => listener());
|
||||
|
||||
@@ -9,6 +9,8 @@ export interface ChatFindProps {
|
||||
agentId: string;
|
||||
serverId: string;
|
||||
epoch: string | null;
|
||||
/** The sequence number of the latest rewind applied to this history, if any. */
|
||||
rewindSeq: number | null;
|
||||
items: StreamItem[];
|
||||
viewportRef: RefObject<StreamViewportHandle | null>;
|
||||
revealLoadedMessage(messageId: string): boolean;
|
||||
|
||||
@@ -139,7 +139,7 @@ describe("useChatOutline", () => {
|
||||
kind: "user_message",
|
||||
text: "live prompt",
|
||||
timestamp: new Date(seq),
|
||||
timelineCursor: { epoch: "epoch-1", seq },
|
||||
timelineCursor: { epoch: "epoch-1", seq, anchorSeq: seq },
|
||||
});
|
||||
rerender({ tail: [loadedPrompt(2)] });
|
||||
await waitFor(() => expect(runtime.listAgentTimelinePrompts).toHaveBeenCalledTimes(2));
|
||||
@@ -198,7 +198,7 @@ describe("useChatOutline", () => {
|
||||
kind: "assistant_message",
|
||||
text: "chunk",
|
||||
timestamp: new Date(),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
|
||||
},
|
||||
],
|
||||
timelineEpoch: "epoch-1",
|
||||
@@ -219,7 +219,7 @@ describe("useChatOutline", () => {
|
||||
kind: "user_message",
|
||||
text: "Replaced conversation",
|
||||
timestamp: new Date(2),
|
||||
timelineCursor: { epoch: "epoch-2", seq: 1 },
|
||||
timelineCursor: { epoch: "epoch-2", seq: 1, anchorSeq: 1 },
|
||||
},
|
||||
],
|
||||
timelineEpoch: "epoch-2",
|
||||
@@ -275,7 +275,7 @@ describe("useChatOutline", () => {
|
||||
kind: "user_message" as const,
|
||||
text: "prompt",
|
||||
timestamp: new Date(1),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
|
||||
},
|
||||
];
|
||||
const { result, rerender } = renderHook(
|
||||
@@ -326,7 +326,7 @@ describe("useChatOutline", () => {
|
||||
kind: "user_message" as const,
|
||||
text: "prompt",
|
||||
timestamp: new Date(1),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
|
||||
};
|
||||
const { result, rerender } = renderHook(
|
||||
({ tail, mountedHistoryMessageIds }) =>
|
||||
@@ -381,7 +381,7 @@ describe("useChatOutline", () => {
|
||||
kind: "user_message" as const,
|
||||
text: "prompt",
|
||||
timestamp: new Date(2),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
|
||||
};
|
||||
const revealLoadedMessage = vi.fn();
|
||||
revealLoadedMessage.mockReturnValue(false);
|
||||
|
||||
@@ -320,7 +320,7 @@ describe("stream presentation through installed plugins", () => {
|
||||
const source = harness.source();
|
||||
const live = source.head[0];
|
||||
if (live?.kind !== "assistant_message") throw new Error("Expected a live assistant message");
|
||||
const canonical = { ...live, timelineCursor: { epoch: "epoch-1", seq: 42 } };
|
||||
const canonical = { ...live, timelineCursor: { epoch: "epoch-1", seq: 42, anchorSeq: 42 } };
|
||||
const present = createStreamPresentation();
|
||||
present({ ...presentationOptions, tail: [], head: [live], transform: undefined });
|
||||
const repointed = rows(
|
||||
@@ -330,7 +330,7 @@ describe("stream presentation through installed plugins", () => {
|
||||
{
|
||||
id: streamed[0]!.id,
|
||||
text: "Streamed answer",
|
||||
timelineCursor: { epoch: "epoch-1", seq: 42 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 42, anchorSeq: 42 },
|
||||
},
|
||||
]);
|
||||
});
|
||||
@@ -517,7 +517,7 @@ describe("timeline presentation", () => {
|
||||
messageId: "provider-message",
|
||||
clientMessageId: "client-message",
|
||||
turnId: "turn-1",
|
||||
timelineCursor: { epoch: "epoch", seq: 12 },
|
||||
timelineCursor: { epoch: "epoch", seq: 12, anchorSeq: 12 },
|
||||
});
|
||||
const presentMessage = () =>
|
||||
present({
|
||||
|
||||
@@ -33,7 +33,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
|
||||
it("forks a failed assistant turn from its Paseo timeline cursor without a provider message id", () => {
|
||||
const failedTurn = {
|
||||
...assistantMessage("assistant-error", 2),
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42 },
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
|
||||
};
|
||||
|
||||
expect(
|
||||
@@ -50,7 +50,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
|
||||
it("includes the provider message id with a supported timeline cursor", () => {
|
||||
const selected = {
|
||||
...assistantMessage("assistant-1", 2, "msg-assistant-1"),
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42 },
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
|
||||
};
|
||||
|
||||
expect(
|
||||
@@ -68,7 +68,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
|
||||
it("falls back to the provider message id when timeline cursors are unsupported", () => {
|
||||
const selected = {
|
||||
...assistantMessage("assistant-1", 2, "msg-assistant-1"),
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42 },
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
|
||||
};
|
||||
|
||||
expect(
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
import type { StreamItem, TimelinePosition } from "@/types/stream";
|
||||
import type { StreamItem } from "@/types/stream";
|
||||
|
||||
/** The daemon's timeline cursor; the row's anchor stays in the client. */
|
||||
interface TimelineBoundaryCursor {
|
||||
epoch: string;
|
||||
seq: number;
|
||||
}
|
||||
|
||||
export type AssistantTurnForkBoundary =
|
||||
| { boundaryCursor: TimelinePosition; boundaryMessageId?: string }
|
||||
| { boundaryCursor: TimelineBoundaryCursor; boundaryMessageId?: string }
|
||||
| { boundaryCursor?: undefined; boundaryMessageId: string };
|
||||
|
||||
export function resolveAssistantTurnForkBoundary(input: {
|
||||
@@ -15,7 +21,7 @@ export function resolveAssistantTurnForkBoundary(input: {
|
||||
}
|
||||
if (input.supportsTimelineCursor && item.timelineCursor) {
|
||||
return {
|
||||
boundaryCursor: item.timelineCursor,
|
||||
boundaryCursor: { epoch: item.timelineCursor.epoch, seq: item.timelineCursor.seq },
|
||||
...(item.messageId ? { boundaryMessageId: item.messageId } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -140,7 +140,7 @@ describe("collapseTurns", () => {
|
||||
it("stands at its host's timeline position, taking a new row when that position lands", () => {
|
||||
const live = collapse([user("u1"), shell("c1"), reply("r1")]);
|
||||
expect(live.summaryRowsByHostId.get("u1")).not.toHaveProperty("timelineCursor");
|
||||
const cursor = { epoch: "epoch-1", seq: 7 };
|
||||
const cursor = { epoch: "epoch-1", seq: 7, anchorSeq: 7 };
|
||||
const placed = [{ ...user("u1"), timelineCursor: cursor }, shell("c1"), reply("r1")];
|
||||
const canonical = collapse(placed, { previousSummaryRowsByHostId: live.summaryRowsByHostId });
|
||||
expect(canonical.summaryRowsByHostId.get("u1")).not.toBe(live.summaryRowsByHostId.get("u1"));
|
||||
|
||||
@@ -408,6 +408,10 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
const timelineEpoch = useSessionStore(
|
||||
(state) => state.sessions[resolvedServerId]?.agentTimelineCursor.get(agentId)?.epoch ?? null,
|
||||
);
|
||||
const timelineRewindSeq = useSessionStore((state) => {
|
||||
const rewind = state.sessions[resolvedServerId]?.agentTimelineLatestRewind.get(agentId);
|
||||
return rewind && rewind.epoch === timelineEpoch ? rewind.seq : null;
|
||||
});
|
||||
const isTimelineDetached = useSessionStore(
|
||||
(state) => state.sessions[resolvedServerId]?.agentTimelineHasNewer.get(agentId) === true,
|
||||
);
|
||||
@@ -1166,6 +1170,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
agentId={agentId}
|
||||
serverId={resolvedServerId}
|
||||
epoch={timelineEpoch}
|
||||
rewindSeq={timelineRewindSeq}
|
||||
items={findItems}
|
||||
viewportRef={viewportRef}
|
||||
revealLoadedMessage={revealLoadedMessage}
|
||||
|
||||
@@ -7,6 +7,7 @@ import { FOOTER_HEIGHT } from "@/constants/layout";
|
||||
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
|
||||
import { KeyboardTranslateView } from "@/keyboard/shift";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useToast } from "@/contexts/toast-context";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import { toErrorMessage } from "@/utils/error-messages";
|
||||
|
||||
@@ -19,6 +20,7 @@ export function ArchivedAgentCallout({ serverId, agentId }: ArchivedAgentCallout
|
||||
const { t } = useTranslation();
|
||||
const client = useHostRuntimeClient(serverId);
|
||||
const isConnected = useHostRuntimeIsConnected(serverId);
|
||||
const toast = useToast();
|
||||
const [isUnarchiving, setIsUnarchiving] = useState(false);
|
||||
const [unarchiveError, setUnarchiveError] = useState<string | null>(null);
|
||||
|
||||
@@ -27,12 +29,15 @@ export function ArchivedAgentCallout({ serverId, agentId }: ArchivedAgentCallout
|
||||
setIsUnarchiving(true);
|
||||
setUnarchiveError(null);
|
||||
try {
|
||||
await client.refreshAgent(agentId);
|
||||
const refreshed = await client.refreshAgent(agentId);
|
||||
if (refreshed.historyDiverged) {
|
||||
toast.show(t("workspace.tabs.toasts.reloadedAgentHistoryDiverged"), { variant: "warning" });
|
||||
}
|
||||
} catch (error) {
|
||||
setUnarchiveError(toErrorMessage(error));
|
||||
setIsUnarchiving(false);
|
||||
}
|
||||
}, [client, isConnected, isUnarchiving, agentId]);
|
||||
}, [client, isConnected, isUnarchiving, agentId, toast, t]);
|
||||
|
||||
return (
|
||||
<KeyboardTranslateView style={styles.container}>
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { useCallback, useMemo, type ReactElement, type ReactNode } from "react";
|
||||
import { Pressable, View } from "react-native";
|
||||
import type { GestureResponderEvent } from "react-native";
|
||||
import { Plus, Server, Settings } from "lucide-react-native";
|
||||
import { StyleSheet, useUnistyles } from "react-native-unistyles";
|
||||
import { HostStatusDot } from "@/components/host-status-dot";
|
||||
@@ -80,19 +79,15 @@ export function HostPickerOption({
|
||||
? formatActiveConnectionLabel(activeConnection)
|
||||
: undefined;
|
||||
const leadingSlot = useMemo(() => <HostStatusDotSlot serverId={serverId} />, [serverId]);
|
||||
const handleSettingsPress = useCallback(
|
||||
(event: GestureResponderEvent) => {
|
||||
event.stopPropagation();
|
||||
onOpenHostSettings?.(serverId);
|
||||
},
|
||||
[onOpenHostSettings, serverId],
|
||||
);
|
||||
const trailingSlot = useMemo(() => {
|
||||
const handleSettingsPress = useCallback(() => {
|
||||
onOpenHostSettings?.(serverId);
|
||||
}, [onOpenHostSettings, serverId]);
|
||||
const trailingAction = useMemo(() => {
|
||||
if (!onOpenHostSettings) return undefined;
|
||||
return (
|
||||
<Pressable
|
||||
onPress={handleSettingsPress}
|
||||
hitSlop={8}
|
||||
style={styles.settingsAction}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={`Open ${label} settings`}
|
||||
>
|
||||
@@ -112,7 +107,7 @@ export function HostPickerOption({
|
||||
label={label}
|
||||
description={connectionLabel}
|
||||
leadingSlot={leadingSlot}
|
||||
trailingSlot={trailingSlot}
|
||||
trailingAction={trailingAction}
|
||||
selected={selected}
|
||||
active={active}
|
||||
onPress={onPress}
|
||||
@@ -319,6 +314,12 @@ export function HostPicker({
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
settingsAction: {
|
||||
flex: 1,
|
||||
justifyContent: "center",
|
||||
paddingLeft: theme.spacing[1],
|
||||
paddingRight: theme.spacing[3],
|
||||
},
|
||||
statusDotSlot: {
|
||||
width: theme.iconSize.sm,
|
||||
height: theme.iconSize.sm,
|
||||
|
||||
@@ -9,6 +9,7 @@ import { useRewindComposerRestore } from "./composer-restore";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { shouldRestoreComposerForRewindMode } from "./rewind-mode";
|
||||
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
||||
import { hostSupportsFeature } from "@/runtime/host-features";
|
||||
|
||||
interface UseRewindAgentMutationInput {
|
||||
serverId?: string;
|
||||
@@ -42,7 +43,16 @@ export function useRewindAgentMutation(input: UseRewindAgentMutationInput): {
|
||||
throw new Error(t("common.errors.daemonClientUnavailable"));
|
||||
}
|
||||
await input.client.rewindAgent(input.agentId, input.messageId, mode);
|
||||
if (mode !== "files") {
|
||||
// COMPAT(timelineRewindOperations): added in v0.14.1, remove after 2027-05-10. A daemon with
|
||||
// the feature delivers the rewind on the live timeline; an older one replaced the timeline
|
||||
// and this client has to read it again.
|
||||
const appliesLive =
|
||||
input.serverId !== undefined &&
|
||||
hostSupportsFeature(
|
||||
useSessionStore.getState().sessions[input.serverId]?.serverInfo,
|
||||
"timelineRewindOperations",
|
||||
);
|
||||
if (mode !== "files" && !appliesLive) {
|
||||
const cursor = input.serverId
|
||||
? useSessionStore
|
||||
.getState()
|
||||
|
||||
@@ -72,6 +72,7 @@ import { buildDesktopFrameStyle } from "./combobox-frame-style";
|
||||
export { buildDesktopFrameStyle } from "./combobox-frame-style";
|
||||
|
||||
const IS_WEB = isWeb;
|
||||
const TRAILING_ACTION_DATASET = { comboboxTrailingAction: true };
|
||||
|
||||
export type ComboboxOption = ComboboxOptionModel;
|
||||
export type ComboboxDesktopPlacement = "top-start" | "bottom-start";
|
||||
@@ -235,6 +236,11 @@ export interface ComboboxItemProps {
|
||||
kind?: "directory" | "file";
|
||||
leadingSlot?: ReactNode;
|
||||
trailingSlot?: ReactNode;
|
||||
/**
|
||||
* A button shown outside the row's own pressable. The button owns its spacing
|
||||
* and hit area.
|
||||
*/
|
||||
trailingAction?: ReactNode;
|
||||
selected?: boolean;
|
||||
active?: boolean;
|
||||
disabled?: boolean;
|
||||
@@ -252,6 +258,7 @@ export function ComboboxItem({
|
||||
kind,
|
||||
leadingSlot,
|
||||
trailingSlot,
|
||||
trailingAction,
|
||||
selected,
|
||||
active,
|
||||
disabled,
|
||||
@@ -300,15 +307,29 @@ export function ComboboxItem({
|
||||
[labelPrefix],
|
||||
);
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
testID={testID}
|
||||
disabled={disabled}
|
||||
onPress={onPress}
|
||||
style={itemPressableStyle}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={accessibilityLabel ?? label}
|
||||
>
|
||||
const [hovered, setHovered] = useState(false);
|
||||
const handleHoverIn = useCallback(() => setHovered(true), []);
|
||||
const handleHoverOut = useCallback(() => setHovered(false), []);
|
||||
const splitPressableStyle = useCallback(
|
||||
({ pressed }: PressableStateCallbackType) => [
|
||||
styles.comboboxItemSplitPressable,
|
||||
pressed && (elevated ? styles.comboboxItemPressedElevated : styles.comboboxItemPressed),
|
||||
],
|
||||
[elevated],
|
||||
);
|
||||
const splitRowStyle = useMemo(
|
||||
() => [
|
||||
styles.comboboxItem,
|
||||
styles.comboboxItemSplitRow,
|
||||
hovered && (elevated ? styles.comboboxItemHoveredElevated : styles.comboboxItemHovered),
|
||||
active && styles.comboboxItemActive,
|
||||
disabled && styles.comboboxItemDisabled,
|
||||
],
|
||||
[active, disabled, elevated, hovered],
|
||||
);
|
||||
|
||||
const content = (
|
||||
<>
|
||||
{leadingContent}
|
||||
<View style={itemContentStyle}>
|
||||
{labelPrefix ? (
|
||||
@@ -333,7 +354,40 @@ export function ComboboxItem({
|
||||
{trailingSlot}
|
||||
</View>
|
||||
) : null}
|
||||
</Pressable>
|
||||
</>
|
||||
);
|
||||
|
||||
if (!trailingAction) {
|
||||
return (
|
||||
<Pressable
|
||||
testID={testID}
|
||||
disabled={disabled}
|
||||
onPress={onPress}
|
||||
style={itemPressableStyle}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={accessibilityLabel ?? label}
|
||||
>
|
||||
{content}
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={splitRowStyle} onPointerEnter={handleHoverIn} onPointerLeave={handleHoverOut}>
|
||||
<Pressable
|
||||
testID={testID}
|
||||
disabled={disabled}
|
||||
onPress={onPress}
|
||||
style={splitPressableStyle}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={accessibilityLabel ?? label}
|
||||
>
|
||||
{content}
|
||||
</Pressable>
|
||||
<View style={styles.comboboxItemActionSlot} dataSet={TRAILING_ACTION_DATASET}>
|
||||
{trailingAction}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -898,6 +952,10 @@ function dispatchDesktopKey(
|
||||
return true;
|
||||
}
|
||||
if (key === "Enter") {
|
||||
// Consume the shortcut but keep the browser's default button activation.
|
||||
if (isWeb && document.activeElement?.matches("[data-combobox-trailing-action] button")) {
|
||||
return true;
|
||||
}
|
||||
if (input.orderedVisibleOptions.length === 0) return false;
|
||||
event?.preventDefault();
|
||||
handleDesktopEnterKey(input);
|
||||
@@ -1742,6 +1800,26 @@ const styles = StyleSheet.create((theme) => ({
|
||||
marginBottom: theme.spacing[1],
|
||||
}),
|
||||
},
|
||||
// Share the highlight while each control owns its padding and hit area.
|
||||
comboboxItemSplitRow: {
|
||||
gap: 0,
|
||||
paddingHorizontal: 0,
|
||||
paddingVertical: 0,
|
||||
},
|
||||
comboboxItemSplitPressable: {
|
||||
flex: 1,
|
||||
alignSelf: "stretch",
|
||||
minWidth: 0,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
paddingLeft: theme.spacing[3],
|
||||
paddingRight: theme.spacing[1],
|
||||
paddingVertical: theme.spacing[2],
|
||||
},
|
||||
comboboxItemActionSlot: {
|
||||
alignSelf: "stretch",
|
||||
},
|
||||
comboboxItemHovered: {
|
||||
backgroundColor: theme.colors.surface1,
|
||||
},
|
||||
|
||||
@@ -385,6 +385,16 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
|
||||
console.warn("[Session] timeline replacement refresh failed", { serverId, error });
|
||||
});
|
||||
};
|
||||
const onRewind = (message: SessionOutboundMessage) => {
|
||||
if (message.type !== "agent.timeline.rewind") return;
|
||||
const { agentId, epoch, seq, retireFromSeq } = message.payload;
|
||||
sync.applyStreamEvent(agentId, {
|
||||
event: { type: "rewind", retireFromSeq },
|
||||
seq,
|
||||
epoch,
|
||||
timestamp: new Date(),
|
||||
});
|
||||
};
|
||||
const sync = getHostRuntimeStore().createViewedTimelineOwner(serverId, {
|
||||
canCheckFreshness: () =>
|
||||
client.getLastServerInfoMessage()?.features?.timelineFreshnessCheck === true,
|
||||
@@ -395,6 +405,7 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
|
||||
update: (message) => {
|
||||
if (message.type === "agent_stream") onStream(message);
|
||||
else if (message.type === "agent.timeline.replacement") onReplacement(message);
|
||||
else if (message.type === "agent.timeline.rewind") onRewind(message);
|
||||
},
|
||||
});
|
||||
return observation;
|
||||
|
||||
@@ -244,6 +244,7 @@ const CATALOG_DATA = [
|
||||
},
|
||||
{
|
||||
id: "hermes",
|
||||
bundledProvider: { hostFeature: "hermesProvider" },
|
||||
title: "Hermes",
|
||||
description: "Nous Research self-improving AI agent",
|
||||
version: "manual",
|
||||
|
||||
@@ -7,6 +7,8 @@ import {
|
||||
buildGitActions,
|
||||
isCurrentBranchBase,
|
||||
canMergeIntoLocalBase,
|
||||
readSyncRemotes,
|
||||
readUpstreamState,
|
||||
type BuildGitActionsInput,
|
||||
} from "./policy";
|
||||
import { deriveMergeCapability, type ForgeSpecificStatusFacts } from "./merge-capability";
|
||||
@@ -59,9 +61,11 @@ function githubStatus(overrides: Partial<GithubMergeFactsFixture> = {}): GithubM
|
||||
function createInput(
|
||||
overrides: Partial<Omit<BuildGitActionsInput, "mergeCapability">> & {
|
||||
pullRequestGithub?: unknown;
|
||||
// Shorthand for a branch that both Pull and Push have a remote for.
|
||||
hasRemote?: boolean;
|
||||
} = {},
|
||||
): BuildGitActionsInput {
|
||||
const { pullRequestGithub = null, ...rest } = overrides;
|
||||
const { pullRequestGithub = null, hasRemote = false, ...rest } = overrides;
|
||||
return {
|
||||
isGit: true,
|
||||
githubFeaturesEnabled: true,
|
||||
@@ -75,7 +79,9 @@ function createInput(
|
||||
pullRequestIsMerged: false,
|
||||
pullRequestMergeable: "UNKNOWN",
|
||||
mergeCapability: deriveMergeCapability(pullRequestGithub),
|
||||
hasRemote: false,
|
||||
hasPullRemote: hasRemote,
|
||||
hasPushRemote: hasRemote,
|
||||
upstream: "tracked",
|
||||
isPaseoOwnedWorktree: false,
|
||||
isOnBaseBranch: true,
|
||||
canMergeLocally: true,
|
||||
@@ -169,6 +175,14 @@ function createInput(
|
||||
};
|
||||
}
|
||||
|
||||
function pushActionOf(actions: ReturnType<typeof buildGitActions>) {
|
||||
return actions.secondary.find((action) => action.id === "push");
|
||||
}
|
||||
|
||||
function pullAndPushActionOf(actions: ReturnType<typeof buildGitActions>) {
|
||||
return actions.secondary.find((action) => action.id === "pull-and-push");
|
||||
}
|
||||
|
||||
describe("git-actions-policy", () => {
|
||||
afterEach(async () => {
|
||||
await i18n.changeLanguage("en");
|
||||
@@ -346,6 +360,7 @@ describe("git-actions-policy", () => {
|
||||
const actions = buildGitActions(
|
||||
createInput({
|
||||
hasRemote: true,
|
||||
upstream: "none",
|
||||
isPaseoOwnedWorktree: true,
|
||||
isOnBaseBranch: false,
|
||||
aheadCount: 1,
|
||||
@@ -361,6 +376,336 @@ describe("git-actions-policy", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("re-publishes a Paseo worktree branch whose remote copy was deleted", () => {
|
||||
const actions = buildGitActions(
|
||||
createInput({
|
||||
hasRemote: true,
|
||||
upstream: "gone",
|
||||
isPaseoOwnedWorktree: true,
|
||||
isOnBaseBranch: false,
|
||||
aheadCount: 2,
|
||||
aheadOfOrigin: null,
|
||||
behindOfOrigin: null,
|
||||
shipDefault: "pr",
|
||||
}),
|
||||
);
|
||||
const pushAction = actions.secondary.find((action) => action.id === "push");
|
||||
|
||||
expect(actions.primary).toMatchObject({ id: "push", label: "Push" });
|
||||
expect(pushAction).toMatchObject({ disabled: false, unavailableMessage: undefined });
|
||||
});
|
||||
|
||||
describe("a never-pushed branch in a regular checkout", () => {
|
||||
const neverPushed = {
|
||||
hasRemote: true,
|
||||
upstream: "none",
|
||||
isOnBaseBranch: false,
|
||||
aheadCount: 1,
|
||||
aheadOfOrigin: null,
|
||||
behindOfOrigin: null,
|
||||
} as const;
|
||||
|
||||
it("offers Push first, ahead of Create PR", () => {
|
||||
const actions = buildGitActions(createInput({ ...neverPushed, shipDefault: "pr" }));
|
||||
|
||||
expect(actions.primary).toMatchObject({ id: "push", label: "Push" });
|
||||
});
|
||||
|
||||
it("offers Push first, ahead of Merge locally", () => {
|
||||
const actions = buildGitActions(
|
||||
createInput({ ...neverPushed, githubFeaturesEnabled: false, shipDefault: "merge" }),
|
||||
);
|
||||
|
||||
expect(actions.primary).toMatchObject({ id: "push", label: "Push" });
|
||||
});
|
||||
|
||||
it("does not offer Push when it has no commits of its own", () => {
|
||||
const actions = buildGitActions(createInput({ ...neverPushed, aheadCount: 0 }));
|
||||
const pushAction = pushActionOf(actions);
|
||||
|
||||
expect(actions.primary?.id).not.toBe("push");
|
||||
expect(pushAction?.unavailableMessage).toBe(
|
||||
"Push isn't available because there is nothing new to send",
|
||||
);
|
||||
});
|
||||
|
||||
it("does not offer Push when the repository has no origin", () => {
|
||||
const actions = buildGitActions(createInput({ ...neverPushed, hasRemote: false }));
|
||||
const pushAction = pushActionOf(actions);
|
||||
|
||||
expect(actions.primary?.id).not.toBe("push");
|
||||
expect(pushAction?.unavailableMessage).toBe(
|
||||
"Push isn't available here because this branch is not connected to a remote yet",
|
||||
);
|
||||
});
|
||||
|
||||
it("does not offer Push when Git pushes the branch to another remote", () => {
|
||||
const actions = buildGitActions(createInput({ ...neverPushed, hasPushRemote: false }));
|
||||
const pushAction = pushActionOf(actions);
|
||||
|
||||
expect(actions.primary?.id).not.toBe("push");
|
||||
expect(pushAction?.unavailableMessage).toBe(
|
||||
"Push isn't available here because this branch is not connected to a remote yet",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// The daemon reports where Pull and Push go for the branch, so the remote's name never matters.
|
||||
describe("a branch that tracks a remote other than origin", () => {
|
||||
const tracksDorasMono = readSyncRemotes({
|
||||
hasRemote: false,
|
||||
pullRemote: "doras-mono",
|
||||
pushRemote: "doras-mono",
|
||||
upstreamState: "tracked",
|
||||
aheadOfOrigin: 1,
|
||||
isPaseoOwnedWorktree: false,
|
||||
});
|
||||
|
||||
it("offers Push when the branch is ahead", () => {
|
||||
const actions = buildGitActions(
|
||||
createInput({ ...tracksDorasMono, aheadOfOrigin: 1, behindOfOrigin: 0 }),
|
||||
);
|
||||
|
||||
expect(actions.primary).toMatchObject({ id: "push", label: "Push" });
|
||||
expect(pushActionOf(actions)).toMatchObject({
|
||||
disabled: false,
|
||||
unavailableMessage: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
it("offers Pull when the branch is behind", () => {
|
||||
const actions = buildGitActions(
|
||||
createInput({ ...tracksDorasMono, aheadOfOrigin: 0, behindOfOrigin: 2 }),
|
||||
);
|
||||
|
||||
expect(actions.primary).toMatchObject({ id: "pull", label: "Pull" });
|
||||
});
|
||||
|
||||
it("offers Pull first and Pull and push when the branch is ahead and behind", () => {
|
||||
const actions = buildGitActions(
|
||||
createInput({ ...tracksDorasMono, aheadOfOrigin: 1, behindOfOrigin: 2 }),
|
||||
);
|
||||
|
||||
expect(actions.primary).toMatchObject({ id: "pull", label: "Pull" });
|
||||
expect(pullAndPushActionOf(actions)).toMatchObject({
|
||||
disabled: false,
|
||||
unavailableMessage: undefined,
|
||||
});
|
||||
expect(pushActionOf(actions)?.unavailableMessage).toBe(
|
||||
"Push isn't available yet because there are newer changes to bring in first",
|
||||
);
|
||||
});
|
||||
|
||||
// `feature` tracking `upstream/main`: the daemon reports a pull remote and no push remote.
|
||||
const pullOnly = readSyncRemotes({
|
||||
hasRemote: false,
|
||||
pullRemote: "upstream",
|
||||
pushRemote: null,
|
||||
upstreamState: "tracked",
|
||||
aheadOfOrigin: 1,
|
||||
isPaseoOwnedWorktree: false,
|
||||
});
|
||||
|
||||
it("does not offer Push when it would land on a differently named upstream branch", () => {
|
||||
const actions = buildGitActions(
|
||||
createInput({ ...pullOnly, aheadOfOrigin: 1, behindOfOrigin: 0 }),
|
||||
);
|
||||
|
||||
expect(actions.primary?.id).not.toBe("push");
|
||||
expect(pushActionOf(actions)?.unavailableMessage).toBe(
|
||||
"Push isn't available here because this branch is not connected to a remote yet",
|
||||
);
|
||||
});
|
||||
|
||||
it("still offers Pull for that branch, and not Pull and push", () => {
|
||||
const actions = buildGitActions(
|
||||
createInput({ ...pullOnly, aheadOfOrigin: 1, behindOfOrigin: 2 }),
|
||||
);
|
||||
|
||||
expect(actions.primary).toMatchObject({ id: "pull", label: "Pull" });
|
||||
expect(pullAndPushActionOf(actions)?.unavailableMessage).toBe(
|
||||
"Pull and push isn't available here because this branch is not connected to a remote yet",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("readSyncRemotes", () => {
|
||||
it("uses the remotes the daemon reports", () => {
|
||||
expect(
|
||||
readSyncRemotes({
|
||||
hasRemote: true,
|
||||
pullRemote: null,
|
||||
pushRemote: "origin",
|
||||
upstreamState: "none",
|
||||
aheadOfOrigin: null,
|
||||
isPaseoOwnedWorktree: false,
|
||||
}),
|
||||
).toEqual({ hasPullRemote: false, hasPushRemote: true });
|
||||
});
|
||||
|
||||
// The rest covers a daemon that predates pullRemote and pushRemote.
|
||||
const tracked = {
|
||||
upstreamState: "tracked",
|
||||
aheadOfOrigin: 1,
|
||||
isPaseoOwnedWorktree: false,
|
||||
} as const;
|
||||
const neverPushed = {
|
||||
upstreamState: "none",
|
||||
aheadOfOrigin: null,
|
||||
isPaseoOwnedWorktree: false,
|
||||
} as const;
|
||||
|
||||
it("pulls and pushes a tracked branch on an older daemon only when the checkout has origin", () => {
|
||||
expect(readSyncRemotes({ ...tracked, hasRemote: true })).toEqual({
|
||||
hasPullRemote: true,
|
||||
hasPushRemote: true,
|
||||
});
|
||||
expect(readSyncRemotes({ ...tracked, hasRemote: false })).toEqual({
|
||||
hasPullRemote: false,
|
||||
hasPushRemote: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("makes a regular checkout's first push only where an older daemon confirmed it", () => {
|
||||
expect(
|
||||
readSyncRemotes({ ...neverPushed, hasRemote: true, firstPushRemote: "origin" }),
|
||||
).toMatchObject({ hasPushRemote: true });
|
||||
expect(
|
||||
readSyncRemotes({ ...neverPushed, hasRemote: true, firstPushRemote: null }),
|
||||
).toMatchObject({ hasPushRemote: false });
|
||||
});
|
||||
|
||||
it("keeps a Paseo worktree's first push on an older daemon that reports no first push remote", () => {
|
||||
expect(
|
||||
readSyncRemotes({
|
||||
...neverPushed,
|
||||
hasRemote: true,
|
||||
firstPushRemote: null,
|
||||
isPaseoOwnedWorktree: true,
|
||||
}),
|
||||
).toMatchObject({ hasPushRemote: true });
|
||||
});
|
||||
});
|
||||
|
||||
it("does not offer a first push when the branch's remote copy was deleted", () => {
|
||||
const actions = buildGitActions(
|
||||
createInput({
|
||||
hasRemote: true,
|
||||
upstream: "gone",
|
||||
isOnBaseBranch: false,
|
||||
aheadCount: 2,
|
||||
aheadOfOrigin: null,
|
||||
behindOfOrigin: null,
|
||||
shipDefault: "pr",
|
||||
}),
|
||||
);
|
||||
const pushAction = actions.secondary.find((action) => action.id === "push");
|
||||
|
||||
expect(actions.primary).toMatchObject({ id: "pr", label: "Create PR" });
|
||||
expect(pushAction?.unavailableMessage).toBe(
|
||||
"Push isn't available because the branch this one tracks no longer exists",
|
||||
);
|
||||
});
|
||||
|
||||
describe("a published branch whose upstream the daemon cannot read", () => {
|
||||
const unreadableUpstream = {
|
||||
hasRemote: true,
|
||||
upstream: "unknown",
|
||||
isOnBaseBranch: false,
|
||||
aheadCount: 2,
|
||||
aheadOfOrigin: null,
|
||||
behindOfOrigin: null,
|
||||
shipDefault: "pr",
|
||||
} as const;
|
||||
|
||||
it("does not offer a first push in a regular checkout", () => {
|
||||
const actions = buildGitActions(createInput(unreadableUpstream));
|
||||
|
||||
expect(actions.primary).toMatchObject({ id: "pr", label: "Create PR" });
|
||||
expect(pushActionOf(actions)?.unavailableMessage).toEqual(expect.any(String));
|
||||
});
|
||||
|
||||
it("keeps offering Push in a Paseo worktree", () => {
|
||||
const actions = buildGitActions(
|
||||
createInput({ ...unreadableUpstream, isPaseoOwnedWorktree: true }),
|
||||
);
|
||||
|
||||
expect(actions.primary).toMatchObject({ id: "push", label: "Push" });
|
||||
expect(pushActionOf(actions)).toMatchObject({
|
||||
disabled: false,
|
||||
unavailableMessage: undefined,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("readUpstreamState", () => {
|
||||
it("uses the upstream state the daemon reports", () => {
|
||||
expect(
|
||||
readUpstreamState({
|
||||
upstreamState: "none",
|
||||
aheadOfOrigin: null,
|
||||
isPaseoOwnedWorktree: false,
|
||||
}),
|
||||
).toBe("none");
|
||||
expect(
|
||||
readUpstreamState({
|
||||
upstreamState: "gone",
|
||||
aheadOfOrigin: null,
|
||||
isPaseoOwnedWorktree: true,
|
||||
}),
|
||||
).toBe("gone");
|
||||
});
|
||||
|
||||
it("keeps the old guess for daemons that predate upstream states", () => {
|
||||
expect(
|
||||
readUpstreamState({
|
||||
upstreamState: undefined,
|
||||
aheadOfOrigin: 1,
|
||||
isPaseoOwnedWorktree: false,
|
||||
}),
|
||||
).toBe("tracked");
|
||||
expect(
|
||||
readUpstreamState({
|
||||
upstreamState: undefined,
|
||||
aheadOfOrigin: null,
|
||||
isPaseoOwnedWorktree: true,
|
||||
}),
|
||||
).toBe("none");
|
||||
expect(
|
||||
readUpstreamState({
|
||||
upstreamState: undefined,
|
||||
aheadOfOrigin: null,
|
||||
isPaseoOwnedWorktree: false,
|
||||
}),
|
||||
).toBe("unknown");
|
||||
});
|
||||
|
||||
it("keeps an old daemon's never-pushed regular branch off Push", () => {
|
||||
const actions = buildGitActions(
|
||||
createInput({
|
||||
hasRemote: true,
|
||||
upstream: readUpstreamState({
|
||||
upstreamState: undefined,
|
||||
aheadOfOrigin: null,
|
||||
isPaseoOwnedWorktree: false,
|
||||
}),
|
||||
isOnBaseBranch: false,
|
||||
aheadCount: 1,
|
||||
aheadOfOrigin: null,
|
||||
behindOfOrigin: null,
|
||||
githubFeaturesEnabled: false,
|
||||
shipDefault: "merge",
|
||||
}),
|
||||
);
|
||||
const pushAction = pushActionOf(actions);
|
||||
|
||||
expect(actions.primary).toMatchObject({ id: "merge-branch" });
|
||||
expect(pushAction?.unavailableMessage).toBe(
|
||||
"Push isn't available because there is nothing new to send",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("prioritizes push over pull request merge when local commits are unpushed", () => {
|
||||
const actions = buildGitActions(
|
||||
createInput({
|
||||
|
||||
@@ -2,7 +2,11 @@ import type { ReactElement } from "react";
|
||||
|
||||
import type { ActionStatus } from "@/components/ui/dropdown-menu";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import type { CheckoutPrMergeMethod, PullRequestMergeable } from "@getpaseo/protocol/messages";
|
||||
import type {
|
||||
CheckoutPrMergeMethod,
|
||||
CheckoutStatusResponse,
|
||||
PullRequestMergeable,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
|
||||
import type { MergeCapability } from "./merge-capability";
|
||||
|
||||
@@ -73,7 +77,60 @@ export function canMergeIntoLocalBase(
|
||||
return currentBranch !== localTarget;
|
||||
}
|
||||
|
||||
export interface BuildGitActionsInput {
|
||||
type CheckoutStatusPayload = CheckoutStatusResponse["payload"];
|
||||
|
||||
export type GitUpstreamState = NonNullable<CheckoutStatusPayload["upstreamState"]>;
|
||||
|
||||
export function readUpstreamState(
|
||||
status: Pick<CheckoutStatusPayload, "upstreamState" | "aheadOfOrigin" | "isPaseoOwnedWorktree">,
|
||||
): GitUpstreamState {
|
||||
if (status.upstreamState !== undefined) {
|
||||
return status.upstreamState;
|
||||
}
|
||||
// COMPAT(checkoutUpstreamState): added in v0.17.4, remove after 2027-05-23 once the daemon
|
||||
// floor reports upstreamState. Older daemons send a null upstream for both a never-pushed and
|
||||
// a deleted remote branch. Only a Paseo worktree's null was trusted as never pushed.
|
||||
if (status.aheadOfOrigin !== null) {
|
||||
return "tracked";
|
||||
}
|
||||
return status.isPaseoOwnedWorktree ? "none" : "unknown";
|
||||
}
|
||||
|
||||
export interface SyncRemotes {
|
||||
/** Pull has a remote to fetch the branch from. Not limited to origin. */
|
||||
hasPullRemote: boolean;
|
||||
/** Push has a remote to send the branch to. Not limited to origin. */
|
||||
hasPushRemote: boolean;
|
||||
}
|
||||
|
||||
export function readSyncRemotes(
|
||||
status: Pick<
|
||||
CheckoutStatusPayload,
|
||||
| "pullRemote"
|
||||
| "pushRemote"
|
||||
| "hasRemote"
|
||||
| "firstPushRemote"
|
||||
| "upstreamState"
|
||||
| "aheadOfOrigin"
|
||||
| "isPaseoOwnedWorktree"
|
||||
>,
|
||||
): SyncRemotes {
|
||||
if (status.pullRemote !== undefined && status.pushRemote !== undefined) {
|
||||
return { hasPullRemote: status.pullRemote !== null, hasPushRemote: status.pushRemote !== null };
|
||||
}
|
||||
// COMPAT(checkoutSyncRemotes): added in v0.17.5, remove after 2027-05-24 once the daemon floor
|
||||
// reports pullRemote and pushRemote. Older daemons pull and push only in checkouts that have
|
||||
// origin. They make a first push from a Paseo worktree, and from a regular checkout only where
|
||||
// they report firstPushRemote.
|
||||
const isFirstPush = readUpstreamState(status) === "none";
|
||||
const canFirstPush = status.isPaseoOwnedWorktree || (status.firstPushRemote ?? null) !== null;
|
||||
return {
|
||||
hasPullRemote: status.hasRemote,
|
||||
hasPushRemote: status.hasRemote && (!isFirstPush || canFirstPush),
|
||||
};
|
||||
}
|
||||
|
||||
export interface BuildGitActionsInput extends SyncRemotes {
|
||||
isGit: boolean;
|
||||
githubFeaturesEnabled: boolean;
|
||||
/** Forge brand label (e.g. "GitHub", "GitLab") for forge-neutral unavailable copy. */
|
||||
@@ -88,7 +145,7 @@ export interface BuildGitActionsInput {
|
||||
pullRequestIsMerged: boolean;
|
||||
pullRequestMergeable: PullRequestMergeable;
|
||||
mergeCapability: MergeCapability | null;
|
||||
hasRemote: boolean;
|
||||
upstream: GitUpstreamState;
|
||||
isPaseoOwnedWorktree: boolean;
|
||||
isOnBaseBranch: boolean;
|
||||
canMergeLocally: boolean;
|
||||
@@ -546,20 +603,28 @@ function getEnablePullRequestAutoMergeActionLabel(id: PullRequestAutoMergeEnable
|
||||
}
|
||||
|
||||
function canPull(input: BuildGitActionsInput): boolean {
|
||||
return input.hasRemote && !input.hasUncommittedChanges && (input.behindOfOrigin ?? 0) > 0;
|
||||
return input.hasPullRemote && !input.hasUncommittedChanges && (input.behindOfOrigin ?? 0) > 0;
|
||||
}
|
||||
|
||||
function canPush(input: BuildGitActionsInput): boolean {
|
||||
return input.hasRemote && hasPushableCommits(input) && (input.behindOfOrigin ?? 0) === 0;
|
||||
return input.hasPushRemote && hasPushableCommits(input) && (input.behindOfOrigin ?? 0) === 0;
|
||||
}
|
||||
|
||||
function hasPushableCommits(input: BuildGitActionsInput): boolean {
|
||||
if ((input.aheadOfOrigin ?? 0) > 0) {
|
||||
return true;
|
||||
switch (input.upstream) {
|
||||
case "tracked":
|
||||
return (input.aheadOfOrigin ?? 0) > 0;
|
||||
case "none":
|
||||
// A first push, which sets the upstream. The commits to send are the ones ahead of the base.
|
||||
return input.aheadCount > 0;
|
||||
case "gone":
|
||||
case "unknown":
|
||||
// The branch has an upstream that is deleted or unreadable, so nothing counts the commits
|
||||
// left to send. Paseo worktrees publish whenever the branch is ahead of its base, for
|
||||
// example after a merged PR. Regular checkouts do not: Push would re-create a branch that
|
||||
// was deleted.
|
||||
return input.isPaseoOwnedWorktree && input.aheadCount > 0;
|
||||
}
|
||||
// No-upstream Paseo worktrees are first-pushable: the daemon push sets upstream with `git push -u`.
|
||||
// Do not fold this into aheadOfOrigin; null also covers deleted/pruned upstream branches.
|
||||
return input.isPaseoOwnedWorktree && input.aheadOfOrigin === null && input.aheadCount > 0;
|
||||
}
|
||||
|
||||
function canMergeFromBase(input: BuildGitActionsInput): boolean {
|
||||
@@ -642,7 +707,7 @@ function hasEnabledPrAutoMerge(input: BuildGitActionsInput): boolean {
|
||||
}
|
||||
|
||||
function getPullUnavailableMessage(input: BuildGitActionsInput): string | undefined {
|
||||
if (!input.hasRemote) {
|
||||
if (!input.hasPullRemote) {
|
||||
return i18n.t("workspace.git.actions.unavailable.pullNoRemote");
|
||||
}
|
||||
if (input.hasUncommittedChanges) {
|
||||
@@ -658,20 +723,23 @@ function getPullUnavailableMessage(input: BuildGitActionsInput): string | undefi
|
||||
}
|
||||
|
||||
function getPushUnavailableMessage(input: BuildGitActionsInput): string | undefined {
|
||||
if (!input.hasRemote) {
|
||||
if (!input.hasPushRemote) {
|
||||
return i18n.t("workspace.git.actions.unavailable.pushNoRemote");
|
||||
}
|
||||
if ((input.behindOfOrigin ?? 0) > 0) {
|
||||
return i18n.t("workspace.git.actions.unavailable.pushBehind");
|
||||
}
|
||||
if (!hasPushableCommits(input)) {
|
||||
return i18n.t("workspace.git.actions.unavailable.pushNothing");
|
||||
if (hasPushableCommits(input)) {
|
||||
return undefined;
|
||||
}
|
||||
return undefined;
|
||||
if (input.upstream === "gone") {
|
||||
return i18n.t("workspace.git.actions.unavailable.pushUpstreamGone");
|
||||
}
|
||||
return i18n.t("workspace.git.actions.unavailable.pushNothing");
|
||||
}
|
||||
|
||||
function getPullAndPushUnavailableMessage(input: BuildGitActionsInput): string | undefined {
|
||||
if (!input.hasRemote) {
|
||||
if (!input.hasPullRemote || !input.hasPushRemote) {
|
||||
return i18n.t("workspace.git.actions.unavailable.pullAndPushNoRemote");
|
||||
}
|
||||
if (input.hasUncommittedChanges) {
|
||||
|
||||
@@ -15,9 +15,13 @@ import {
|
||||
isCurrentBranchBase,
|
||||
canMergeIntoLocalBase,
|
||||
narrowPullRequestState,
|
||||
readSyncRemotes,
|
||||
readUpstreamState,
|
||||
type BuildGitActionsInput,
|
||||
type GitAction,
|
||||
type GitActions,
|
||||
type GitUpstreamState,
|
||||
type SyncRemotes,
|
||||
} from "@/git/policy";
|
||||
import { deriveMergeCapability } from "@/git/merge-capability";
|
||||
import type { CheckoutPrMergeMethod } from "@getpaseo/protocol/messages";
|
||||
@@ -121,14 +125,16 @@ interface DeriveGitActionsStateArgs {
|
||||
baseRef: string | undefined;
|
||||
}
|
||||
|
||||
interface DerivedGitActionsState {
|
||||
const NO_SYNC_REMOTES: SyncRemotes = { hasPullRemote: false, hasPushRemote: false };
|
||||
|
||||
interface DerivedGitActionsState extends SyncRemotes {
|
||||
actionsDisabled: boolean;
|
||||
aheadCount: number;
|
||||
behindBaseCount: number;
|
||||
aheadOfOrigin: number | null;
|
||||
behindOfOrigin: number | null;
|
||||
hasPullRequest: boolean;
|
||||
hasRemote: boolean;
|
||||
upstream: GitUpstreamState;
|
||||
isPaseoOwnedWorktree: boolean;
|
||||
isOnBaseBranch: boolean;
|
||||
canMergeLocally: boolean;
|
||||
@@ -179,7 +185,8 @@ function deriveGitActionsState(args: DeriveGitActionsStateArgs): DerivedGitActio
|
||||
actionsDisabled,
|
||||
...extractGitCommitCounts(gitStatus),
|
||||
hasPullRequest: Boolean(prStatus?.url),
|
||||
hasRemote: gitStatus?.hasRemote ?? false,
|
||||
...(gitStatus ? readSyncRemotes(gitStatus) : NO_SYNC_REMOTES),
|
||||
upstream: gitStatus ? readUpstreamState(gitStatus) : "unknown",
|
||||
isPaseoOwnedWorktree,
|
||||
isOnBaseBranch: isCurrentBranchBase(gitStatus?.currentBranch, baseRef),
|
||||
canMergeLocally: canMergeIntoLocalBase(gitStatus?.currentBranch, baseRef),
|
||||
@@ -667,7 +674,9 @@ export function useGitActions({ serverId, cwd, icons }: UseGitActionsInput): Use
|
||||
aheadOfOrigin,
|
||||
behindOfOrigin,
|
||||
hasPullRequest,
|
||||
hasRemote,
|
||||
hasPullRemote,
|
||||
hasPushRemote,
|
||||
upstream,
|
||||
isPaseoOwnedWorktree,
|
||||
isOnBaseBranch,
|
||||
canMergeLocally,
|
||||
@@ -698,7 +707,9 @@ export function useGitActions({ serverId, cwd, icons }: UseGitActionsInput): Use
|
||||
pullRequestIsMerged: prStatus?.isMerged ?? false,
|
||||
pullRequestMergeable: prStatus?.mergeable ?? "UNKNOWN",
|
||||
mergeCapability: deriveMergeCapability(prStatus?.forgeSpecific, prStatus?.github),
|
||||
hasRemote,
|
||||
hasPullRemote,
|
||||
hasPushRemote,
|
||||
upstream,
|
||||
isPaseoOwnedWorktree,
|
||||
isOnBaseBranch,
|
||||
canMergeLocally,
|
||||
@@ -806,7 +817,9 @@ export function useGitActions({ serverId, cwd, icons }: UseGitActionsInput): Use
|
||||
};
|
||||
}, [
|
||||
isGit,
|
||||
hasRemote,
|
||||
hasPullRemote,
|
||||
hasPushRemote,
|
||||
upstream,
|
||||
hasPullRequest,
|
||||
prStatus?.url,
|
||||
prStatus?.state,
|
||||
|
||||
@@ -151,20 +151,26 @@ describe("ACP provider catalog", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("adds bundled goose on capable hosts and uses the ACP config on older hosts", () => {
|
||||
const goose = findProvider("goose");
|
||||
expect(buildAcpProviderConfigPatch(goose, (feature) => feature === "gooseProvider")).toEqual({
|
||||
providers: { goose: { enabled: true } },
|
||||
});
|
||||
expect(buildAcpProviderConfigPatch(goose)).toEqual({
|
||||
providers: {
|
||||
goose: {
|
||||
extends: "acp",
|
||||
label: "goose",
|
||||
description: goose.description,
|
||||
command: ["goose", "acp"],
|
||||
env: {},
|
||||
it.each([
|
||||
{ id: "goose", feature: "gooseProvider" },
|
||||
{ id: "hermes", feature: "hermesProvider" },
|
||||
] as const)(
|
||||
"adds bundled $id on capable hosts and uses the ACP config on older hosts",
|
||||
({ id, feature }) => {
|
||||
const entry = findProvider(id);
|
||||
expect(buildAcpProviderConfigPatch(entry, (supported) => supported === feature)).toEqual({
|
||||
providers: { [id]: { enabled: true } },
|
||||
});
|
||||
expect(buildAcpProviderConfigPatch(entry)).toEqual({
|
||||
providers: {
|
||||
[id]: {
|
||||
extends: "acp",
|
||||
label: entry.title,
|
||||
description: entry.description,
|
||||
command: [id, "acp"],
|
||||
env: {},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
@@ -24,9 +24,10 @@ export function buildAcpProviderConfigPatch(
|
||||
return { providers: { [entry.id]: { enabled: true } } };
|
||||
}
|
||||
// COMPAT(gooseProvider): added in v0.17.0, remove after 2027-05-20 once host floor includes the bundled adapter.
|
||||
// COMPAT(hermesProvider): added in v0.17.4, remove after 2027-05-23 once host floor includes the bundled adapter.
|
||||
// COMPAT(hopliteProvider): added after v0.11.2, remove after 2027-04-15 once host floor includes the bundled adapter.
|
||||
// COMPAT(fxProvider): added after v0.15.3, remove after 2027-05-09 once host floor includes the bundled adapter.
|
||||
if (feature !== "gooseProvider") {
|
||||
if (feature !== "gooseProvider" && feature !== "hermesProvider") {
|
||||
throw new Error(`Update the host to add ${entry.title}.`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -166,7 +166,7 @@ describe("ensureAgentIsInitialized", () => {
|
||||
kind: "assistant_message",
|
||||
id: "canonical-item",
|
||||
text: "Canonical before restart",
|
||||
timelineCursor: { epoch: "epoch-1", seq: 12 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 12, anchorSeq: 12 },
|
||||
timestamp: new Date("2026-07-27T10:00:00.000Z"),
|
||||
},
|
||||
],
|
||||
|
||||
@@ -738,6 +738,8 @@ export const ar: TranslationResources = {
|
||||
resumeCommandUnavailable: "أمر الاستئناف غير متوفر",
|
||||
reloadingAgent: "وكيل إعادة التحميل...",
|
||||
reloadedAgent: "وكيل إعادة تحميل",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"تمت إعادة تحميل الوكيل، لكن سجل المزوّد لا يطابق هذه المحادثة، لذا لم تتم مزامنته",
|
||||
failedToReloadAgent: "فشل في إعادة تحميل الوكيل",
|
||||
failedToCloseAgent: "فشل في إغلاق الوكيل",
|
||||
},
|
||||
@@ -912,6 +914,7 @@ export const ar: TranslationResources = {
|
||||
pushNoRemote: "الدفع غير متاح هنا لأن هذا الفرع غير متصل بجهاز التحكم عن بعد بعد",
|
||||
pushBehind: "الدفع غير متاح حتى الآن نظرًا لوجود تغييرات أحدث يجب إدخالها أولاً",
|
||||
pushNothing: "خدمة الدفع غير متاحة لأنه لا يوجد شيء جديد لإرساله",
|
||||
pushUpstreamGone: "الدفع غير متاح لأن الفرع الذي يتتبعه هذا الفرع لم يعد موجودًا",
|
||||
pullAndPushNoRemote:
|
||||
"السحب والدفع غير متاح هنا لأن هذا الفرع غير متصل بجهاز التحكم عن بعد بعد",
|
||||
pullAndPushDirty:
|
||||
|
||||
@@ -737,6 +737,8 @@ export const en = {
|
||||
resumeCommandUnavailable: "Resume command not available",
|
||||
reloadingAgent: "Reloading agent...",
|
||||
reloadedAgent: "Reloaded agent",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"Reloaded agent, but the provider's history doesn't match this chat, so it wasn't synced",
|
||||
failedToReloadAgent: "Failed to reload agent",
|
||||
failedToCloseAgent: "Failed to close agent",
|
||||
},
|
||||
@@ -913,6 +915,8 @@ export const en = {
|
||||
"Push isn't available here because this branch is not connected to a remote yet",
|
||||
pushBehind: "Push isn't available yet because there are newer changes to bring in first",
|
||||
pushNothing: "Push isn't available because there is nothing new to send",
|
||||
pushUpstreamGone:
|
||||
"Push isn't available because the branch this one tracks no longer exists",
|
||||
pullAndPushNoRemote:
|
||||
"Pull and push isn't available here because this branch is not connected to a remote yet",
|
||||
pullAndPushDirty:
|
||||
|
||||
@@ -745,6 +745,8 @@ export const es: TranslationResources = {
|
||||
resumeCommandUnavailable: "Comando de reanudación no disponible",
|
||||
reloadingAgent: "Agente de recarga...",
|
||||
reloadedAgent: "Agente recargado",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"Agente recargado, pero el historial del proveedor no coincide con este chat, así que no se sincronizó",
|
||||
failedToReloadAgent: "No se pudo recargar el agente",
|
||||
failedToCloseAgent: "No se pudo cerrar el agente",
|
||||
},
|
||||
@@ -925,6 +927,8 @@ export const es: TranslationResources = {
|
||||
pushBehind:
|
||||
"Push aún no está disponible porque hay cambios más nuevos que implementar primero",
|
||||
pushNothing: "Push no está disponible porque no hay nada nuevo que enviar",
|
||||
pushUpstreamGone:
|
||||
"Push no está disponible porque la rama que sigue esta rama ya no existe",
|
||||
pullAndPushNoRemote:
|
||||
"Tirar y empujar no está disponible aquí porque esta rama aún no está conectada a un control remoto",
|
||||
pullAndPushDirty:
|
||||
|
||||
@@ -745,6 +745,8 @@ export const fr: TranslationResources = {
|
||||
resumeCommandUnavailable: "Commande de reprise indisponible",
|
||||
reloadingAgent: "Rechargement de l’agent…",
|
||||
reloadedAgent: "Agent rechargé",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"Agent rechargé, mais l’historique du fournisseur ne correspond pas à cette conversation, il n’a donc pas été synchronisé",
|
||||
failedToReloadAgent: "Impossible de recharger l’agent",
|
||||
failedToCloseAgent: "Impossible de fermer l’agent",
|
||||
},
|
||||
@@ -926,6 +928,7 @@ export const fr: TranslationResources = {
|
||||
pushBehind:
|
||||
"Push indisponible pour l’instant : des modifications plus récentes doivent d’abord être récupérées",
|
||||
pushNothing: "Push indisponible : il n’y a rien de nouveau à pousser",
|
||||
pushUpstreamGone: "Push indisponible : la branche suivie par cette branche n’existe plus",
|
||||
pullAndPushNoRemote:
|
||||
"Pull et push indisponibles : cette branche n’est pas encore liée à un dépôt distant",
|
||||
pullAndPushDirty:
|
||||
|
||||
@@ -745,6 +745,8 @@ export const ja: TranslationResources = {
|
||||
resumeCommandUnavailable: "再開コマンドが利用できません",
|
||||
reloadingAgent: "エージェントを再読み込み中...",
|
||||
reloadedAgent: "エージェントを再読み込みしました",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"エージェントを再読み込みしましたが、プロバイダーの履歴がこのチャットと一致しないため同期しませんでした",
|
||||
failedToReloadAgent: "エージェントの再読み込みに失敗しました",
|
||||
failedToCloseAgent: "エージェントを閉じられませんでした",
|
||||
},
|
||||
@@ -919,6 +921,8 @@ export const ja: TranslationResources = {
|
||||
"このブランチはまだリモートに接続されていないため、プッシュはここでは利用できません",
|
||||
pushBehind: "取り込む必要がある新しい変更があるため、まだプッシュは利用できません",
|
||||
pushNothing: "プッシュする変更がないため、プッシュは利用できません",
|
||||
pushUpstreamGone:
|
||||
"このブランチが追跡しているブランチが存在しないため、プッシュは利用できません",
|
||||
pullAndPushNoRemote:
|
||||
"このブランチはまだリモートに接続されていないため、プル&プッシュはここでは利用できません",
|
||||
pullAndPushDirty:
|
||||
|
||||
@@ -740,6 +740,8 @@ export const ko: TranslationResources = {
|
||||
resumeCommandUnavailable: "재개 명령을 사용할 수 없습니다",
|
||||
reloadingAgent: "에이전트 다시 로드 중...",
|
||||
reloadedAgent: "에이전트를 다시 로드했습니다",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"에이전트를 다시 로드했지만 제공자 기록이 이 채팅과 일치하지 않아 동기화하지 않았습니다",
|
||||
failedToReloadAgent: "에이전트를 다시 로드하지 못했습니다",
|
||||
failedToCloseAgent: "에이전트를 닫지 못했습니다",
|
||||
},
|
||||
@@ -913,6 +915,7 @@ export const ko: TranslationResources = {
|
||||
"이 브랜치가 아직 원격에 연결되어 있지 않아 여기서 푸시를 사용할 수 없습니다",
|
||||
pushBehind: "먼저 가져와야 할 최신 변경 사항이 있어 아직 푸시를 사용할 수 없습니다",
|
||||
pushNothing: "새로 보낼 항목이 없어 푸시를 사용할 수 없습니다",
|
||||
pushUpstreamGone: "이 브랜치가 추적하는 브랜치가 더 이상 없어 푸시를 사용할 수 없습니다",
|
||||
pullAndPushNoRemote:
|
||||
"이 브랜치가 아직 원격에 연결되어 있지 않아 여기서 풀 후 푸시를 사용할 수 없습니다",
|
||||
pullAndPushDirty:
|
||||
|
||||
@@ -743,6 +743,8 @@ export const ptBR: TranslationResources = {
|
||||
resumeCommandUnavailable: "Comando de retomada indisponível",
|
||||
reloadingAgent: "Recarregando agente...",
|
||||
reloadedAgent: "Agente recarregado",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"Agente recarregado, mas o histórico do provedor não corresponde a este chat, então não foi sincronizado",
|
||||
failedToReloadAgent: "Falha ao recarregar agente",
|
||||
failedToCloseAgent: "Falha ao fechar agente",
|
||||
},
|
||||
@@ -921,6 +923,8 @@ export const ptBR: TranslationResources = {
|
||||
pushBehind:
|
||||
"Push ainda não está disponível porque há alterações mais recentes para trazer primeiro",
|
||||
pushNothing: "Push não está disponível porque não há nada novo para enviar",
|
||||
pushUpstreamGone:
|
||||
"Push não está disponível porque a branch que esta branch acompanha não existe mais",
|
||||
pullAndPushNoRemote:
|
||||
"Pull e push não estão disponíveis aqui porque esta branch ainda não está conectada a um remoto",
|
||||
pullAndPushDirty:
|
||||
|
||||
@@ -746,6 +746,8 @@ export const ru: TranslationResources = {
|
||||
resumeCommandUnavailable: "Команда возобновления недоступна",
|
||||
reloadingAgent: "Перезагрузка агента...",
|
||||
reloadedAgent: "Агент перезагружен",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"Агент перезагружен, но история провайдера не совпадает с этим чатом, поэтому она не синхронизирована",
|
||||
failedToReloadAgent: "Не удалось перезагрузить агента",
|
||||
failedToCloseAgent: "Не удалось закрыть агента",
|
||||
},
|
||||
@@ -924,6 +926,8 @@ export const ru: TranslationResources = {
|
||||
"Отправка изменений недоступна: эта ветка ещё не связана с удалённым репозиторием.",
|
||||
pushBehind: "Отправка изменений пока недоступна: сначала получите более новые изменения.",
|
||||
pushNothing: "Отправка изменений недоступна: нет новых изменений для отправки.",
|
||||
pushUpstreamGone:
|
||||
"Отправка изменений недоступна: ветка, которую отслеживает эта ветка, больше не существует.",
|
||||
pullAndPushNoRemote:
|
||||
"Получение и отправка изменений недоступны: эта ветка ещё не связана с удалённым репозиторием.",
|
||||
pullAndPushDirty:
|
||||
|
||||
@@ -738,6 +738,8 @@ export const zhCN: TranslationResources = {
|
||||
resumeCommandUnavailable: "恢复命令不可用",
|
||||
reloadingAgent: "正在重新加载 Agent...",
|
||||
reloadedAgent: "已重新加载 Agent",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"已重新加载 Agent,但提供方的历史记录与此对话不一致,因此未同步",
|
||||
failedToReloadAgent: "重新加载 Agent 失败",
|
||||
failedToCloseAgent: "关闭 Agent 失败",
|
||||
},
|
||||
@@ -908,6 +910,7 @@ export const zhCN: TranslationResources = {
|
||||
pushNoRemote: "此处无法 push,因为此分支尚未连接到 remote",
|
||||
pushBehind: "暂时无法 push,因为需要先拉取更新的变更",
|
||||
pushNothing: "无法 push,因为没有新的内容可发送",
|
||||
pushUpstreamGone: "无法 push,因为此分支跟踪的分支已不存在",
|
||||
pullAndPushNoRemote: "此处无法 pull 并 push,因为此分支尚未连接到 remote",
|
||||
pullAndPushDirty: "有本地变更时无法 pull 并 push,请先 commit 或 stash",
|
||||
pullAndPushNoIncoming: "无法 pull 并 push,因为没有需要先 pull 的传入变更",
|
||||
|
||||
@@ -91,7 +91,7 @@ describe("AgentDirectoryReplica", () => {
|
||||
id: "reply",
|
||||
text: "server history",
|
||||
timestamp: new Date(),
|
||||
timelineCursor: { epoch: "e", seq: 1 },
|
||||
timelineCursor: { epoch: "e", seq: 1, anchorSeq: 1 },
|
||||
},
|
||||
],
|
||||
head: [],
|
||||
|
||||
@@ -250,6 +250,7 @@ const PROBE_INACTIVE_WHILE_ONLINE_MAX_MS = 30 * 60_000;
|
||||
const ACTIVE_RTT_WINDOW_MS = 60_000;
|
||||
const ADAPTIVE_SWITCH_THRESHOLD_MS = 40;
|
||||
const ADAPTIVE_SWITCH_MIN_IMPROVEMENT_RATIO = 0.35;
|
||||
const MAX_STALE_TIMELINE_PAGE_ATTEMPTS = 3;
|
||||
const ADAPTIVE_SWITCH_CONSECUTIVE_PROBES = 3;
|
||||
const CONFIGURED_OVERRIDE_BOOTSTRAP_RETRY_MS = 1_000;
|
||||
|
||||
@@ -3054,12 +3055,19 @@ export class HostRuntimeStore {
|
||||
const directory = this.directorySyncByServer.get(serverId);
|
||||
if (!directory) throw new Error(`Unknown host runtime for serverId ${serverId}`);
|
||||
const owner = useSessionStore.getState().sessions[serverId]?.viewedTimelineSync;
|
||||
const page = await directory.fetchTimeline(agentId, request);
|
||||
if (owner && useSessionStore.getState().sessions[serverId]?.viewedTimelineSync === owner) {
|
||||
// A page served before a rewind this client applied is asked for again. Seqs only grow within
|
||||
// an epoch, so the next page includes the rewind unless another one landed meanwhile.
|
||||
for (let attempt = 1; ; attempt += 1) {
|
||||
const page = await directory.fetchTimeline(agentId, request);
|
||||
if (!owner || useSessionStore.getState().sessions[serverId]?.viewedTimelineSync !== owner) {
|
||||
return page;
|
||||
}
|
||||
owner.flushStreamAgent(agentId);
|
||||
owner.applyTimelineResponse(page);
|
||||
if (owner.applyTimelineResponse(page) === "applied") return page;
|
||||
if (attempt === MAX_STALE_TIMELINE_PAGE_ATTEMPTS) {
|
||||
throw new Error(`Timeline page for ${agentId} stayed behind a rewind`);
|
||||
}
|
||||
}
|
||||
return page;
|
||||
}
|
||||
|
||||
createViewedTimelineOwner(
|
||||
|
||||
@@ -189,7 +189,7 @@ function timelineItem(text = "Cached"): StreamItem {
|
||||
id: "message-1",
|
||||
text,
|
||||
timestamp: new Date("2026-07-18T08:02:00.000Z"),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 12 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 12, anchorSeq: 12 },
|
||||
};
|
||||
}
|
||||
|
||||
@@ -840,7 +840,7 @@ describe("ReplicaCache", () => {
|
||||
version: 1,
|
||||
data: { passed: 4, failed: 0 },
|
||||
timestamp: new Date("2026-07-18T08:02:00.000Z"),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 12 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 12, anchorSeq: 12 },
|
||||
};
|
||||
writer.commitTimeline(SERVER_ID, "agent-1", {
|
||||
agentId: "agent-1",
|
||||
@@ -885,6 +885,32 @@ describe("ReplicaCache", () => {
|
||||
expect(await createCache(storage).readTimeline(SERVER_ID, "agent-1")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("keeps where each cached row started, and refetches a timeline cached without it", async () => {
|
||||
const storage = new MemoryStorage();
|
||||
const writer = createCache(storage);
|
||||
const updatedAfterItStarted: StreamItem = {
|
||||
...timelineItem(),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 12, anchorSeq: 9 },
|
||||
};
|
||||
writer.commitTimeline(SERVER_ID, "agent-1", { ...timeline(), items: [updatedAfterItStarted] });
|
||||
await writer.flush();
|
||||
expect((await createCache(storage).readTimeline(SERVER_ID, "agent-1"))?.items).toEqual([
|
||||
updatedAfterItStarted,
|
||||
]);
|
||||
|
||||
const row = requireTimelineRow(storage);
|
||||
const payload = JSON.parse(row.payload) as {
|
||||
items: Array<{ timelineCursor?: Record<string, unknown> }>;
|
||||
};
|
||||
delete payload.items[0]?.timelineCursor?.anchorSeq;
|
||||
storage.rows.set(`${row.serverId}:${row.kind}:${row.id}`, {
|
||||
...row,
|
||||
payload: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
expect(await createCache(storage).readTimeline(SERVER_ID, "agent-1")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("refetches old cached Markdown fragments instead of offering them as whole messages", async () => {
|
||||
const storage = new MemoryStorage();
|
||||
const writer = createCache(storage);
|
||||
@@ -1355,7 +1381,7 @@ it("retains semantic agent messages across disk-cache reconstruction", async ()
|
||||
kind: "tool_call",
|
||||
id: "delivery",
|
||||
timestamp: new Date(1),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 12 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 12, anchorSeq: 12 },
|
||||
payload: {
|
||||
source: "agent",
|
||||
data: {
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
isUnreconciledLocalUserMessage,
|
||||
type AgentToolCallData,
|
||||
type StreamItem,
|
||||
type TimelinePosition,
|
||||
} from "@/types/stream";
|
||||
import type { UnsettledTurn } from "@/timeline/turn-liveness";
|
||||
import { normalizeAgentSnapshot } from "@/utils/agent-snapshots";
|
||||
@@ -82,7 +83,15 @@ const IsoDateSchema = z.iso.datetime();
|
||||
const TimelinePositionSchema = z.strictObject({
|
||||
epoch: z.string(),
|
||||
seq: z.number().int().nonnegative(),
|
||||
// COMPAT(timelineRewindOperations): absent on caches written before rows were anchored, added in
|
||||
// v0.14.1, remove after 2027-05-10. Such a cache is not restored; the chat loads its tail instead.
|
||||
anchorSeq: z.number().int().nonnegative().optional(),
|
||||
});
|
||||
type StoredTimelinePosition = z.infer<typeof TimelinePositionSchema>;
|
||||
|
||||
function isAnchored(position: StoredTimelinePosition | undefined): boolean {
|
||||
return position === undefined || position.anchorSeq !== undefined;
|
||||
}
|
||||
const PluginTimelineDataSchema: z.ZodType<PluginTimelineData> = z.lazy(() =>
|
||||
z.union([
|
||||
z.null(),
|
||||
@@ -423,6 +432,10 @@ function deserializeTimeline(stored: StoredTimeline | null): CachedTimeline | nu
|
||||
if (!stored) {
|
||||
return null;
|
||||
}
|
||||
// A rewind retires rows by anchor, so an unanchored row could not be retired.
|
||||
if (!stored.items.every((item) => isAnchored(item.timelineCursor))) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
agentId: stored.agentId,
|
||||
items: stored.items.map(deserializeTimelineItem),
|
||||
@@ -539,11 +552,20 @@ function serializeTimelineItem(item: StreamItem): StoredTimelineItem | null {
|
||||
}
|
||||
}
|
||||
|
||||
function anchoredPosition(position: StoredTimelinePosition | undefined): {
|
||||
timelineCursor?: TimelinePosition;
|
||||
} {
|
||||
if (!position || position.anchorSeq === undefined) return {};
|
||||
return {
|
||||
timelineCursor: { epoch: position.epoch, seq: position.seq, anchorSeq: position.anchorSeq },
|
||||
};
|
||||
}
|
||||
|
||||
function deserializeTimelineItem(item: StoredTimelineItem): StreamItem {
|
||||
if (item.kind === "plugin") {
|
||||
return {
|
||||
id: item.id,
|
||||
...(item.timelineCursor ? { timelineCursor: item.timelineCursor } : {}),
|
||||
...anchoredPosition(item.timelineCursor),
|
||||
...(item.turnId ? { turnId: item.turnId } : {}),
|
||||
timestamp: new Date(item.timestamp),
|
||||
kind: item.kind,
|
||||
@@ -562,7 +584,7 @@ function deserializeBuiltinTimelineItem(
|
||||
): StreamItem {
|
||||
const base = {
|
||||
id: item.id,
|
||||
...(item.timelineCursor ? { timelineCursor: item.timelineCursor } : {}),
|
||||
...anchoredPosition(item.timelineCursor),
|
||||
...(item.turnId ? { turnId: item.turnId } : {}),
|
||||
timestamp: new Date(item.timestamp),
|
||||
};
|
||||
|
||||
@@ -2188,11 +2188,10 @@ function WorkspaceScreenContent({
|
||||
|
||||
toast.show(t("workspace.tabs.toasts.reloadingAgent"), { durationMs: null });
|
||||
try {
|
||||
await client.refreshAgent(agentId);
|
||||
// Send the existing cursor so the server detects the new epoch and
|
||||
// returns reset:true. Without a cursor, the server returns reset:false
|
||||
// and the client takes the incremental path, where new-epoch rows are
|
||||
// dropped against the stale cursor.
|
||||
const refreshed = await client.refreshAgent(agentId);
|
||||
// Send the existing cursor: Reload agent keeps the history, so the server
|
||||
// returns only the rows it added. When the history was imported again
|
||||
// under a new epoch, the cursor reads as stale and the server resets.
|
||||
const sessionState = useSessionStore.getState().sessions[normalizedServerId];
|
||||
const currentCursor = sessionState?.agentTimelineCursor.get(agentId);
|
||||
await getHostRuntimeStore().fetchAgentTimeline(normalizedServerId, agentId, {
|
||||
@@ -2201,7 +2200,13 @@ function WorkspaceScreenContent({
|
||||
? { cursor: { epoch: currentCursor.epoch, seq: currentCursor.endSeq } }
|
||||
: {}),
|
||||
});
|
||||
toast.show(t("workspace.tabs.toasts.reloadedAgent"), { variant: "success" });
|
||||
if (refreshed.historyDiverged) {
|
||||
toast.show(t("workspace.tabs.toasts.reloadedAgentHistoryDiverged"), {
|
||||
variant: "warning",
|
||||
});
|
||||
} else {
|
||||
toast.show(t("workspace.tabs.toasts.reloadedAgent"), { variant: "success" });
|
||||
}
|
||||
} catch (error) {
|
||||
toast.error(
|
||||
error instanceof Error ? error.message : t("workspace.tabs.toasts.failedToReloadAgent"),
|
||||
|
||||
@@ -322,6 +322,12 @@ export interface AgentTimelineCursorState {
|
||||
}>;
|
||||
}
|
||||
|
||||
/** The latest conversation rewind applied to an agent's history, by its sequence number. */
|
||||
export interface AgentTimelineRewind {
|
||||
epoch: string;
|
||||
seq: number;
|
||||
}
|
||||
|
||||
export type AgentTimelineState =
|
||||
| { status: "cold" }
|
||||
| { status: "painted"; items: StreamItem[] }
|
||||
@@ -496,6 +502,7 @@ export interface SessionState {
|
||||
agentTimelineUnsettledTurn: Map<string, UnsettledTurn>;
|
||||
agentTimelineHasOlder: Map<string, boolean>;
|
||||
agentTimelineHasNewer: Map<string, boolean>;
|
||||
agentTimelineLatestRewind: Map<string, AgentTimelineRewind>;
|
||||
agentTimelineOlderFetchInFlight: Map<string, boolean>;
|
||||
historySyncGeneration: number;
|
||||
agentHistorySyncGeneration: Map<string, number>;
|
||||
@@ -615,6 +622,12 @@ interface SessionStoreActions {
|
||||
serverId: string,
|
||||
state: Map<string, boolean> | ((prev: Map<string, boolean>) => Map<string, boolean>),
|
||||
) => void;
|
||||
/** Records a rewind applied to the agent's history; an older one of the same history is ignored. */
|
||||
recordAgentTimelineRewind: (
|
||||
serverId: string,
|
||||
agentId: string,
|
||||
rewind: AgentTimelineRewind,
|
||||
) => void;
|
||||
setAgentTimelineOlderFetchInFlight: (
|
||||
serverId: string,
|
||||
state: Map<string, boolean> | ((prev: Map<string, boolean>) => Map<string, boolean>),
|
||||
@@ -751,6 +764,7 @@ function createInitialSessionState(
|
||||
agentTimelineUnsettledTurn: new Map(),
|
||||
agentTimelineHasOlder: new Map(),
|
||||
agentTimelineHasNewer: new Map(),
|
||||
agentTimelineLatestRewind: new Map(),
|
||||
agentTimelineOlderFetchInFlight: new Map(),
|
||||
historySyncGeneration: 0,
|
||||
agentHistorySyncGeneration: new Map(),
|
||||
@@ -1392,6 +1406,24 @@ export const useSessionStore = create<SessionStore>()(
|
||||
});
|
||||
},
|
||||
|
||||
recordAgentTimelineRewind: (serverId, agentId, rewind) => {
|
||||
set((prev) => {
|
||||
const session = prev.sessions[serverId];
|
||||
if (!session) return prev;
|
||||
const current = session.agentTimelineLatestRewind.get(agentId);
|
||||
if (current && current.epoch === rewind.epoch && current.seq >= rewind.seq) return prev;
|
||||
const next = new Map(session.agentTimelineLatestRewind);
|
||||
next.set(agentId, rewind);
|
||||
return {
|
||||
...prev,
|
||||
sessions: {
|
||||
...prev.sessions,
|
||||
[serverId]: { ...session, agentTimelineLatestRewind: next },
|
||||
},
|
||||
};
|
||||
});
|
||||
},
|
||||
|
||||
setAgentTimelineOlderFetchInFlight: (serverId, state) => {
|
||||
set((prev) => {
|
||||
const session = prev.sessions[serverId];
|
||||
|
||||
@@ -22,7 +22,10 @@ import {
|
||||
|
||||
export const TERMINAL_INPUT_CONTEXT_MENU_HIDDEN = true;
|
||||
export const TERMINAL_INPUT_HITBOX_SIZE = 1;
|
||||
/** Matched by the Android hardware keyboard module to claim arrow keys for this input. */
|
||||
/**
|
||||
* Matched on Android by the hardware keyboard module to claim arrow keys for this input, and by
|
||||
* PaseoTerminal to keep the keyboard from learning what is typed here, such as passwords.
|
||||
*/
|
||||
export const TERMINAL_INPUT_NATIVE_ID = "paseo-terminal-input";
|
||||
|
||||
export interface TerminalTextInputChange {
|
||||
|
||||
@@ -39,7 +39,7 @@ function item(id: string, text: string, seq: number): StreamItem {
|
||||
id,
|
||||
text,
|
||||
timestamp: new Date("2026-08-26T10:00:00.000Z"),
|
||||
timelineCursor: { epoch: "epoch-1", seq },
|
||||
timelineCursor: { epoch: "epoch-1", seq, anchorSeq: seq },
|
||||
};
|
||||
}
|
||||
|
||||
@@ -579,6 +579,235 @@ describe("viewed timeline persistence", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("conversation rewind through the owner", () => {
|
||||
const page = {
|
||||
requestId: "page-1",
|
||||
agentId: AGENT_ID,
|
||||
agent: null,
|
||||
direction: "tail",
|
||||
projection: "projected",
|
||||
reset: false,
|
||||
epoch: "epoch-1",
|
||||
error: null,
|
||||
hasNewer: false,
|
||||
hasOlder: false,
|
||||
staleCursor: false,
|
||||
gap: false,
|
||||
} as const;
|
||||
|
||||
function entry(seq: number, type: "user_message" | "assistant_message", text: string) {
|
||||
return {
|
||||
seqStart: seq,
|
||||
seqEnd: seq,
|
||||
sourceSeqRanges: [{ startSeq: seq, endSeq: seq }],
|
||||
collapsed: [],
|
||||
provider: "codex",
|
||||
item: { type, text },
|
||||
timestamp: `2026-08-26T10:00:0${seq}.000Z`,
|
||||
};
|
||||
}
|
||||
|
||||
function texts(items: readonly StreamItem[]): string[] {
|
||||
return items.flatMap((row) =>
|
||||
row.kind === "user_message" || row.kind === "assistant_message" ? [row.text] : [],
|
||||
);
|
||||
}
|
||||
|
||||
function viewed(): string[] {
|
||||
const session = useSessionStore.getState().sessions[SERVER_ID];
|
||||
const timeline = selectAgentTimelineState(session, AGENT_ID);
|
||||
const tail = timeline.status === "cold" ? [] : timeline.items;
|
||||
return texts([...tail, ...(session?.agentStreamHead.get(AGENT_ID) ?? [])]);
|
||||
}
|
||||
|
||||
function latestRewind() {
|
||||
return useSessionStore.getState().sessions[SERVER_ID]?.agentTimelineLatestRewind.get(AGENT_ID);
|
||||
}
|
||||
|
||||
it("retires B from the viewed and persisted timeline without refetching", () => {
|
||||
useSessionStore.getState().initializeSession(SERVER_ID, null);
|
||||
const commits: CachedTimeline[] = [];
|
||||
const owner = createOwner({
|
||||
readTimeline: async () => undefined,
|
||||
commitTimeline: (_serverId, _agentId, timeline) => commits.push(timeline),
|
||||
});
|
||||
owner.applyTimelineResponse({
|
||||
...page,
|
||||
window: { minSeq: 1, maxSeq: 4, nextSeq: 5 },
|
||||
startCursor: { epoch: "epoch-1", seq: 1 },
|
||||
endCursor: { epoch: "epoch-1", seq: 4 },
|
||||
entries: [
|
||||
entry(1, "user_message", "A"),
|
||||
entry(2, "assistant_message", "reply A"),
|
||||
entry(3, "user_message", "B"),
|
||||
entry(4, "assistant_message", "reply B"),
|
||||
],
|
||||
});
|
||||
|
||||
owner.applyStreamEvent(AGENT_ID, {
|
||||
event: { type: "rewind", retireFromSeq: 3 },
|
||||
seq: 5,
|
||||
epoch: "epoch-1",
|
||||
timestamp: new Date("2026-08-26T10:00:05.000Z"),
|
||||
});
|
||||
owner.applyStreamEvent(AGENT_ID, {
|
||||
event: {
|
||||
type: "timeline",
|
||||
provider: "codex",
|
||||
item: { type: "user_message", text: "C", messageId: "c" },
|
||||
} as AgentStreamEventPayload,
|
||||
seq: 6,
|
||||
epoch: "epoch-1",
|
||||
timestamp: new Date("2026-08-26T10:00:06.000Z"),
|
||||
});
|
||||
owner.flushStreamAgent(AGENT_ID);
|
||||
|
||||
expect(viewed()).toEqual(["A", "reply A", "C"]);
|
||||
expect(texts(commits.at(-1)?.items ?? [])).toEqual(["A", "reply A", "C"]);
|
||||
expect(commits.at(-1)?.range).toMatchObject({ epoch: "epoch-1", endSeq: 6 });
|
||||
expect(latestRewind()).toEqual({ epoch: "epoch-1", seq: 5 });
|
||||
owner.dispose();
|
||||
});
|
||||
|
||||
it("brings a second client that loads after the rewind to the same conversation", () => {
|
||||
useSessionStore.getState().initializeSession(SERVER_ID, null);
|
||||
const owner = createOwner({ readTimeline: async () => undefined, commitTimeline: () => {} });
|
||||
|
||||
owner.applyTimelineResponse({
|
||||
...page,
|
||||
window: { minSeq: 1, maxSeq: 6, nextSeq: 7 },
|
||||
startCursor: { epoch: "epoch-1", seq: 1 },
|
||||
endCursor: { epoch: "epoch-1", seq: 6 },
|
||||
entries: [
|
||||
entry(1, "user_message", "A"),
|
||||
entry(2, "assistant_message", "reply A"),
|
||||
entry(6, "user_message", "C"),
|
||||
],
|
||||
retirements: [{ seq: 5, retireFromSeq: 3 }],
|
||||
});
|
||||
|
||||
expect(viewed()).toEqual(["A", "reply A", "C"]);
|
||||
expect(latestRewind()).toEqual({ epoch: "epoch-1", seq: 5 });
|
||||
owner.dispose();
|
||||
});
|
||||
|
||||
function liveRewindOfB(owner: ViewedTimelineOwner, retirement: { seq: number }): void {
|
||||
owner.applyStreamEvent(AGENT_ID, {
|
||||
event: { type: "rewind", retireFromSeq: 3 },
|
||||
seq: retirement.seq,
|
||||
epoch: "epoch-1",
|
||||
timestamp: new Date("2026-08-26T10:00:06.000Z"),
|
||||
});
|
||||
owner.applyStreamEvent(AGENT_ID, {
|
||||
event: {
|
||||
type: "timeline",
|
||||
provider: "codex",
|
||||
item: { type: "user_message", text: "C", messageId: "c" },
|
||||
} as AgentStreamEventPayload,
|
||||
seq: retirement.seq + 1,
|
||||
epoch: "epoch-1",
|
||||
timestamp: new Date("2026-08-26T10:00:07.000Z"),
|
||||
});
|
||||
owner.flushStreamAgent(AGENT_ID);
|
||||
}
|
||||
|
||||
/** A, reply A, B, reply B as a page served before B was rewound. */
|
||||
const pageServedBeforeTheRewind: Parameters<ViewedTimelineOwner["applyTimelineResponse"]>[0] = {
|
||||
...page,
|
||||
direction: "before",
|
||||
hasOlder: false,
|
||||
window: { minSeq: 1, maxSeq: 5, nextSeq: 6 },
|
||||
startCursor: { epoch: "epoch-1", seq: 1 },
|
||||
endCursor: { epoch: "epoch-1", seq: 4 },
|
||||
entries: [
|
||||
entry(1, "user_message", "A"),
|
||||
entry(2, "assistant_message", "reply A"),
|
||||
entry(3, "user_message", "B"),
|
||||
entry(4, "assistant_message", "reply B"),
|
||||
],
|
||||
};
|
||||
|
||||
function loadTheEndOfB(owner: ViewedTimelineOwner): void {
|
||||
owner.applyTimelineResponse({
|
||||
...page,
|
||||
hasOlder: true,
|
||||
window: { minSeq: 1, maxSeq: 5, nextSeq: 6 },
|
||||
startCursor: { epoch: "epoch-1", seq: 5 },
|
||||
endCursor: { epoch: "epoch-1", seq: 5 },
|
||||
entries: [entry(5, "assistant_message", "more of B")],
|
||||
});
|
||||
}
|
||||
|
||||
it("refuses an older page served before the rewind and takes the one served after it", () => {
|
||||
useSessionStore.getState().initializeSession(SERVER_ID, null);
|
||||
const owner = createOwner({ readTimeline: async () => undefined, commitTimeline: () => {} });
|
||||
loadTheEndOfB(owner);
|
||||
liveRewindOfB(owner, { seq: 6 });
|
||||
expect(viewed()).toEqual(["C"]);
|
||||
|
||||
const outcome = owner.applyTimelineResponse(pageServedBeforeTheRewind);
|
||||
expect(viewed()).toEqual(["C"]);
|
||||
expect(outcome).toBe("stale");
|
||||
|
||||
owner.applyTimelineResponse({
|
||||
...pageServedBeforeTheRewind,
|
||||
window: { minSeq: 1, maxSeq: 7, nextSeq: 8 },
|
||||
// Retired rows count as covered, so the page reaches the loaded start.
|
||||
endCursor: { epoch: "epoch-1", seq: 4 },
|
||||
entries: [entry(1, "user_message", "A"), entry(2, "assistant_message", "reply A")],
|
||||
});
|
||||
expect(viewed()).toEqual(["A", "reply A", "C"]);
|
||||
owner.dispose();
|
||||
});
|
||||
|
||||
it("refuses a prompt jump window served before the rewind", () => {
|
||||
useSessionStore.getState().initializeSession(SERVER_ID, null);
|
||||
const owner = createOwner({ readTimeline: async () => undefined, commitTimeline: () => {} });
|
||||
loadTheEndOfB(owner);
|
||||
liveRewindOfB(owner, { seq: 6 });
|
||||
|
||||
const outcome = owner.applyTimelineResponse({
|
||||
...pageServedBeforeTheRewind,
|
||||
mergeWindow: true,
|
||||
});
|
||||
expect(viewed()).toEqual(["C"]);
|
||||
expect(outcome).toBe("stale");
|
||||
owner.dispose();
|
||||
});
|
||||
|
||||
it("refuses a first page served before a rewind that reached the chat while it loaded", () => {
|
||||
useSessionStore.getState().initializeSession(SERVER_ID, null);
|
||||
const owner = createOwner({ readTimeline: async () => undefined, commitTimeline: () => {} });
|
||||
liveRewindOfB(owner, { seq: 5 });
|
||||
|
||||
const outcome = owner.applyTimelineResponse({
|
||||
...pageServedBeforeTheRewind,
|
||||
direction: "tail",
|
||||
window: { minSeq: 1, maxSeq: 4, nextSeq: 5 },
|
||||
});
|
||||
expect(viewed()).toEqual(["C"]);
|
||||
expect(outcome).toBe("stale");
|
||||
|
||||
owner.applyTimelineResponse({
|
||||
...page,
|
||||
window: { minSeq: 1, maxSeq: 6, nextSeq: 7 },
|
||||
startCursor: { epoch: "epoch-1", seq: 1 },
|
||||
endCursor: { epoch: "epoch-1", seq: 6 },
|
||||
entries: [
|
||||
entry(1, "user_message", "A"),
|
||||
entry(2, "assistant_message", "reply A"),
|
||||
{
|
||||
...entry(6, "user_message", "C"),
|
||||
item: { type: "user_message", text: "C", messageId: "c" },
|
||||
},
|
||||
],
|
||||
retirements: [{ seq: 5, retireFromSeq: 3 }],
|
||||
});
|
||||
expect(viewed()).toEqual(["A", "reply A", "C"]);
|
||||
owner.dispose();
|
||||
});
|
||||
});
|
||||
|
||||
describe("turn boundaries", () => {
|
||||
it("commits a turn's final reply before the turn stops running", () => {
|
||||
useSessionStore.getState().initializeSession(SERVER_ID, null);
|
||||
|
||||
@@ -398,7 +398,7 @@ describe("processTimelineResponse", () => {
|
||||
messageId: "provider-message",
|
||||
text: "local prompt",
|
||||
timestamp: new Date(1000),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
|
||||
turnId: "turn-1",
|
||||
});
|
||||
const hello = createUserMessage({
|
||||
@@ -406,7 +406,7 @@ describe("processTimelineResponse", () => {
|
||||
clientMessageId: "hello-client",
|
||||
text: "hello",
|
||||
timestamp: new Date(1500),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
|
||||
turnId: "turn-1",
|
||||
});
|
||||
const currentTail = [canonical, makeAssistantItem("existing tail", "existing-tail"), hello];
|
||||
@@ -456,7 +456,7 @@ describe("processTimelineResponse", () => {
|
||||
id: "stale-history",
|
||||
text: "stale history",
|
||||
timestamp: new Date(1040),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 40 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 40, anchorSeq: 40 },
|
||||
},
|
||||
],
|
||||
currentCursor: { epoch: "epoch-1", startSeq: 1, endSeq: 40 },
|
||||
@@ -484,11 +484,11 @@ describe("processTimelineResponse", () => {
|
||||
const unresolved = makeSubmittedUserMessage("unresolved prompt", "client-unresolved");
|
||||
const coveredLive: StreamItem = {
|
||||
...makeAssistantItem("covered live", "covered-live"),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 235 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 235, anchorSeq: 235 },
|
||||
};
|
||||
const newerLive: StreamItem = {
|
||||
...makeAssistantItem("newer live", "newer-live"),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 245 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 245, anchorSeq: 245 },
|
||||
};
|
||||
|
||||
const result = processTimelineResponse({
|
||||
@@ -573,7 +573,7 @@ describe("processTimelineResponse", () => {
|
||||
expect.objectContaining({
|
||||
kind: "assistant_message",
|
||||
text: "[System Error] failed",
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42 },
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 40 },
|
||||
}),
|
||||
]);
|
||||
});
|
||||
@@ -745,7 +745,7 @@ describe("processTimelineResponse", () => {
|
||||
}).item,
|
||||
} as AgentStreamEventPayload,
|
||||
timestamp: new Date(2000),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
|
||||
},
|
||||
],
|
||||
{ source: "canonical" },
|
||||
@@ -775,7 +775,7 @@ describe("processTimelineResponse", () => {
|
||||
|
||||
expect(getAgentToolCalls([...result.tail, ...result.head])).toEqual([
|
||||
expect.objectContaining({
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 1 },
|
||||
payload: expect.objectContaining({
|
||||
data: expect.objectContaining({ callId, status: "completed" }),
|
||||
}),
|
||||
@@ -796,7 +796,7 @@ describe("processTimelineResponse", () => {
|
||||
},
|
||||
} as AgentStreamEventPayload,
|
||||
timestamp: new Date(2000),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
|
||||
},
|
||||
],
|
||||
{ source: "canonical" },
|
||||
@@ -831,7 +831,7 @@ describe("processTimelineResponse", () => {
|
||||
|
||||
expect([...result.tail, ...result.head].filter((item) => item.kind === "todo_list")).toEqual([
|
||||
expect.objectContaining({
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 1 },
|
||||
items: [{ text: "Verify hydration", completed: true }],
|
||||
}),
|
||||
]);
|
||||
@@ -847,7 +847,7 @@ describe("processTimelineResponse", () => {
|
||||
item: { type: "compaction", status: "completed", trigger: "auto", preTokens: 1200 },
|
||||
} as AgentStreamEventPayload,
|
||||
timestamp: new Date(2000),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
|
||||
},
|
||||
],
|
||||
{ source: "canonical" },
|
||||
@@ -879,7 +879,7 @@ describe("processTimelineResponse", () => {
|
||||
|
||||
expect([...result.tail, ...result.head].filter((item) => item.kind === "compaction")).toEqual([
|
||||
expect.objectContaining({
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 1 },
|
||||
status: "completed",
|
||||
trigger: "auto",
|
||||
preTokens: 1200,
|
||||
@@ -918,7 +918,7 @@ describe("processTimelineResponse", () => {
|
||||
messageId: "assistant-live",
|
||||
text: " continuation",
|
||||
timestamp: new Date(2001),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 101 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 101, anchorSeq: 101 },
|
||||
},
|
||||
],
|
||||
isInitializing: true,
|
||||
@@ -946,7 +946,7 @@ describe("processTimelineResponse", () => {
|
||||
);
|
||||
expect(assistants).toHaveLength(1);
|
||||
expect(assistants[0]?.text).toBe("canonical prefix continuation");
|
||||
expect(assistants[0]?.timelineCursor).toEqual({ epoch: "epoch-1", seq: 101 });
|
||||
expect(assistants[0]?.timelineCursor).toEqual({ epoch: "epoch-1", seq: 101, anchorSeq: 100 });
|
||||
});
|
||||
|
||||
it("keeps assistant segments separate when a live tool sits between them", () => {
|
||||
@@ -963,12 +963,12 @@ describe("processTimelineResponse", () => {
|
||||
}).item,
|
||||
} as AgentStreamEventPayload,
|
||||
timestamp: new Date(2101),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 101 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 101, anchorSeq: 101 },
|
||||
},
|
||||
{
|
||||
event: makeAssistantTimelineEvent("after tool", messageId),
|
||||
timestamp: new Date(2102),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 102 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 102, anchorSeq: 102 },
|
||||
},
|
||||
],
|
||||
{ source: "canonical" },
|
||||
@@ -1019,7 +1019,7 @@ describe("processTimelineResponse", () => {
|
||||
id: "assistant-live",
|
||||
text: "canonical prefix continuation",
|
||||
timestamp: new Date(2001),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 101 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 101, anchorSeq: 101 },
|
||||
},
|
||||
],
|
||||
isInitializing: true,
|
||||
@@ -1038,7 +1038,7 @@ describe("processTimelineResponse", () => {
|
||||
);
|
||||
expect(assistants).toHaveLength(1);
|
||||
expect(assistants[0]?.text).toBe("canonical prefix continuation");
|
||||
expect(assistants[0]?.timelineCursor).toEqual({ epoch: "epoch-1", seq: 101 });
|
||||
expect(assistants[0]?.timelineCursor).toEqual({ epoch: "epoch-1", seq: 101, anchorSeq: 100 });
|
||||
});
|
||||
|
||||
it("keeps a canonical live user row newer than the bootstrap page", () => {
|
||||
@@ -1060,7 +1060,7 @@ describe("processTimelineResponse", () => {
|
||||
});
|
||||
expect(live.head[0]).toMatchObject({
|
||||
kind: "user_message",
|
||||
timelineCursor: { epoch: "epoch-1", seq: 101 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 101, anchorSeq: 101 },
|
||||
});
|
||||
|
||||
const result = processTimelineResponse({
|
||||
@@ -1123,7 +1123,7 @@ describe("processTimelineResponse", () => {
|
||||
kind: "user_message",
|
||||
clientMessageId: "client-message-1",
|
||||
messageId: "provider-message-1",
|
||||
timelineCursor: { epoch: "epoch-1", seq: 51 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 51, anchorSeq: 51 },
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2808,7 +2808,7 @@ describe("processTimelineResponse", () => {
|
||||
id: "newest",
|
||||
text: "newest",
|
||||
timestamp: new Date(1000),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 100 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 100, anchorSeq: 100 },
|
||||
},
|
||||
makeSubmittedUserMessage("pending submission", "pending-submission"),
|
||||
],
|
||||
@@ -2886,14 +2886,14 @@ describe("processTimelineResponse", () => {
|
||||
id: "oldest",
|
||||
text: "oldest",
|
||||
timestamp: new Date(1000),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
|
||||
},
|
||||
{
|
||||
kind: "user_message",
|
||||
id: "newest",
|
||||
text: "newest",
|
||||
timestamp: new Date(100_000),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 100 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 100, anchorSeq: 100 },
|
||||
},
|
||||
];
|
||||
|
||||
@@ -2935,7 +2935,7 @@ describe("processTimelineResponse", () => {
|
||||
id: "newest",
|
||||
text: "newest",
|
||||
timestamp: new Date(100_000),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 100 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 100, anchorSeq: 100 },
|
||||
},
|
||||
...(lane === "tail" ? [pending] : []),
|
||||
],
|
||||
@@ -2976,9 +2976,13 @@ describe("processTimelineResponse", () => {
|
||||
{
|
||||
text: "local pending prompt",
|
||||
messageId: "canonical-message",
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
|
||||
},
|
||||
{
|
||||
text: "newest",
|
||||
messageId: undefined,
|
||||
timelineCursor: { epoch: "epoch-1", seq: 100, anchorSeq: 100 },
|
||||
},
|
||||
{ text: "newest", messageId: undefined, timelineCursor: { epoch: "epoch-1", seq: 100 } },
|
||||
],
|
||||
head: [],
|
||||
acknowledgedClientMessageIds: [clientMessageId],
|
||||
@@ -2992,7 +2996,7 @@ describe("processTimelineResponse", () => {
|
||||
{
|
||||
event: makeToolCallTimelineEvent("call-1"),
|
||||
timestamp: new Date(500),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 500 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 500, anchorSeq: 500 },
|
||||
},
|
||||
],
|
||||
{ source: "canonical" },
|
||||
@@ -3038,7 +3042,7 @@ describe("processTimelineResponse", () => {
|
||||
{
|
||||
callId: "call-1",
|
||||
status: "completed",
|
||||
timelineCursor: { epoch: "epoch-1", seq: 500 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 500, anchorSeq: 1 },
|
||||
},
|
||||
]);
|
||||
});
|
||||
@@ -3050,7 +3054,7 @@ describe("processTimelineResponse", () => {
|
||||
...makeAssistantItem("projected response", "loaded-assistant"),
|
||||
messageId: "assistant-message",
|
||||
timestamp,
|
||||
timelineCursor: { epoch: "epoch-1", seq: 500 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 500, anchorSeq: 500 },
|
||||
},
|
||||
];
|
||||
const result = processTimelineResponse({
|
||||
@@ -3100,7 +3104,7 @@ describe("processTimelineResponse", () => {
|
||||
id: "loaded-assistant",
|
||||
text: "projected response",
|
||||
messageId: "assistant-message",
|
||||
timelineCursor: { epoch: "epoch-1", seq: 500 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 500, anchorSeq: 1 },
|
||||
},
|
||||
]);
|
||||
});
|
||||
@@ -3112,7 +3116,7 @@ describe("processTimelineResponse", () => {
|
||||
id: "current-200",
|
||||
text: "current-200",
|
||||
timestamp: new Date(3200),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 200 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 200, anchorSeq: 200 },
|
||||
},
|
||||
];
|
||||
const existingCursor: TimelineCursor = {
|
||||
@@ -3219,7 +3223,7 @@ describe("processTimelineResponse", () => {
|
||||
const currentTail = [
|
||||
{
|
||||
...makeAssistantItem("newer chunk", "assistant-newer"),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 3 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 3, anchorSeq: 3 },
|
||||
},
|
||||
];
|
||||
const existingCursor: TimelineCursor = {
|
||||
@@ -3246,7 +3250,7 @@ describe("processTimelineResponse", () => {
|
||||
expect(result.tail[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
id: "assistant-newer",
|
||||
timelineCursor: { epoch: "epoch-1", seq: 3 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 3, anchorSeq: 3 },
|
||||
}),
|
||||
);
|
||||
expect(result.cursor).toEqual({
|
||||
@@ -3686,7 +3690,7 @@ describe("processAgentStreamEvent", () => {
|
||||
expect.objectContaining({
|
||||
kind: "assistant_message",
|
||||
text: "[System Error] failed",
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42 },
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
|
||||
}),
|
||||
]);
|
||||
});
|
||||
@@ -3933,7 +3937,7 @@ describe("processAgentStreamEvent", () => {
|
||||
expect(getUserTexts(result.head)).toEqual(["live before bootstrap"]);
|
||||
expect(result.head[0]).toMatchObject({
|
||||
kind: "user_message",
|
||||
timelineCursor: { epoch: "epoch-1", seq: 51 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 51, anchorSeq: 51 },
|
||||
});
|
||||
expect(result.cursorChanged).toBe(false);
|
||||
expect(result.cursor).toBeNull();
|
||||
@@ -3968,7 +3972,7 @@ describe("processAgentStreamEvent", () => {
|
||||
clientMessageId: "client-message-1",
|
||||
messageId: "provider-message-1",
|
||||
text: "submitted before bootstrap",
|
||||
timelineCursor: { epoch: "epoch-1", seq: 51 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 51, anchorSeq: 51 },
|
||||
}),
|
||||
]);
|
||||
});
|
||||
@@ -4559,6 +4563,279 @@ describe("createAgentStreamReducerQueue", () => {
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Conversation rewind: A, B, rewind B, C
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("conversation rewind", () => {
|
||||
const rewindB = { seq: 5, retireFromSeq: 3 };
|
||||
|
||||
function loadAB(): { tail: StreamItem[]; head: StreamItem[]; cursor: TimelineCursor } {
|
||||
const result = processTimelineResponse({
|
||||
...baseTimelineInput,
|
||||
isInitializing: true,
|
||||
hasActiveInitDeferred: true,
|
||||
payload: {
|
||||
...baseTimelineInput.payload,
|
||||
direction: "tail",
|
||||
window: { minSeq: 1, maxSeq: 4, nextSeq: 5 },
|
||||
startCursor: { seq: 1 },
|
||||
endCursor: { seq: 4 },
|
||||
entries: [
|
||||
makeTimelineEntry(1, "A", "user_message"),
|
||||
makeTimelineEntry(2, "reply A"),
|
||||
makeTimelineEntry(3, "B", "user_message"),
|
||||
makeTimelineEntry(4, "reply B"),
|
||||
],
|
||||
},
|
||||
});
|
||||
if (!result.cursor) throw new Error("expected a loaded range");
|
||||
return { tail: result.tail, head: result.head, cursor: result.cursor };
|
||||
}
|
||||
|
||||
function live(
|
||||
state: { tail: StreamItem[]; head: StreamItem[]; cursor: TimelineCursor },
|
||||
events: AgentStreamReducerEvent[],
|
||||
) {
|
||||
const result = processAgentStreamEvents({
|
||||
events,
|
||||
currentTail: state.tail,
|
||||
currentHead: state.head,
|
||||
currentCursor: state.cursor,
|
||||
hasAuthoritativeBaseline: true,
|
||||
});
|
||||
return {
|
||||
tail: result.tail,
|
||||
head: result.head,
|
||||
cursor: result.cursor ?? state.cursor,
|
||||
sideEffects: result.sideEffects,
|
||||
};
|
||||
}
|
||||
|
||||
function rewindEvent(retirement: { seq: number; retireFromSeq: number }) {
|
||||
return {
|
||||
event: { type: "rewind" as const, retireFromSeq: retirement.retireFromSeq },
|
||||
seq: retirement.seq,
|
||||
epoch: "epoch-1",
|
||||
timestamp: new Date(1000 + retirement.seq),
|
||||
};
|
||||
}
|
||||
|
||||
const promptC = [
|
||||
makeStreamReducerEvent(makeTimelineEvent("C", "user_message"), 6),
|
||||
makeStreamReducerEvent(makeTimelineEvent("reply C"), 7),
|
||||
];
|
||||
|
||||
function conversation(state: { tail: StreamItem[]; head: StreamItem[] }) {
|
||||
return [...state.tail, ...state.head].map((item) =>
|
||||
item.kind === "user_message" || item.kind === "assistant_message" ? item.text : item.kind,
|
||||
);
|
||||
}
|
||||
|
||||
it("retires B in place, keeps A mounted, and shows C once", () => {
|
||||
const loaded = loadAB();
|
||||
const [promptA, replyA] = loaded.tail;
|
||||
|
||||
const rewound = live(loaded, [rewindEvent(rewindB), ...promptC]);
|
||||
|
||||
expect(conversation(rewound)).toEqual(["A", "reply A", "C", "reply C"]);
|
||||
expect(rewound.tail[0]).toBe(promptA);
|
||||
expect(rewound.tail[1]).toBe(replyA);
|
||||
expect(rewound.cursor).toMatchObject({ epoch: "epoch-1", startSeq: 1, endSeq: 7 });
|
||||
expect(rewound.sideEffects).toEqual([]);
|
||||
});
|
||||
|
||||
it("ignores a duplicate rewind so C is not retired", () => {
|
||||
const rewound = live(loadAB(), [rewindEvent(rewindB), ...promptC]);
|
||||
|
||||
const replayed = live(rewound, [rewindEvent(rewindB)]);
|
||||
|
||||
expect(conversation(replayed)).toEqual(["A", "reply A", "C", "reply C"]);
|
||||
expect(replayed.cursor.endSeq).toBe(7);
|
||||
});
|
||||
|
||||
it("does not let an old page resurrect B after the rewind applied", () => {
|
||||
const rewound = live(loadAB(), [rewindEvent(rewindB), ...promptC]);
|
||||
|
||||
const stale = processTimelineResponse({
|
||||
...baseTimelineInput,
|
||||
currentTail: rewound.tail,
|
||||
currentHead: rewound.head,
|
||||
currentCursor: rewound.cursor,
|
||||
payload: {
|
||||
...baseTimelineInput.payload,
|
||||
direction: "after",
|
||||
window: { minSeq: 1, maxSeq: 4, nextSeq: 5 },
|
||||
startCursor: { seq: 3 },
|
||||
endCursor: { seq: 4 },
|
||||
entries: [makeTimelineEntry(3, "B", "user_message"), makeTimelineEntry(4, "reply B")],
|
||||
},
|
||||
});
|
||||
|
||||
expect(conversation(stale)).toEqual(["A", "reply A", "C", "reply C"]);
|
||||
expect(stale.cursorChanged).toBe(false);
|
||||
});
|
||||
|
||||
it("drops a late live delivery for the retired range", () => {
|
||||
const rewound = live(loadAB(), [rewindEvent(rewindB)]);
|
||||
|
||||
const late = live(rewound, [makeStreamReducerEvent(makeTimelineEvent("late B"), 4)]);
|
||||
|
||||
expect(conversation(late)).toEqual(["A", "reply A"]);
|
||||
});
|
||||
|
||||
it("catches up through a page that only carries the retirement", () => {
|
||||
const loaded = loadAB();
|
||||
|
||||
const caughtUp = processTimelineResponse({
|
||||
...baseTimelineInput,
|
||||
currentTail: loaded.tail,
|
||||
currentHead: loaded.head,
|
||||
currentCursor: loaded.cursor,
|
||||
payload: {
|
||||
...baseTimelineInput.payload,
|
||||
direction: "after",
|
||||
window: { minSeq: 1, maxSeq: 5, nextSeq: 6 },
|
||||
startCursor: { seq: 5 },
|
||||
endCursor: { seq: 5 },
|
||||
entries: [],
|
||||
retirements: [rewindB],
|
||||
},
|
||||
});
|
||||
if (!caughtUp.cursor) throw new Error("expected a loaded range");
|
||||
|
||||
expect(conversation(caughtUp)).toEqual(["A", "reply A"]);
|
||||
expect(caughtUp.cursor.endSeq).toBe(5);
|
||||
expect(caughtUp.sideEffects).not.toContainEqual(expect.objectContaining({ type: "catch_up" }));
|
||||
|
||||
const continued = live({ ...caughtUp, cursor: caughtUp.cursor }, promptC);
|
||||
expect(conversation(continued)).toEqual(["A", "reply A", "C", "reply C"]);
|
||||
});
|
||||
|
||||
it("converges after reconnect from a resume page that crosses the rewind", () => {
|
||||
const loaded = loadAB();
|
||||
|
||||
const resumed = processTimelineResponse({
|
||||
...baseTimelineInput,
|
||||
currentTail: loaded.tail,
|
||||
currentHead: loaded.head,
|
||||
currentCursor: loaded.cursor,
|
||||
payload: {
|
||||
...baseTimelineInput.payload,
|
||||
direction: "tail",
|
||||
window: { minSeq: 1, maxSeq: 7, nextSeq: 8 },
|
||||
startCursor: { seq: 1 },
|
||||
endCursor: { seq: 7 },
|
||||
entries: [
|
||||
makeTimelineEntry(1, "A", "user_message"),
|
||||
makeTimelineEntry(2, "reply A"),
|
||||
makeTimelineEntry(6, "C", "user_message"),
|
||||
makeTimelineEntry(7, "reply C"),
|
||||
],
|
||||
retirements: [rewindB],
|
||||
},
|
||||
});
|
||||
|
||||
expect(conversation(resumed)).toEqual(["A", "reply A", "C", "reply C"]);
|
||||
expect(resumed.tail[0]).toBe(loaded.tail[0]);
|
||||
expect(resumed.cursor).toMatchObject({ endSeq: 7 });
|
||||
});
|
||||
|
||||
it("recovers a rewind that skips past the loaded end", () => {
|
||||
const loaded = loadAB();
|
||||
|
||||
const gapped = live(loaded, [rewindEvent({ seq: 9, retireFromSeq: 3 })]);
|
||||
|
||||
expect(conversation(gapped)).toEqual(["A", "reply A", "B", "reply B"]);
|
||||
expect(gapped.sideEffects).toEqual([
|
||||
{ type: "catch_up", cursor: { epoch: "epoch-1", endSeq: 4 } },
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps an A row whose late update carries a seq inside B's range", () => {
|
||||
const loaded = loadAB();
|
||||
const [promptA, replyA, ...rest] = loaded.tail;
|
||||
const lateTool = hydrateStreamState(
|
||||
[
|
||||
{
|
||||
event: makeToolCallTimelineEvent("call-a"),
|
||||
timestamp: new Date(1002),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 4, anchorSeq: 2 },
|
||||
},
|
||||
],
|
||||
{ source: "canonical" },
|
||||
);
|
||||
const state = { ...loaded, tail: [promptA, replyA, ...lateTool, ...rest] };
|
||||
|
||||
const rewound = live(state, [rewindEvent(rewindB)]);
|
||||
|
||||
expect(conversation(rewound)).toEqual(["A", "reply A", "tool_call"]);
|
||||
});
|
||||
|
||||
it("keeps a tool that started before B when B's prompt is not loaded and the tool updated after B", () => {
|
||||
const toolA = {
|
||||
...makeToolCallTimelineEntry(2, "call-a", "completed", {
|
||||
type: "read",
|
||||
filePath: "/tmp/a.ts",
|
||||
}),
|
||||
seqEnd: 6,
|
||||
sourceSeqRanges: [
|
||||
{ startSeq: 2, endSeq: 2 },
|
||||
{ startSeq: 6, endSeq: 6 },
|
||||
],
|
||||
};
|
||||
const loaded = processTimelineResponse({
|
||||
...baseTimelineInput,
|
||||
isInitializing: true,
|
||||
hasActiveInitDeferred: true,
|
||||
payload: {
|
||||
...baseTimelineInput.payload,
|
||||
direction: "tail",
|
||||
window: { minSeq: 1, maxSeq: 6, nextSeq: 7 },
|
||||
startCursor: { seq: 1 },
|
||||
endCursor: { seq: 6 },
|
||||
entries: [makeTimelineEntry(1, "A", "user_message"), toolA],
|
||||
},
|
||||
});
|
||||
if (!loaded.cursor) throw new Error("expected a loaded range");
|
||||
|
||||
const rewound = live({ tail: loaded.tail, head: loaded.head, cursor: loaded.cursor }, [
|
||||
rewindEvent({ seq: 7, retireFromSeq: 3 }),
|
||||
]);
|
||||
|
||||
expect(conversation(rewound)).toEqual(["A", "tool_call"]);
|
||||
});
|
||||
|
||||
it("keeps C from the live overlay when the first page brings the retirement C followed", () => {
|
||||
const overlay = processAgentStreamEvents({
|
||||
events: [rewindEvent(rewindB), ...promptC],
|
||||
currentTail: [],
|
||||
currentHead: [],
|
||||
currentCursor: undefined,
|
||||
hasAuthoritativeBaseline: false,
|
||||
});
|
||||
|
||||
const initialized = processTimelineResponse({
|
||||
...baseTimelineInput,
|
||||
isInitializing: true,
|
||||
hasActiveInitDeferred: true,
|
||||
currentTail: overlay.tail,
|
||||
currentHead: overlay.head,
|
||||
payload: {
|
||||
...baseTimelineInput.payload,
|
||||
direction: "tail",
|
||||
window: { minSeq: 1, maxSeq: 5, nextSeq: 6 },
|
||||
startCursor: { seq: 1 },
|
||||
endCursor: { seq: 5 },
|
||||
entries: [makeTimelineEntry(1, "A", "user_message"), makeTimelineEntry(2, "reply A")],
|
||||
retirements: [rewindB],
|
||||
},
|
||||
});
|
||||
|
||||
expect(conversation(initialized)).toEqual(["A", "reply A", "C", "reply C"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("turn metrics", () => {
|
||||
const metrics = [
|
||||
{ label: "Model", value: "opus" },
|
||||
@@ -4816,4 +5093,30 @@ describe("turn metrics", () => {
|
||||
|
||||
expect(repeated.tail).toBe(first.tail);
|
||||
});
|
||||
|
||||
it("stamps turn metrics carried on a live timeline event appended by reload", () => {
|
||||
const result = processAgentStreamEvents({
|
||||
events: [
|
||||
makeStreamReducerEvent(makeTimelineEvent("question", "user_message"), 1),
|
||||
makeStreamReducerEvent(
|
||||
{
|
||||
type: "timeline",
|
||||
provider: "claude",
|
||||
item: { type: "assistant_message", text: "Appended reply." },
|
||||
turnMetrics: metrics,
|
||||
},
|
||||
2,
|
||||
),
|
||||
],
|
||||
currentTail: [],
|
||||
currentHead: [],
|
||||
currentCursor: { epoch: "epoch-1", startSeq: 0, endSeq: 0 },
|
||||
hasAuthoritativeBaseline: true,
|
||||
});
|
||||
|
||||
expect(metricsByKind([...result.tail, ...result.head])).toEqual([
|
||||
{ kind: "user_message", turnMetrics: undefined },
|
||||
{ kind: "assistant_message", turnMetrics: metrics },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
import type { AgentMetric, AgentTimelineItem } from "@getpaseo/protocol/agent-types";
|
||||
import type { AgentStreamEventPayload } from "@getpaseo/protocol/messages";
|
||||
import { selectAgentTimelineState, useSessionStore } from "@/stores/session-store";
|
||||
import type { AssistantMessageItem, StreamItem, TodoEntry } from "@/types/stream";
|
||||
import {
|
||||
advanceTimelinePosition,
|
||||
type AssistantMessageItem,
|
||||
type StreamItem,
|
||||
type TimelinePosition,
|
||||
type TodoEntry,
|
||||
} from "@/types/stream";
|
||||
import type { TurnLivenessTransition } from "@/timeline/turn-liveness";
|
||||
import { stampTimelineTurnMetrics } from "@/timeline/turn-metrics";
|
||||
import {
|
||||
@@ -72,6 +78,64 @@ interface TimelineSeqRange {
|
||||
endSeq: number;
|
||||
}
|
||||
|
||||
/** A conversation rewind took the rows anchored in `[retireFromSeq, seq)` out of the conversation. */
|
||||
export interface TimelineRetirement {
|
||||
seq: number;
|
||||
retireFromSeq: number;
|
||||
}
|
||||
|
||||
/** The live form of a retirement; it is sequenced with the stream events around it. */
|
||||
export interface TimelineRewindEvent {
|
||||
type: "rewind";
|
||||
retireFromSeq: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Drops the rows a retirement took out of the conversation: those anchored in
|
||||
* `[retireFromSeq, seq)`. Anchors do not move on update, so an earlier row updated after the
|
||||
* rewound prompt stays, and a row that started after the retirement stays. Items without a
|
||||
* timeline position are local sends the daemon has not echoed and stay.
|
||||
*/
|
||||
function retireRewoundStreamItems(input: {
|
||||
tail: StreamItem[];
|
||||
head: StreamItem[];
|
||||
epoch: string;
|
||||
retirement: TimelineRetirement;
|
||||
}): { tail: StreamItem[]; head: StreamItem[] } {
|
||||
const { tail, head, epoch, retirement } = input;
|
||||
const isRetired = (item: StreamItem) => {
|
||||
const position = item.timelineCursor;
|
||||
return (
|
||||
position?.epoch === epoch &&
|
||||
position.anchorSeq >= retirement.retireFromSeq &&
|
||||
position.anchorSeq < retirement.seq
|
||||
);
|
||||
};
|
||||
const nextTail = tail.filter((item) => !isRetired(item));
|
||||
const nextHead = head.filter((item) => !isRetired(item));
|
||||
return {
|
||||
tail: nextTail.length === tail.length ? tail : nextTail,
|
||||
head: nextHead.length === head.length ? head : nextHead,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a page's retirements to what this client holds. The page's own entries are already
|
||||
* active. Applying a retirement twice changes nothing, since its range is bounded.
|
||||
*/
|
||||
function retireForPage(input: {
|
||||
payload: ProcessTimelineResponseInput["payload"];
|
||||
tail: StreamItem[];
|
||||
head: StreamItem[];
|
||||
}): { tail: StreamItem[]; head: StreamItem[] } {
|
||||
const { payload } = input;
|
||||
let held = { tail: input.tail, head: input.head };
|
||||
for (const retirement of payload.retirements ?? []) {
|
||||
held = retireRewoundStreamItems({ ...held, epoch: payload.epoch, retirement });
|
||||
}
|
||||
return held;
|
||||
}
|
||||
|
||||
function mergeTimelineCoverage(
|
||||
current: TimelineCursor,
|
||||
added: TimelineLoadedRange,
|
||||
@@ -152,6 +216,7 @@ export interface ProcessTimelineResponseInput {
|
||||
hasNewer: boolean;
|
||||
hasOlder: boolean;
|
||||
mergeWindow?: boolean;
|
||||
retirements?: TimelineRetirement[];
|
||||
};
|
||||
currentTail: StreamItem[];
|
||||
currentHead: StreamItem[];
|
||||
@@ -396,7 +461,7 @@ function mergeTimelineWindow(args: {
|
||||
toHydratedEvents: (units: TimelineUnit[]) => Array<{
|
||||
event: AgentStreamEventPayload;
|
||||
timestamp: Date;
|
||||
timelineCursor: { epoch: string; seq: number };
|
||||
timelineCursor: TimelinePosition;
|
||||
}>;
|
||||
}): TimelinePathResult {
|
||||
const { timelineUnits, payload, currentTail, currentHead, currentCursor, toHydratedEvents } =
|
||||
@@ -760,7 +825,7 @@ function replaceLiveAssistantWithProjectedText(params: {
|
||||
head: StreamItem[];
|
||||
event: AgentStreamEventPayload;
|
||||
timestamp: Date;
|
||||
timelineCursor: { epoch: string; seq: number };
|
||||
timelineCursor: TimelinePosition;
|
||||
}): StreamItem[] | null {
|
||||
const { head, event, timestamp, timelineCursor } = params;
|
||||
if (event.type !== "timeline" || event.item.type !== "assistant_message") {
|
||||
@@ -779,7 +844,7 @@ function replaceLiveAssistantWithProjectedText(params: {
|
||||
...current,
|
||||
text: event.item.text,
|
||||
timestamp,
|
||||
timelineCursor,
|
||||
...advanceTimelinePosition(current.timelineCursor, timelineCursor),
|
||||
};
|
||||
return next;
|
||||
}
|
||||
@@ -829,7 +894,7 @@ function reconcileOverlappingProjectedAssistant(params: {
|
||||
...(messageId !== undefined ? { messageId } : {}),
|
||||
text: projectedText,
|
||||
timestamp: unit.timestamp,
|
||||
timelineCursor: { epoch: params.epoch, seq: unit.seqEnd },
|
||||
timelineCursor: { epoch: params.epoch, seq: unit.seqEnd, anchorSeq: unit.seq },
|
||||
};
|
||||
const replaceMatch = (items: StreamItem[], index: number) => {
|
||||
const next = [...items];
|
||||
@@ -946,8 +1011,8 @@ function applyCanonicalForwardUnit(params: {
|
||||
unit: TimelineUnit;
|
||||
epoch: string;
|
||||
}): { tail: StreamItem[]; head: StreamItem[]; acknowledgedClientMessageIds: string[] } {
|
||||
const { event, timestamp, seqEnd } = params.unit;
|
||||
const timelineCursor = { epoch: params.epoch, seq: seqEnd };
|
||||
const { event, timestamp, seq, seqEnd } = params.unit;
|
||||
const timelineCursor: TimelinePosition = { epoch: params.epoch, seq: seqEnd, anchorSeq: seq };
|
||||
if (event.type === "timeline" && event.item.type === "user_message") {
|
||||
const applied = applyStreamEvent({
|
||||
tail: params.tail,
|
||||
@@ -1146,10 +1211,10 @@ function applyAcceptedTimelinePage(input: {
|
||||
});
|
||||
}
|
||||
const olderTail = hydrateStreamState(
|
||||
acceptedUnits.map(({ event, timestamp, seqEnd }) => ({
|
||||
acceptedUnits.map(({ event, timestamp, seq, seqEnd }) => ({
|
||||
event,
|
||||
timestamp,
|
||||
timelineCursor: { epoch: payload.epoch, seq: seqEnd },
|
||||
timelineCursor: { epoch: payload.epoch, seq: seqEnd, anchorSeq: seq },
|
||||
})),
|
||||
{
|
||||
source: "canonical",
|
||||
@@ -1181,7 +1246,12 @@ function applyTimelineIncrementalPath(args: {
|
||||
let cursorChanged = false;
|
||||
const sideEffects: TimelineReducerSideEffect[] = [];
|
||||
|
||||
if (timelineUnits.length === 0 && payload.direction !== "before") {
|
||||
// A forward page of retirements alone still advances the loaded end.
|
||||
if (
|
||||
timelineUnits.length === 0 &&
|
||||
payload.direction !== "before" &&
|
||||
(payload.retirements?.length ?? 0) === 0
|
||||
) {
|
||||
return {
|
||||
tail: currentTail,
|
||||
head: currentHead,
|
||||
@@ -1239,8 +1309,6 @@ export function processTimelineResponse(
|
||||
): ProcessTimelineResponseOutput {
|
||||
const {
|
||||
payload,
|
||||
currentTail,
|
||||
currentHead,
|
||||
currentCursor,
|
||||
isInitializing,
|
||||
hasActiveInitDeferred,
|
||||
@@ -1254,8 +1322,8 @@ export function processTimelineResponse(
|
||||
if (payload.error) {
|
||||
return {
|
||||
commit: "apply",
|
||||
tail: currentTail,
|
||||
head: currentHead,
|
||||
tail: input.currentTail,
|
||||
head: input.currentHead,
|
||||
cursor: currentCursor,
|
||||
cursorChanged: false,
|
||||
older: "unchanged",
|
||||
@@ -1267,6 +1335,13 @@ export function processTimelineResponse(
|
||||
};
|
||||
}
|
||||
|
||||
// Entries are already free of retired rows; the retirements apply to what this client holds.
|
||||
const { tail: currentTail, head: currentHead } = retireForPage({
|
||||
payload,
|
||||
tail: input.currentTail,
|
||||
head: input.currentHead,
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Convert entries to timeline units
|
||||
// ------------------------------------------------------------------
|
||||
@@ -1292,12 +1367,12 @@ export function processTimelineResponse(
|
||||
): Array<{
|
||||
event: AgentStreamEventPayload;
|
||||
timestamp: Date;
|
||||
timelineCursor: { epoch: string; seq: number };
|
||||
timelineCursor: TimelinePosition;
|
||||
}> =>
|
||||
units.map(({ event, timestamp, seqEnd }) => ({
|
||||
units.map(({ event, timestamp, seq, seqEnd }) => ({
|
||||
event,
|
||||
timestamp,
|
||||
timelineCursor: { epoch: payload.epoch, seq: seqEnd },
|
||||
timelineCursor: { epoch: payload.epoch, seq: seqEnd, anchorSeq: seq },
|
||||
}));
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
@@ -1432,7 +1507,7 @@ export function processTimelineResponse(
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface ProcessAgentStreamEventInput {
|
||||
event: AgentStreamEventPayload;
|
||||
event: AgentStreamEventPayload | TimelineRewindEvent;
|
||||
seq: number | undefined;
|
||||
epoch: string | undefined;
|
||||
currentTail: StreamItem[];
|
||||
@@ -1455,7 +1530,7 @@ export interface ProcessAgentStreamEventOutput {
|
||||
}
|
||||
|
||||
export interface AgentStreamReducerEvent {
|
||||
event: AgentStreamEventPayload;
|
||||
event: AgentStreamEventPayload | TimelineRewindEvent;
|
||||
seq: number | undefined;
|
||||
epoch: string | undefined;
|
||||
timestamp: Date;
|
||||
@@ -1573,11 +1648,70 @@ function processTimelineSequencingGate(input: {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a live rewind in sequence with the stream. One that does not follow the loaded end is
|
||||
* stale (already applied, or older than a page this client took) or leaves a gap to catch up.
|
||||
*/
|
||||
function processTimelineRewind(
|
||||
input: ProcessAgentStreamEventInput & { event: TimelineRewindEvent },
|
||||
): ProcessAgentStreamEventOutput {
|
||||
const { event, seq, epoch, currentTail, currentHead, currentCursor } = input;
|
||||
const unchanged: ProcessAgentStreamEventOutput = {
|
||||
tail: currentTail,
|
||||
head: currentHead,
|
||||
changedTail: false,
|
||||
changedHead: false,
|
||||
cursor: null,
|
||||
cursorChanged: false,
|
||||
acknowledgedClientMessageIds: [],
|
||||
sideEffects: [],
|
||||
};
|
||||
if (seq === undefined || epoch === undefined) return unchanged;
|
||||
const decision =
|
||||
input.hasAuthoritativeBaseline === false
|
||||
? "overlay"
|
||||
: classifySessionTimelineSeq({
|
||||
cursor: currentCursor
|
||||
? { epoch: currentCursor.epoch, endSeq: currentCursor.endSeq }
|
||||
: null,
|
||||
epoch,
|
||||
seq,
|
||||
});
|
||||
if (decision === "gap" && currentCursor) {
|
||||
return {
|
||||
...unchanged,
|
||||
sideEffects: [
|
||||
{ type: "catch_up", cursor: { epoch: currentCursor.epoch, endSeq: currentCursor.endSeq } },
|
||||
],
|
||||
};
|
||||
}
|
||||
if (decision !== "accept" && decision !== "init" && decision !== "overlay") return unchanged;
|
||||
const retired = retireRewoundStreamItems({
|
||||
tail: currentTail,
|
||||
head: currentHead,
|
||||
epoch,
|
||||
retirement: { seq, retireFromSeq: event.retireFromSeq },
|
||||
});
|
||||
let cursor: TimelineCursor | null = null;
|
||||
if (decision === "accept" && currentCursor) cursor = { ...currentCursor, endSeq: seq };
|
||||
if (decision === "init") cursor = { epoch, startSeq: seq, endSeq: seq };
|
||||
return {
|
||||
...unchanged,
|
||||
tail: retired.tail,
|
||||
head: retired.head,
|
||||
changedTail: retired.tail !== currentTail,
|
||||
changedHead: retired.head !== currentHead,
|
||||
cursor,
|
||||
cursorChanged: cursor !== null,
|
||||
};
|
||||
}
|
||||
|
||||
export function processAgentStreamEvent(
|
||||
input: ProcessAgentStreamEventInput,
|
||||
): ProcessAgentStreamEventOutput {
|
||||
const event = input.event;
|
||||
if (event.type === "rewind") return processTimelineRewind({ ...input, event });
|
||||
const {
|
||||
event,
|
||||
seq,
|
||||
epoch,
|
||||
currentTail,
|
||||
@@ -1596,7 +1730,7 @@ export function processAgentStreamEvent(
|
||||
});
|
||||
const timelineCursor =
|
||||
event.type === "timeline" && seq !== undefined && epoch !== undefined
|
||||
? { epoch, seq }
|
||||
? { epoch, seq, anchorSeq: seq }
|
||||
: undefined;
|
||||
// ------------------------------------------------------------------
|
||||
// Apply stream event to tail/head
|
||||
@@ -1910,6 +2044,10 @@ export function createSessionAgentStreamReducerQueue(
|
||||
};
|
||||
},
|
||||
commit: (agentId, result, events) => {
|
||||
for (const { event, seq, epoch } of events) {
|
||||
if (event.type !== "rewind" || seq === undefined || epoch === undefined) continue;
|
||||
useSessionStore.getState().recordAgentTimelineRewind(serverId, agentId, { epoch, seq });
|
||||
}
|
||||
if (
|
||||
result.changedTail ||
|
||||
result.changedHead ||
|
||||
|
||||
@@ -237,6 +237,13 @@ function commitProcessedTimeline(input: {
|
||||
const agentId = payload.agentId;
|
||||
const store = useSessionStore.getState();
|
||||
if (result.commit !== "discard") {
|
||||
const latestRewindSeq = Math.max(...(payload.retirements ?? []).map(({ seq }) => seq));
|
||||
if (Number.isFinite(latestRewindSeq)) {
|
||||
store.recordAgentTimelineRewind(serverId, agentId, {
|
||||
epoch: payload.epoch,
|
||||
seq: latestRewindSeq,
|
||||
});
|
||||
}
|
||||
store.applyAgentTimelineResponseState(serverId, agentId, {
|
||||
items: result.tail,
|
||||
head: result.head,
|
||||
@@ -457,8 +464,14 @@ export type ViewedTimelineOwnerPorts = Omit<
|
||||
| "applyCurrentTimeline"
|
||||
>;
|
||||
|
||||
/**
|
||||
* `stale`: the page was served before a rewind this client already applied, so it can hold rows
|
||||
* that rewind retired. Nothing was applied; request the page again.
|
||||
*/
|
||||
export type TimelineResponseOutcome = "applied" | "stale";
|
||||
|
||||
export interface ViewedTimelineOwner extends ViewedTimelineSync {
|
||||
applyTimelineResponse(payload: TimelineResponsePayload): void;
|
||||
applyTimelineResponse(payload: TimelineResponsePayload): TimelineResponseOutcome;
|
||||
/**
|
||||
* Accepts one live stream event. Content is coalesced to the next frame; a turn boundary
|
||||
* commits the turn's queued content before its liveness changes, so the view never shows
|
||||
@@ -468,6 +481,37 @@ export interface ViewedTimelineOwner extends ViewedTimelineSync {
|
||||
flushStreamAgent(agentId: string): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* The latest retirement each chat has seen, live or on a page. Tail, older and prompt-jump pages
|
||||
* are served from active rows at one moment; one served before that retirement can still hold the
|
||||
* rows it retired, and has no retirement to drop them with. Forward pages are sequenced against
|
||||
* the loaded end instead, so they are never stale here.
|
||||
*/
|
||||
function createRetirementHighWater() {
|
||||
const latest = new Map<string, { epoch: string; seq: number }>();
|
||||
function note(agentId: string, retirement: { epoch: string; seq: number }): void {
|
||||
const current = latest.get(agentId);
|
||||
if (current?.epoch === retirement.epoch && current.seq >= retirement.seq) return;
|
||||
latest.set(agentId, retirement);
|
||||
}
|
||||
return {
|
||||
note,
|
||||
notePage(payload: TimelineResponsePayload): void {
|
||||
for (const retirement of payload.retirements ?? []) {
|
||||
note(payload.agentId, { epoch: payload.epoch, seq: retirement.seq });
|
||||
}
|
||||
},
|
||||
servedBefore(payload: TimelineResponsePayload): boolean {
|
||||
const known = latest.get(payload.agentId);
|
||||
return (
|
||||
payload.direction !== "after" &&
|
||||
known?.epoch === payload.epoch &&
|
||||
payload.window.maxSeq < known.seq
|
||||
);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function createViewedTimelineOwner(input: {
|
||||
serverId: string;
|
||||
replica: TimelineReplica;
|
||||
@@ -477,6 +521,7 @@ export function createViewedTimelineOwner(input: {
|
||||
ports: ViewedTimelineOwnerPorts;
|
||||
}): ViewedTimelineOwner {
|
||||
const forcedTailReplacements = new Set<string>();
|
||||
const retirements = createRetirementHighWater();
|
||||
const sync = createViewedTimelineSync({
|
||||
...input.ports,
|
||||
fetchLatestTail: async (agentId) => {
|
||||
@@ -517,6 +562,8 @@ export function createViewedTimelineOwner(input: {
|
||||
return {
|
||||
...sync,
|
||||
applyTimelineResponse(receivedPayload) {
|
||||
if (retirements.servedBefore(receivedPayload)) return "stale";
|
||||
retirements.notePage(receivedPayload);
|
||||
const payload = consumeForcedTimelineTailReplacement(receivedPayload, forcedTailReplacements);
|
||||
const accepted = applyAuthoritativeTimelineResponse({
|
||||
serverId: input.serverId,
|
||||
@@ -526,8 +573,12 @@ export function createViewedTimelineOwner(input: {
|
||||
drainQueuedAgentMessage: input.drainQueuedAgentMessage,
|
||||
});
|
||||
if (accepted) input.replica.timelineUpdated(payload.agentId);
|
||||
return "applied";
|
||||
},
|
||||
applyStreamEvent(agentId, event) {
|
||||
if (event.event.type === "rewind" && event.epoch !== undefined && event.seq !== undefined) {
|
||||
retirements.note(agentId, { epoch: event.epoch, seq: event.seq });
|
||||
}
|
||||
streamQueue.enqueue(agentId, event);
|
||||
const turnLiveness = deriveAgentStreamTurnLiveness([event]);
|
||||
if (turnLiveness.length === 0) return;
|
||||
|
||||
@@ -1009,7 +1009,7 @@ describe("stream reducer canonical tool calls", () => {
|
||||
});
|
||||
|
||||
it("keeps the timeline position on the whole assistant message", () => {
|
||||
const timelineCursor = { epoch: "epoch-1", seq: 42 };
|
||||
const timelineCursor = { epoch: "epoch-1", seq: 42, anchorSeq: 42 };
|
||||
const result = applyStreamEvent({
|
||||
tail: [],
|
||||
head: [],
|
||||
@@ -1890,7 +1890,7 @@ describe("turn lifecycle events", () => {
|
||||
new Date("2025-01-01T15:03:11Z"),
|
||||
{
|
||||
source: "canonical",
|
||||
timelineCursor: { epoch: "epoch-1", seq: 42 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 42, anchorSeq: 42 },
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1902,7 +1902,11 @@ describe("turn lifecycle events", () => {
|
||||
assert.strictEqual(userMessage.messageId, "provider-owned-canonical");
|
||||
assert.strictEqual(userMessage.text, "Analyze this");
|
||||
assert.strictEqual(userMessage.timestamp.getTime(), submittedTimestamp.getTime());
|
||||
assert.deepStrictEqual(userMessage.timelineCursor, { epoch: "epoch-1", seq: 42 });
|
||||
assert.deepStrictEqual(userMessage.timelineCursor, {
|
||||
epoch: "epoch-1",
|
||||
seq: 42,
|
||||
anchorSeq: 42,
|
||||
});
|
||||
assert.deepStrictEqual(userMessage.images, [image]);
|
||||
assert.deepStrictEqual(userMessage.attachments, [attachment]);
|
||||
});
|
||||
|
||||
@@ -266,7 +266,7 @@ function produceUserMessage(
|
||||
...presentation,
|
||||
clientMessageId: incoming.clientMessageId ?? existing.clientMessageId,
|
||||
messageId: incoming.messageId ?? existing.messageId,
|
||||
timelineCursor: incoming.timelineCursor ?? existing.timelineCursor,
|
||||
...advanceTimelinePosition(existing.timelineCursor, incoming.timelineCursor),
|
||||
});
|
||||
if (
|
||||
existing.id === merged.id &&
|
||||
@@ -482,7 +482,7 @@ function mergeRetainedLifecycleItem(tail: StreamItem[], retained: StreamItem): S
|
||||
const next = [...tail];
|
||||
next[tailIndex] = {
|
||||
...existing,
|
||||
timelineCursor: retained.timelineCursor,
|
||||
...advanceTimelinePosition(existing.timelineCursor, retained.timelineCursor),
|
||||
timestamp: retained.timestamp,
|
||||
items: retained.items,
|
||||
};
|
||||
@@ -499,7 +499,7 @@ function mergeRetainedLifecycleItem(tail: StreamItem[], retained: StreamItem): S
|
||||
const next = [...tail];
|
||||
next[tailIndex] = {
|
||||
...existing,
|
||||
timelineCursor: retained.timelineCursor,
|
||||
...advanceTimelinePosition(existing.timelineCursor, retained.timelineCursor),
|
||||
status: "completed",
|
||||
trigger: retained.trigger ?? existing.trigger,
|
||||
preTokens: retained.preTokens ?? existing.preTokens,
|
||||
@@ -519,7 +519,10 @@ function replaceTimelineIdentityItem(
|
||||
const existing = items[index];
|
||||
if (index < 0 || !existing || existing.kind !== "plugin") return null;
|
||||
const next = [...items];
|
||||
next[index] = retained;
|
||||
next[index] = {
|
||||
...retained,
|
||||
...advanceTimelinePosition(existing.timelineCursor, retained.timelineCursor),
|
||||
};
|
||||
return next;
|
||||
}
|
||||
|
||||
@@ -610,7 +613,11 @@ function preserveReplacementHead(
|
||||
: `${tailAssistant.text}${liveAssistant.text}`;
|
||||
const head = [
|
||||
...unreconciledHead.slice(0, liveAssistantIndex),
|
||||
{ ...liveAssistant, text },
|
||||
{
|
||||
...liveAssistant,
|
||||
text,
|
||||
...advanceTimelinePosition(tailAssistant.timelineCursor, liveAssistant.timelineCursor),
|
||||
},
|
||||
...unreconciledHead.slice(liveAssistantIndex + 1),
|
||||
];
|
||||
return {
|
||||
@@ -625,7 +632,13 @@ function preserveReplacementHead(
|
||||
|
||||
const head = [
|
||||
...unreconciledHead.slice(0, liveAssistantIndex),
|
||||
{ ...liveAssistant, text: tailAssistant.text },
|
||||
{
|
||||
...liveAssistant,
|
||||
text: tailAssistant.text,
|
||||
...(liveAssistant.timelineCursor
|
||||
? advanceTimelinePosition(tailAssistant.timelineCursor, liveAssistant.timelineCursor)
|
||||
: {}),
|
||||
},
|
||||
...unreconciledHead.slice(liveAssistantIndex + 1),
|
||||
];
|
||||
return {
|
||||
@@ -724,7 +737,27 @@ export interface AssistantMessageItem {
|
||||
|
||||
export interface TimelinePosition {
|
||||
epoch: string;
|
||||
/** The latest seq that changed this row. */
|
||||
seq: number;
|
||||
/** The seq the row started at. Updates never move it; rewinds retire rows by it. */
|
||||
anchorSeq: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* The position of a row after an update: it moves to the update's seq and stays anchored where it
|
||||
* started. Without an incoming position the row keeps the one it has.
|
||||
*/
|
||||
export function advanceTimelinePosition(
|
||||
existing: TimelinePosition | undefined,
|
||||
incoming: TimelinePosition | undefined,
|
||||
): { timelineCursor?: TimelinePosition } {
|
||||
if (!incoming) return existing ? { timelineCursor: existing } : {};
|
||||
if (!existing || existing.epoch !== incoming.epoch) return { timelineCursor: incoming };
|
||||
const anchorSeq = Math.min(existing.anchorSeq, incoming.anchorSeq);
|
||||
if (existing.seq === incoming.seq && existing.anchorSeq === anchorSeq) {
|
||||
return { timelineCursor: existing };
|
||||
}
|
||||
return { timelineCursor: { ...incoming, anchorSeq } };
|
||||
}
|
||||
|
||||
export type ThoughtStatus = "loading" | "ready";
|
||||
@@ -972,7 +1005,7 @@ function appendAssistantMessage(
|
||||
...last,
|
||||
text: `${last.text}${chunk}`,
|
||||
timestamp,
|
||||
...(timelineCursor ? { timelineCursor } : {}),
|
||||
...advanceTimelinePosition(last.timelineCursor, timelineCursor),
|
||||
};
|
||||
return [...state.slice(0, -1), updated];
|
||||
}
|
||||
@@ -990,7 +1023,7 @@ function appendAssistantMessage(
|
||||
...secondLast,
|
||||
text: `${secondLast.text}${chunk}`,
|
||||
timestamp,
|
||||
...(timelineCursor ? { timelineCursor } : {}),
|
||||
...advanceTimelinePosition(secondLast.timelineCursor, timelineCursor),
|
||||
};
|
||||
return [...state.slice(0, -2), updated, last];
|
||||
}
|
||||
@@ -1028,7 +1061,7 @@ function appendThought(
|
||||
if (last && last.kind === "thought" && last.turnId === turnId) {
|
||||
const updated: ThoughtItem = {
|
||||
...last,
|
||||
...(timelineCursor ? { timelineCursor } : {}),
|
||||
...advanceTimelinePosition(last.timelineCursor, timelineCursor),
|
||||
text: `${last.text}${chunk}`,
|
||||
timestamp,
|
||||
status: "loading",
|
||||
@@ -1208,7 +1241,7 @@ export function mergeAgentToolCallItem(
|
||||
|
||||
return {
|
||||
...existing,
|
||||
...(timelineCursor ? { timelineCursor } : {}),
|
||||
...advanceTimelinePosition(existing.timelineCursor, timelineCursor),
|
||||
timestamp,
|
||||
payload: {
|
||||
source: "agent",
|
||||
@@ -1314,7 +1347,11 @@ function appendPluginTimelineItem(
|
||||
const existing = state[existingIndex];
|
||||
if (!existing || existing.kind !== "plugin") return state;
|
||||
const next = [...state];
|
||||
next[existingIndex] = { ...nextItem, id: existing.id };
|
||||
next[existingIndex] = {
|
||||
...nextItem,
|
||||
id: existing.id,
|
||||
...advanceTimelinePosition(existing.timelineCursor, timelineCursor),
|
||||
};
|
||||
return next;
|
||||
}
|
||||
|
||||
@@ -1345,7 +1382,7 @@ function appendTodoList(
|
||||
const next = [...state];
|
||||
next[previousIndex] = {
|
||||
...previous,
|
||||
...(timelineCursor ? { timelineCursor } : {}),
|
||||
...advanceTimelinePosition(previous.timelineCursor, timelineCursor),
|
||||
items: normalizedItems,
|
||||
timestamp,
|
||||
};
|
||||
@@ -1364,7 +1401,7 @@ function appendTodoList(
|
||||
const next = [...state];
|
||||
next[next.length - 1] = {
|
||||
...lastItem,
|
||||
...(timelineCursor ? { timelineCursor } : {}),
|
||||
...advanceTimelinePosition(lastItem.timelineCursor, timelineCursor),
|
||||
items: normalizedItems,
|
||||
activity: { type: "created", count: normalizedItems.length },
|
||||
timestamp,
|
||||
@@ -1509,7 +1546,7 @@ function reduceTimelineCompaction(
|
||||
if (loadingIdx >= 0 && existing && existing.kind === "compaction") {
|
||||
const updated: CompactionItem = {
|
||||
...existing,
|
||||
...(timelineCursor ? { timelineCursor } : {}),
|
||||
...advanceTimelinePosition(existing.timelineCursor, timelineCursor),
|
||||
status: "completed",
|
||||
trigger: item.trigger ?? existing.trigger,
|
||||
preTokens: item.preTokens ?? existing.preTokens,
|
||||
@@ -1634,7 +1671,10 @@ export function reduceStreamUpdate(
|
||||
),
|
||||
event,
|
||||
);
|
||||
return event.item.type === "reasoning" ? updated : finalizeActiveThoughts(updated);
|
||||
const stamped = event.turnMetrics?.length
|
||||
? stampCompletedTurnMetrics(updated, event.turnMetrics, event.turnId)
|
||||
: updated;
|
||||
return event.item.type === "reasoning" ? stamped : finalizeActiveThoughts(stamped);
|
||||
}
|
||||
case "turn_completed":
|
||||
return stampCompletedTurnMetrics(finalizeActiveThoughts(state), event.metrics, event.turnId);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/cli",
|
||||
"version": "0.17.3",
|
||||
"version": "0.17.4",
|
||||
"description": "Paseo CLI - control your AI coding agents from the command line",
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
@@ -29,9 +29,9 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@clack/prompts": "^1.0.0",
|
||||
"@getpaseo/client": "0.17.3",
|
||||
"@getpaseo/protocol": "0.17.3",
|
||||
"@getpaseo/server": "0.17.3",
|
||||
"@getpaseo/client": "0.17.4",
|
||||
"@getpaseo/protocol": "0.17.4",
|
||||
"@getpaseo/server": "0.17.4",
|
||||
"chalk": "^5.3.0",
|
||||
"commander": "^12.0.0",
|
||||
"mime-types": "^2.1.35",
|
||||
@@ -47,5 +47,8 @@
|
||||
"typescript": "^5.2.2",
|
||||
"vitest": "^4.1.6",
|
||||
"zx": "^8.8.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.16.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -146,6 +146,10 @@ export async function runAttachCommand(
|
||||
const unsubscribe = client.subscribeAgentTimeline(resolvedId, (message) => {
|
||||
if (message.type === "agent.timeline.replacement") {
|
||||
console.log("\n[Timeline replaced; earlier output is no longer current]");
|
||||
} else if (message.type === "agent.timeline.rewind") {
|
||||
console.log(
|
||||
"\n[Conversation rewound; output since the rewound message is no longer current]",
|
||||
);
|
||||
} else if (message.type === "agent.timeline.subscription_restored") {
|
||||
console.log("\n[Reconnected; live output resumed. Events may have been missed.]");
|
||||
} else if (message.type === "agent.timeline.error") {
|
||||
|
||||
@@ -408,7 +408,6 @@ async function runFollowMode({
|
||||
} catch (error) {
|
||||
console.warn("Warning: failed to fetch existing timeline", error);
|
||||
}
|
||||
|
||||
// Apply filter to existing items
|
||||
if (options.filter) {
|
||||
existingItems = existingItems.filter((item) => matchesFilter(item, options.filter));
|
||||
@@ -439,6 +438,11 @@ async function runFollowMode({
|
||||
notice("\n[Timeline replaced; earlier output is no longer current]");
|
||||
return;
|
||||
}
|
||||
if (message.type === "agent.timeline.rewind") {
|
||||
writer.end();
|
||||
notice("\n[Conversation rewound; output since the rewound message is no longer current]");
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.type === "agent.timeline.error") {
|
||||
writer.end();
|
||||
|
||||
@@ -210,7 +210,12 @@ try {
|
||||
console.log("Foreground SIGINT reached the supervisor. The worker and ACP processes exited.");
|
||||
|
||||
daemon = await startSupervisor();
|
||||
const restoredIdle = (await daemon.client.fetchAgentTimeline(idle.id)).agent;
|
||||
// The stored timeline is served without reopening the agent.
|
||||
const storedIdle = (await daemon.client.fetchAgentTimeline(idle.id)).agent;
|
||||
assert.equal(storedIdle?.status, "closed");
|
||||
assert.equal(storedIdle?.requiresAttention, false);
|
||||
await daemon.client.refreshAgent(idle.id);
|
||||
const restoredIdle = (await daemon.client.fetchAgent(idle.id))?.agent;
|
||||
assert.equal(restoredIdle?.status, "idle");
|
||||
assert.equal(restoredIdle?.requiresAttention, false);
|
||||
await waitFor(async () => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/client",
|
||||
"version": "0.17.3",
|
||||
"version": "0.17.4",
|
||||
"description": "Paseo client SDK package",
|
||||
"license": "Apache-2.0",
|
||||
"files": [
|
||||
@@ -49,8 +49,8 @@
|
||||
"measure:diff-materialization": "tsx scripts/measure-diff-materialization.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@getpaseo/protocol": "0.17.3",
|
||||
"@getpaseo/relay": "0.17.3",
|
||||
"@getpaseo/protocol": "0.17.4",
|
||||
"@getpaseo/relay": "0.17.4",
|
||||
"ws": "^8.20.0",
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
|
||||
@@ -211,6 +211,37 @@ test("SDK subscribers receive timeline replacement instead of silently losing hi
|
||||
}
|
||||
});
|
||||
|
||||
test("SDK subscribers receive a conversation rewind as a retired range", async () => {
|
||||
const { createPaseoApi } = await import("./index");
|
||||
const h = connection();
|
||||
const received: unknown[] = [];
|
||||
try {
|
||||
const ready = h.client.connect();
|
||||
h.open();
|
||||
await ready;
|
||||
const off = createPaseoApi(h.client)
|
||||
.agents.ref("agent")
|
||||
.timeline.subscribe((event) => received.push(event));
|
||||
await off.ready;
|
||||
h.receive({
|
||||
type: "agent.timeline.rewind",
|
||||
payload: {
|
||||
agentId: "agent",
|
||||
epoch: "epoch-1",
|
||||
seq: 12,
|
||||
retireFromSeq: 7,
|
||||
subscriptionId: off.subscriptionId,
|
||||
},
|
||||
});
|
||||
expect(received).toEqual([
|
||||
{ agentId: "agent", event: { type: "rewind", epoch: "epoch-1", seq: 12, retireFromSeq: 7 } },
|
||||
]);
|
||||
off();
|
||||
} finally {
|
||||
await h.client.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("local listeners create no demand before or after reconnect", async () => {
|
||||
const h = connection();
|
||||
try {
|
||||
|
||||
@@ -141,6 +141,7 @@ export const DEFAULT_CLIENT_CAPABILITIES = {
|
||||
[CLIENT_CAPS.compactProviderSnapshots]: true,
|
||||
[CLIENT_CAPS.providerSnapshotReferences]: true,
|
||||
[CLIENT_CAPS.timelineReplacementInvalidation]: true,
|
||||
[CLIENT_CAPS.timelineRewindOperations]: true,
|
||||
[CLIENT_CAPS.timelineNotifications]: true,
|
||||
[CLIENT_CAPS.pluginTimelineItems]: true,
|
||||
[CLIENT_CAPS.workspaceSetupBlocked]: true,
|
||||
|
||||
@@ -246,7 +246,9 @@ export class LegacySubscriptions {
|
||||
);
|
||||
case "agent.timeline.set_subscription.request":
|
||||
return (
|
||||
(message.type === "agent_stream" || message.type === "agent.timeline.replacement") &&
|
||||
(message.type === "agent_stream" ||
|
||||
message.type === "agent.timeline.replacement" ||
|
||||
message.type === "agent.timeline.rewind") &&
|
||||
(query.agentIds as string[]).includes(message.payload.agentId)
|
||||
);
|
||||
case "session.events.set_subscription.request":
|
||||
|
||||
@@ -1131,6 +1131,7 @@ test("advertises client capabilities in hello", async () => {
|
||||
all_providers: true,
|
||||
selective_agent_timeline: true,
|
||||
timeline_replacement_invalidation: true,
|
||||
timeline_rewind_operations: true,
|
||||
provider_snapshot_references: true,
|
||||
explicit_event_subscriptions: true,
|
||||
owned_subscriptions: true,
|
||||
|
||||
@@ -346,6 +346,14 @@ export type PaseoAgentTimelineEvent =
|
||||
agentId: string;
|
||||
event: { type: "replacement"; epoch: string };
|
||||
}
|
||||
| {
|
||||
/**
|
||||
* A conversation rewind removed the rows anchored in `[retireFromSeq, seq)` from the active
|
||||
* history. Rows after `seq` belong to the rewound conversation.
|
||||
*/
|
||||
agentId: string;
|
||||
event: { type: "rewind"; epoch: string; seq: number; retireFromSeq: number };
|
||||
}
|
||||
| {
|
||||
agentId: string;
|
||||
subscriptionId: string;
|
||||
@@ -367,7 +375,9 @@ export interface PaseoAgentTimelineHandle {
|
||||
* Delivers live events only. After reconnect, subscription_restored precedes
|
||||
* subsequent updates. History may have been missed; use refetch() to request
|
||||
* the range you need. No history is fetched automatically. A replacement event
|
||||
* invalidates the previous epoch. Subscription errors release this observation.
|
||||
* invalidates the previous epoch. A rewind event removes `[retireFromSeq, seq)`
|
||||
* from the active history without changing the epoch. Subscription errors
|
||||
* release this observation.
|
||||
* Await the returned unsubscribe function's `ready` promise before starting
|
||||
* work that must be observed. It rejects if establishment fails.
|
||||
*/
|
||||
@@ -1047,6 +1057,16 @@ function createAgentHandleFactory(
|
||||
agentId: id,
|
||||
event: { type: "replacement", epoch: message.payload.epoch },
|
||||
});
|
||||
case "agent.timeline.rewind":
|
||||
return handler({
|
||||
agentId: id,
|
||||
event: {
|
||||
type: "rewind",
|
||||
epoch: message.payload.epoch,
|
||||
seq: message.payload.seq,
|
||||
retireFromSeq: message.payload.retireFromSeq,
|
||||
},
|
||||
});
|
||||
}
|
||||
}),
|
||||
},
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { OwnedSubscription, TimelineSubscription } from "../connection/inde
|
||||
|
||||
type TimelineUpdate = Extract<
|
||||
SessionOutboundMessage,
|
||||
{ type: "agent_stream" | "agent.timeline.replacement" }
|
||||
{ type: "agent_stream" | "agent.timeline.replacement" | "agent.timeline.rewind" }
|
||||
>;
|
||||
|
||||
/** Local SDK lifecycle messages; these are not additional wire RPCs. */
|
||||
@@ -59,7 +59,11 @@ export function subscribeTimeline(
|
||||
});
|
||||
},
|
||||
update: (message) => {
|
||||
if (message.type === "agent_stream" || message.type === "agent.timeline.replacement")
|
||||
if (
|
||||
message.type === "agent_stream" ||
|
||||
message.type === "agent.timeline.replacement" ||
|
||||
message.type === "agent.timeline.rewind"
|
||||
)
|
||||
notify(message);
|
||||
},
|
||||
error: fail,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/desktop",
|
||||
"version": "0.17.3",
|
||||
"version": "0.17.4",
|
||||
"private": true,
|
||||
"description": "Paseo desktop app (Electron wrapper)",
|
||||
"homepage": "https://paseo.sh",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/expo-two-way-audio",
|
||||
"version": "0.17.3",
|
||||
"version": "0.17.4",
|
||||
"description": "Native module for two way audio streaming",
|
||||
"keywords": [
|
||||
"ExpoTwoWayAudio",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/highlight",
|
||||
"version": "0.17.3",
|
||||
"version": "0.17.4",
|
||||
"license": "Apache-2.0",
|
||||
"files": [
|
||||
"dist",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/plugin",
|
||||
"version": "0.17.3",
|
||||
"version": "0.17.4",
|
||||
"description": "Paseo plugin SDK package",
|
||||
"license": "Apache-2.0",
|
||||
"files": [
|
||||
@@ -78,8 +78,8 @@
|
||||
"use-sync-external-store": "^1.6.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@getpaseo/client": "0.17.3",
|
||||
"@getpaseo/protocol": "0.17.3",
|
||||
"@getpaseo/client": "0.17.4",
|
||||
"@getpaseo/protocol": "0.17.4",
|
||||
"@types/node": "^20.9.0",
|
||||
"@types/react": "~19.2.0",
|
||||
"react": "19.2.3",
|
||||
@@ -89,8 +89,8 @@
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@getpaseo/client": "0.17.3",
|
||||
"@getpaseo/protocol": "0.17.3",
|
||||
"@getpaseo/client": "0.17.4",
|
||||
"@getpaseo/protocol": "0.17.4",
|
||||
"react": ">=19.1.0 <20",
|
||||
"react-native": ">=0.81.5",
|
||||
"zod": "^4.4.3"
|
||||
|
||||
@@ -13,14 +13,15 @@ import {
|
||||
type RequestPermissionRequest,
|
||||
type RequestPermissionResponse,
|
||||
type SessionConfigOption,
|
||||
type SessionInfo,
|
||||
type SessionNotification,
|
||||
type SessionUpdate,
|
||||
type ToolCall,
|
||||
type ToolCallContent,
|
||||
type ToolCallUpdate,
|
||||
type Stream,
|
||||
} from "@agentclientprotocol/sdk";
|
||||
import { z } from "zod";
|
||||
import type { JsonValue } from "@getpaseo/protocol/agent-types";
|
||||
import type {
|
||||
AcpConfigAccess,
|
||||
AcpConfigChange,
|
||||
@@ -31,6 +32,7 @@ import type {
|
||||
AcpVendorUpdate,
|
||||
RunAcpProviderOptions,
|
||||
} from "../acp.js";
|
||||
import { standardToolCallDetail } from "./tool-call-detail.js";
|
||||
import {
|
||||
PROVIDER_PROTOCOL_VERSION,
|
||||
ProviderEventSchema,
|
||||
@@ -48,6 +50,7 @@ import {
|
||||
type ProviderLaunch,
|
||||
type ProviderModel,
|
||||
type ProviderPermissionResponse,
|
||||
type ProviderToolCallDetail,
|
||||
type ProviderPersistence,
|
||||
type ProviderSessionConfig,
|
||||
type ProviderSetting,
|
||||
@@ -296,8 +299,7 @@ async function listSessions(
|
||||
emit: state.emit,
|
||||
});
|
||||
try {
|
||||
const response = await runtime.listSessions(input.cwd);
|
||||
const selected = input.limit ? response.sessions.slice(0, input.limit) : response.sessions;
|
||||
const selected = await runtime.listSessions({ cwd: input.cwd, limit: input.limit });
|
||||
state.emit({
|
||||
type: "sessions",
|
||||
requestId: input.requestId,
|
||||
@@ -408,14 +410,14 @@ interface ActivePrompt {
|
||||
}
|
||||
|
||||
const DEFAULT_DEFERRED_SETTLE_DELAY_MS = 500;
|
||||
const SESSION_SCAN_LIMIT = 500;
|
||||
// COMPAT(acpAutoAccept): added in v0.17.4, remove after 2027-05-23. The generic ACP adapter saves
|
||||
// its Auto Accept toggle as this setting on agents that later moved to a bundled ACP provider.
|
||||
const LEGACY_AUTO_ACCEPT_SETTING = "auto_accept";
|
||||
const DEFAULT_DEFERRED_QUIET_LIMIT_MS = 120_000;
|
||||
|
||||
type AcpToolCallSource = AcpToolCallSnapshot & {
|
||||
diff?: Extract<ToolCallContent, { type: "diff" }>;
|
||||
};
|
||||
|
||||
interface AcpToolCallState {
|
||||
source: AcpToolCallSource;
|
||||
source: AcpToolCallSnapshot;
|
||||
presentation: AcpToolCallSnapshot;
|
||||
}
|
||||
|
||||
@@ -916,8 +918,17 @@ class AcpRuntime {
|
||||
return true;
|
||||
}
|
||||
|
||||
listSessions(cwd?: string) {
|
||||
return this.call(this.connection.listSessions({ cwd }));
|
||||
/** Follows `nextCursor` until `limit` sessions, the last page, or the scan cap. */
|
||||
async listSessions({ cwd, limit }: { cwd?: string; limit?: number }): Promise<SessionInfo[]> {
|
||||
const wanted = Math.min(limit ?? SESSION_SCAN_LIMIT, SESSION_SCAN_LIMIT);
|
||||
const sessions: SessionInfo[] = [];
|
||||
let cursor: string | undefined;
|
||||
do {
|
||||
const page = await this.call(this.connection.listSessions({ cwd, cursor }));
|
||||
sessions.push(...page.sessions);
|
||||
cursor = page.nextCursor ?? undefined;
|
||||
} while (cursor && sessions.length < wanted);
|
||||
return sessions.slice(0, wanted);
|
||||
}
|
||||
|
||||
async drainNotifications(): Promise<void> {
|
||||
@@ -1072,17 +1083,41 @@ class AcpRuntime {
|
||||
const requested: AcpConfigChange[] = [];
|
||||
if (config.model) requested.push({ target: "model", value: config.model });
|
||||
const autoAcceptMode = this.options.options.acpOptions?.autoAcceptMode;
|
||||
const mode = config.mode ?? (autoAcceptMode?.default ? autoAcceptMode.mode.id : undefined);
|
||||
const { settings, legacyAutoAccept } = this.withoutLegacyAutoAccept(config.settings);
|
||||
// The toggle stays saved after a mode is chosen here, so it counts only while the saved mode
|
||||
// is one the generic adapter wrote.
|
||||
const mode =
|
||||
legacyAutoAccept && autoAcceptMode && !this.offersMode(config.mode)
|
||||
? autoAcceptMode.mode.id
|
||||
: (config.mode ?? (autoAcceptMode?.default ? autoAcceptMode.mode.id : undefined));
|
||||
if (mode) requested.push({ target: "mode", value: mode });
|
||||
if (config.thinkingOption) {
|
||||
requested.push({ target: "thinking", value: config.thinkingOption });
|
||||
}
|
||||
for (const [id, value] of Object.entries(config.settings)) {
|
||||
for (const [id, value] of Object.entries(settings)) {
|
||||
requested.push({ target: "setting", id, value });
|
||||
}
|
||||
for (const change of this.inAgentOrder(requested)) await this.applyConfigChange(change);
|
||||
}
|
||||
|
||||
private offersMode(mode: string | undefined): boolean {
|
||||
if (mode === undefined) return false;
|
||||
if (mode === this.options.options.acpOptions?.autoAcceptMode?.mode.id) return true;
|
||||
return toProviderCatalog(this.modes, this.configOptions).modes.some(({ id }) => id === mode);
|
||||
}
|
||||
|
||||
/** Reads the generic ACP adapter's saved Auto Accept toggle unless the agent has such a setting. */
|
||||
private withoutLegacyAutoAccept(settings: Readonly<Record<string, JsonValue>>): {
|
||||
settings: Readonly<Record<string, JsonValue>>;
|
||||
legacyAutoAccept: boolean;
|
||||
} {
|
||||
if (this.configOptions.some((option) => option.id === LEGACY_AUTO_ACCEPT_SETTING)) {
|
||||
return { settings, legacyAutoAccept: false };
|
||||
}
|
||||
const { [LEGACY_AUTO_ACCEPT_SETTING]: saved, ...rest } = settings;
|
||||
return { settings: rest, legacyAutoAccept: saved === true };
|
||||
}
|
||||
|
||||
// One option can reset another: choosing an fx provider also selects that provider's saved
|
||||
// model, so a model applied first would be lost. Agents list the option that decides first.
|
||||
private inAgentOrder(changes: readonly AcpConfigChange[]): AcpConfigChange[] {
|
||||
@@ -1282,6 +1317,7 @@ class AcpRuntime {
|
||||
}
|
||||
}
|
||||
const permissionId = `permission:${request.toolCall.toolCallId}`;
|
||||
const { presentation } = this.presentToolCall(request.toolCall);
|
||||
return new Promise((resolve) => {
|
||||
this.permissions.set(permissionId, { request, resolve, turnId: this.activePrompt?.turnId });
|
||||
if (this.activePrompt?.deferred) this.scheduleDeferredSettle();
|
||||
@@ -1294,6 +1330,7 @@ class AcpRuntime {
|
||||
kind: "tool",
|
||||
title: request.toolCall.title ?? undefined,
|
||||
input: jsonRecord(request.toolCall.rawInput),
|
||||
detail: toolCallDetail(presentation),
|
||||
actions: request.options.map((option) => ({
|
||||
id: option.optionId,
|
||||
label: option.name,
|
||||
@@ -1562,6 +1599,21 @@ class AcpRuntime {
|
||||
this.pendingCompactions.clear();
|
||||
}
|
||||
|
||||
/** Merges an update into the call's earlier updates and runs it through the transformers. */
|
||||
private presentToolCall(update: ToolCall | ToolCallUpdate): AcpToolCallState {
|
||||
const tool = this.toolCalls.get(update.toolCallId);
|
||||
const source = mergeToolCallSnapshot(update, tool?.source);
|
||||
const context = {
|
||||
sessionId: this.options.boundarySessionId,
|
||||
mcpServerNames: this.mcpServerNames,
|
||||
previous: tool?.presentation,
|
||||
};
|
||||
let presentation: AcpToolCallSnapshot = source;
|
||||
for (const transformer of this.transformers)
|
||||
presentation = transformer.toolCall?.(presentation, context) ?? presentation;
|
||||
return { source, presentation };
|
||||
}
|
||||
|
||||
private reduceToolCall(
|
||||
update: Extract<SessionUpdate, { sessionUpdate: "tool_call" | "tool_call_update" }>,
|
||||
wireSeq: number,
|
||||
@@ -1581,25 +1633,7 @@ class AcpRuntime {
|
||||
current !== undefined &&
|
||||
this.liveOpenToolIds.has(current.id) &&
|
||||
this.toolKeepsTurnOpen(current);
|
||||
const source = mergeToolCallSnapshot(update, tool?.source);
|
||||
let snapshot: AcpToolCallSnapshot = source;
|
||||
const context = {
|
||||
sessionId: this.options.boundarySessionId,
|
||||
mcpServerNames: this.mcpServerNames,
|
||||
};
|
||||
for (const transformer of this.transformers)
|
||||
snapshot = transformer.toolCall?.(snapshot, context) ?? snapshot;
|
||||
if (!snapshot.detail && source.diff && snapshot.kind === "edit") {
|
||||
snapshot = {
|
||||
...snapshot,
|
||||
detail: {
|
||||
type: "edit",
|
||||
filePath: source.diff.path,
|
||||
oldString: source.diff.oldText ?? undefined,
|
||||
newString: source.diff.newText,
|
||||
},
|
||||
};
|
||||
}
|
||||
const { source, presentation: snapshot } = this.presentToolCall(update);
|
||||
this.toolCalls.set(snapshot.id, { source, presentation: snapshot });
|
||||
const isOpen = snapshot.status === "pending" || snapshot.status === "in_progress";
|
||||
if (this.replayWindow === null) {
|
||||
@@ -2179,8 +2213,8 @@ function ownConnectorStream(source: Stream): {
|
||||
|
||||
function mergeToolCallSnapshot(
|
||||
update: ToolCall | ToolCallUpdate,
|
||||
current: AcpToolCallSource | undefined,
|
||||
): AcpToolCallSource {
|
||||
current: AcpToolCallSnapshot | undefined,
|
||||
): AcpToolCallSnapshot {
|
||||
return {
|
||||
id: update.toolCallId,
|
||||
name: firstText(update.name, current?.name),
|
||||
@@ -2190,10 +2224,7 @@ function mergeToolCallSnapshot(
|
||||
input: jsonValue(firstDefined(update.rawInput, current?.input, null)),
|
||||
output: jsonValue(firstDefined(update.rawOutput, current?.output, null)),
|
||||
locations: update.locations?.map((location) => location.path) ?? current?.locations ?? [],
|
||||
diff:
|
||||
update.content === undefined
|
||||
? current?.diff
|
||||
: update.content?.find((item) => item.type === "diff"),
|
||||
content: update.content === undefined ? current?.content : jsonValue(update.content),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -2367,21 +2398,12 @@ function configValues(
|
||||
|
||||
type ToolCallTimelineItem = Extract<ProviderTimelineItem, { type: "tool_call" }>;
|
||||
|
||||
function toolCallDetail(snapshot: AcpToolCallSnapshot): ProviderToolCallDetail {
|
||||
return snapshot.detail ?? standardToolCallDetail(snapshot);
|
||||
}
|
||||
|
||||
function toolTimelineItem(snapshot: AcpToolCallSnapshot): ToolCallTimelineItem {
|
||||
const input = jsonRecord(snapshot.input);
|
||||
const isEdit = snapshot.kind === "edit" || snapshot.name?.toLowerCase().includes("edit") === true;
|
||||
const detail =
|
||||
snapshot.detail ??
|
||||
(isEdit
|
||||
? {
|
||||
type: "edit" as const,
|
||||
filePath:
|
||||
typeof input.filePath === "string" ? input.filePath : (snapshot.locations[0] ?? ""),
|
||||
oldString: typeof input.oldString === "string" ? input.oldString : undefined,
|
||||
newString: typeof input.newString === "string" ? input.newString : undefined,
|
||||
unifiedDiff: typeof input.unifiedDiff === "string" ? input.unifiedDiff : undefined,
|
||||
}
|
||||
: { type: "unknown" as const, input: snapshot.input, output: snapshot.output });
|
||||
const detail = toolCallDetail(snapshot);
|
||||
const status =
|
||||
snapshot.status === "in_progress" || snapshot.status === "pending"
|
||||
? "running"
|
||||
@@ -2416,6 +2438,7 @@ function jsonValue(value: unknown) {
|
||||
}
|
||||
|
||||
function jsonRecord(value: unknown): Record<string, ReturnType<typeof jsonValue>> {
|
||||
if (value === undefined) return {};
|
||||
const parsed = jsonValue(value);
|
||||
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return {};
|
||||
return parsed;
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
import type { JsonValue } from "@getpaseo/protocol/agent-types";
|
||||
import type { AcpToolCallSnapshot } from "../acp.js";
|
||||
import type { ProviderToolCallDetail } from "../provider.js";
|
||||
|
||||
type JsonRecord = Readonly<Record<string, JsonValue>>;
|
||||
|
||||
interface ToolCallParts {
|
||||
call: AcpToolCallSnapshot;
|
||||
input: JsonRecord;
|
||||
output: JsonRecord;
|
||||
text: string | undefined;
|
||||
}
|
||||
|
||||
type KindDetail = (parts: ToolCallParts) => ProviderToolCallDetail;
|
||||
|
||||
const KIND_DETAILS = new Map<string, KindDetail>(
|
||||
Object.entries({
|
||||
read: ({ call, input, output, text }) => ({
|
||||
type: "read",
|
||||
filePath: call.locations[0] ?? string(input, "path", "filePath", "file") ?? call.title,
|
||||
content: text ?? string(output, "content", "text"),
|
||||
offset: number(input, "offset", "line"),
|
||||
limit: number(input, "limit"),
|
||||
}),
|
||||
edit: editDetail,
|
||||
delete: editDetail,
|
||||
search: ({ call, input, output, text }) => ({
|
||||
type: "search",
|
||||
query: string(input, "query", "pattern") ?? call.title,
|
||||
toolName: "search",
|
||||
content: text ?? string(output, "content", "text"),
|
||||
filePaths: call.locations.length > 0 ? [...call.locations] : undefined,
|
||||
}),
|
||||
execute: ({ call, input, output, text }) => ({
|
||||
type: "shell",
|
||||
command: shellCommand(input) ?? call.title,
|
||||
cwd: string(input, "cwd"),
|
||||
output: text ?? string(output, "output", "text"),
|
||||
exitCode: number(output, "exitCode"),
|
||||
}),
|
||||
fetch: ({ call, input, output, text }) => ({
|
||||
type: "fetch",
|
||||
url: string(input, "url") ?? call.title,
|
||||
prompt: string(input, "prompt"),
|
||||
result: text ?? string(output, "result", "text", "content"),
|
||||
code: number(output, "status", "code"),
|
||||
}),
|
||||
think: ({ call, text }) => ({ type: "plain_text", label: call.title, icon: "brain", text }),
|
||||
switch_mode: ({ call, text }) => ({
|
||||
type: "plain_text",
|
||||
label: call.title,
|
||||
icon: "sparkles",
|
||||
text,
|
||||
}),
|
||||
} satisfies Record<string, KindDetail>),
|
||||
);
|
||||
|
||||
/**
|
||||
* The row for a tool call whose transformers set no detail, read from the call's ACP `kind`,
|
||||
* `rawInput`, `rawOutput`, `content` and `locations` the way the ACP spec defines them.
|
||||
*/
|
||||
export function standardToolCallDetail(call: AcpToolCallSnapshot): ProviderToolCallDetail {
|
||||
const parts: ToolCallParts = {
|
||||
call,
|
||||
input: record(call.input),
|
||||
output: record(call.output),
|
||||
text: contentText(call.content),
|
||||
};
|
||||
const kindDetail = call.kind === undefined ? undefined : KIND_DETAILS.get(call.kind);
|
||||
if (kindDetail) return kindDetail(parts);
|
||||
if (call.name?.toLowerCase().includes("edit")) return editDetail(parts);
|
||||
// Raw input or output is the most a client can show for a tool it does not know.
|
||||
if (parts.text !== undefined && call.input === null && call.output === null) {
|
||||
return { type: "plain_text", label: call.title, icon: "wrench", text: parts.text };
|
||||
}
|
||||
return { type: "unknown", input: call.input, output: call.output };
|
||||
}
|
||||
|
||||
function editDetail({ call, input, text }: ToolCallParts): ProviderToolCallDetail {
|
||||
const diff = contentDiff(call.content);
|
||||
const filePath =
|
||||
diff?.path ?? string(input, "filePath", "path", "file") ?? call.locations[0] ?? "";
|
||||
if (call.kind === "delete") {
|
||||
return {
|
||||
type: "edit",
|
||||
filePath,
|
||||
oldString: diff?.oldText ?? fileText(input, "oldText"),
|
||||
newString: "",
|
||||
unifiedDiff: text,
|
||||
};
|
||||
}
|
||||
return {
|
||||
type: "edit",
|
||||
filePath,
|
||||
oldString: diff?.oldText ?? fileText(input, "oldString", "oldText"),
|
||||
newString: diff?.newText ?? fileText(input, "newString", "newText"),
|
||||
unifiedDiff: string(input, "unifiedDiff") ?? text,
|
||||
};
|
||||
}
|
||||
|
||||
function shellCommand(input: JsonRecord): string | undefined {
|
||||
const command = string(input, "command");
|
||||
if (!command) return undefined;
|
||||
const args = Array.isArray(input.args)
|
||||
? input.args.filter((arg): arg is string => typeof arg === "string")
|
||||
: [];
|
||||
return args.length > 0 ? `${command} ${args.join(" ")}` : command;
|
||||
}
|
||||
|
||||
function contentText(content: JsonValue | undefined): string | undefined {
|
||||
const parts = contentBlocks(content).flatMap((block) => {
|
||||
if (block.type !== "content") return [];
|
||||
const body = record(block.content ?? null);
|
||||
return body.type === "text" && typeof body.text === "string" && body.text.length > 0
|
||||
? [body.text]
|
||||
: [];
|
||||
});
|
||||
return parts.length > 0 ? parts.join("\n") : undefined;
|
||||
}
|
||||
|
||||
function contentDiff(
|
||||
content: JsonValue | undefined,
|
||||
): { path?: string; oldText?: string; newText?: string } | undefined {
|
||||
const diff = contentBlocks(content).find((block) => block.type === "diff");
|
||||
if (!diff) return undefined;
|
||||
return {
|
||||
path: string(diff, "path"),
|
||||
oldText: typeof diff.oldText === "string" ? diff.oldText : undefined,
|
||||
newText: typeof diff.newText === "string" ? diff.newText : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function contentBlocks(content: JsonValue | undefined): JsonRecord[] {
|
||||
return Array.isArray(content) ? content.map((block) => record(block)) : [];
|
||||
}
|
||||
|
||||
function record(value: JsonValue): JsonRecord {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
|
||||
}
|
||||
|
||||
function string(value: JsonRecord, ...keys: string[]): string | undefined {
|
||||
for (const key of keys) {
|
||||
const entry = value[key];
|
||||
if (typeof entry === "string" && entry.trim().length > 0) return entry;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** File text is kept as written: whitespace or an empty string is the edit itself. */
|
||||
function fileText(value: JsonRecord, ...keys: string[]): string | undefined {
|
||||
for (const key of keys) {
|
||||
const entry = value[key];
|
||||
if (typeof entry === "string") return entry;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function number(value: JsonRecord, ...keys: string[]): number | undefined {
|
||||
for (const key of keys) {
|
||||
const entry = value[key];
|
||||
if (typeof entry === "number" && Number.isFinite(entry)) return entry;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
} from "@agentclientprotocol/sdk";
|
||||
import type { ProviderConnection, ProviderEvent, ProviderInput } from "./provider.js";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import type { JsonValue } from "@getpaseo/protocol/agent-types";
|
||||
import { AgentTimelineItemPayloadSchema } from "@getpaseo/protocol/messages";
|
||||
import { runAcpProvider, type AcpStreamMessage } from "./acp.js";
|
||||
|
||||
@@ -6724,3 +6725,403 @@ describe("deferTurnOnRunningTools", () => {
|
||||
await connection.close();
|
||||
});
|
||||
});
|
||||
|
||||
describe("ACP tool call rows", () => {
|
||||
function jsonRecord(value: JsonValue | undefined): Readonly<Record<string, JsonValue>> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
|
||||
}
|
||||
|
||||
function text(value: string) {
|
||||
return [{ type: "content", content: { type: "text", text: value } }];
|
||||
}
|
||||
|
||||
async function toolRows(
|
||||
updates: unknown[],
|
||||
transformers?: Parameters<typeof runAcpProvider>[0]["transformers"],
|
||||
) {
|
||||
const harness = connectorHarness({ promptUpdates: () => updates });
|
||||
const registration = runAcpProvider({
|
||||
id: "tool-rows-acp",
|
||||
label: "Tool rows ACP",
|
||||
connector: harness.connector,
|
||||
transformers,
|
||||
});
|
||||
const connection = await registration.connect({
|
||||
versions: [1],
|
||||
capabilities: ["prompt.message"],
|
||||
});
|
||||
const events: ProviderEvent[] = [];
|
||||
connection.onEvent((event) => events.push(event));
|
||||
try {
|
||||
await connection.send(openInput());
|
||||
await waitForEvent(events, (event) => event.type === "session.ready");
|
||||
await connection.send({
|
||||
type: "session.prompt",
|
||||
sessionId: "session-1",
|
||||
prompt: {
|
||||
clientMessageId: "first",
|
||||
delivery: "auto",
|
||||
input: { type: "message", content: [{ type: "text", text: "Use a tool" }] },
|
||||
},
|
||||
});
|
||||
await waitForEvent(
|
||||
events,
|
||||
(event) => event.type === "session.turn" && event.state === "completed",
|
||||
);
|
||||
const rows = events.flatMap((event) =>
|
||||
event.type === "timeline.item" && event.item.type === "tool_call" ? [event.item] : [],
|
||||
);
|
||||
for (const row of rows) {
|
||||
expect(AgentTimelineItemPayloadSchema.safeParse(row).success).toBe(true);
|
||||
}
|
||||
return rows;
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
}
|
||||
|
||||
it.each([
|
||||
{
|
||||
kind: "execute",
|
||||
start: { title: "Run tests", rawInput: { command: "npm", args: ["test"], cwd: "/repo" } },
|
||||
end: { content: text("passed"), rawOutput: { exitCode: 0 } },
|
||||
detail: { type: "shell", command: "npm test", cwd: "/repo", output: "passed", exitCode: 0 },
|
||||
},
|
||||
{
|
||||
kind: "execute",
|
||||
start: { title: "Run tests" },
|
||||
end: { content: text("passed") },
|
||||
detail: { type: "shell", command: "Run tests", output: "passed" },
|
||||
},
|
||||
{
|
||||
kind: "read",
|
||||
start: { title: "Read a.ts", locations: [{ path: "/repo/a.ts" }], rawInput: { offset: 3 } },
|
||||
end: { content: text("const a = 1;") },
|
||||
detail: { type: "read", filePath: "/repo/a.ts", content: "const a = 1;", offset: 3 },
|
||||
},
|
||||
{
|
||||
kind: "search",
|
||||
start: { title: "Search TODO", rawInput: { pattern: "TODO" } },
|
||||
end: { content: text("a.ts:1"), locations: [{ path: "/repo/a.ts" }] },
|
||||
detail: {
|
||||
type: "search",
|
||||
query: "TODO",
|
||||
toolName: "search",
|
||||
content: "a.ts:1",
|
||||
filePaths: ["/repo/a.ts"],
|
||||
},
|
||||
},
|
||||
{
|
||||
kind: "fetch",
|
||||
start: { title: "Fetch example", rawInput: { url: "https://example.com" } },
|
||||
end: { content: text("Example Domain") },
|
||||
detail: { type: "fetch", url: "https://example.com", result: "Example Domain" },
|
||||
},
|
||||
{
|
||||
kind: "edit",
|
||||
start: {
|
||||
title: "Edit a.ts",
|
||||
content: [{ type: "diff", path: "/repo/a.ts", oldText: "a", newText: "b" }],
|
||||
},
|
||||
end: {},
|
||||
detail: { type: "edit", filePath: "/repo/a.ts", oldString: "a", newString: "b" },
|
||||
},
|
||||
{
|
||||
kind: "edit",
|
||||
start: { title: "Edit a.ts", locations: [{ path: "/repo/a.ts" }] },
|
||||
end: { content: text("Replaced 1 occurrence") },
|
||||
detail: { type: "edit", filePath: "/repo/a.ts", unifiedDiff: "Replaced 1 occurrence" },
|
||||
},
|
||||
{
|
||||
kind: "edit",
|
||||
start: {
|
||||
title: "Edit a.ts",
|
||||
rawInput: { filePath: "/repo/a.ts", oldString: "remove me", newString: " " },
|
||||
},
|
||||
end: {},
|
||||
detail: { type: "edit", filePath: "/repo/a.ts", oldString: "remove me", newString: " " },
|
||||
},
|
||||
{
|
||||
kind: "delete",
|
||||
start: { title: "Delete a.ts", locations: [{ path: "/repo/a.ts" }] },
|
||||
end: {},
|
||||
detail: { type: "edit", filePath: "/repo/a.ts", newString: "" },
|
||||
},
|
||||
{
|
||||
kind: "think",
|
||||
start: { title: "Plan" },
|
||||
end: { content: text("First read the tests") },
|
||||
detail: { type: "plain_text", label: "Plan", icon: "brain", text: "First read the tests" },
|
||||
},
|
||||
{
|
||||
kind: "other",
|
||||
start: { title: "Update todos" },
|
||||
end: { content: text("2 open") },
|
||||
detail: { type: "plain_text", label: "Update todos", icon: "wrench", text: "2 open" },
|
||||
},
|
||||
{
|
||||
kind: "other",
|
||||
start: { title: "Custom tool", rawInput: { value: 1 } },
|
||||
end: { content: text("done"), rawOutput: { ok: true } },
|
||||
detail: { type: "unknown", input: { value: 1 }, output: { ok: true } },
|
||||
},
|
||||
])("presents a completed $kind call as its standard row ($start.title)", async (example) => {
|
||||
const rows = await toolRows([
|
||||
{
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "tool-1",
|
||||
kind: example.kind,
|
||||
status: "in_progress",
|
||||
...example.start,
|
||||
},
|
||||
{
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId: "tool-1",
|
||||
status: "completed",
|
||||
...example.end,
|
||||
},
|
||||
]);
|
||||
expect(rows.at(-1)?.detail).toEqual(example.detail);
|
||||
});
|
||||
|
||||
it("gives transformers the call's content and the call as it was last presented", async () => {
|
||||
const commandFromStart: NonNullable<
|
||||
NonNullable<Parameters<typeof runAcpProvider>[0]["transformers"]>[number]["toolCall"]
|
||||
> = (call, { previous }) => {
|
||||
const first = Array.isArray(call.content) ? call.content[0] : undefined;
|
||||
const startText = jsonRecord(jsonRecord(first).content).text;
|
||||
if (typeof startText === "string" && startText.startsWith("$ ")) {
|
||||
return { ...call, input: { command: startText.slice(2) } };
|
||||
}
|
||||
const command = jsonRecord(previous?.input).command;
|
||||
return typeof command === "string" ? { ...call, input: { command } } : call;
|
||||
};
|
||||
const rows = await toolRows(
|
||||
[
|
||||
{
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "tool-1",
|
||||
title: "git status + 1 command",
|
||||
kind: "execute",
|
||||
status: "in_progress",
|
||||
content: text("$ git status && git diff"),
|
||||
},
|
||||
{
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId: "tool-1",
|
||||
status: "completed",
|
||||
content: text("clean"),
|
||||
},
|
||||
],
|
||||
[{ toolCall: commandFromStart }],
|
||||
);
|
||||
expect(rows.map((row) => row.detail)).toEqual([
|
||||
{ type: "shell", command: "git status && git diff", output: "$ git status && git diff" },
|
||||
{ type: "shell", command: "git status && git diff", output: "clean" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps a transformer's own detail over the standard row", async () => {
|
||||
const rows = await toolRows(
|
||||
[
|
||||
{
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "tool-1",
|
||||
title: "Run tests",
|
||||
kind: "execute",
|
||||
status: "completed",
|
||||
rawInput: { command: "npm test" },
|
||||
},
|
||||
],
|
||||
[
|
||||
{
|
||||
toolCall: (call) => ({
|
||||
...call,
|
||||
detail: { type: "unknown", input: call.input, output: null },
|
||||
}),
|
||||
},
|
||||
],
|
||||
);
|
||||
expect(rows.at(-1)?.detail).toEqual({
|
||||
type: "unknown",
|
||||
input: { command: "npm test" },
|
||||
output: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("shows the call's row on its approval", async () => {
|
||||
const harness = connectorHarness({
|
||||
handleRequest(runtime, request) {
|
||||
if (request.method !== "session/prompt") return false;
|
||||
void runtime.request("session/request_permission", {
|
||||
sessionId: "connector-session",
|
||||
toolCall: {
|
||||
toolCallId: "edit-1",
|
||||
title: "Edit a.ts",
|
||||
kind: "edit",
|
||||
status: "pending",
|
||||
content: [{ type: "diff", path: "/repo/a.ts", oldText: "a", newText: "b" }],
|
||||
},
|
||||
options: [
|
||||
{ optionId: "allow", name: "Allow edit", kind: "allow_once" },
|
||||
{ optionId: "deny", name: "Deny", kind: "reject_once" },
|
||||
],
|
||||
});
|
||||
return true;
|
||||
},
|
||||
});
|
||||
const connection = await runAcpProvider({
|
||||
id: "approval-rows",
|
||||
label: "Approval rows",
|
||||
connector: harness.connector,
|
||||
}).connect({ versions: [1], capabilities: ["prompt.message", "permission"] });
|
||||
const events: ProviderEvent[] = [];
|
||||
connection.onEvent((event) => events.push(event));
|
||||
try {
|
||||
await connection.send(openInput());
|
||||
await waitForEvent(events, (event) => event.type === "session.ready");
|
||||
await connection.send({
|
||||
type: "session.prompt",
|
||||
sessionId: "session-1",
|
||||
prompt: {
|
||||
clientMessageId: "edit",
|
||||
delivery: "auto",
|
||||
input: { type: "message", content: [{ type: "text", text: "Edit a.ts" }] },
|
||||
},
|
||||
});
|
||||
expect(
|
||||
await waitForEvent(events, (event) => event.type === "session.permission"),
|
||||
).toMatchObject({
|
||||
request: {
|
||||
id: "permission:edit-1",
|
||||
title: "Edit a.ts",
|
||||
detail: { type: "edit", filePath: "/repo/a.ts", oldString: "a", newString: "b" },
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("lists sessions across every page the agent returns", async () => {
|
||||
const pages: Record<string, { sessions: unknown[]; nextCursor?: string }> = {
|
||||
first: {
|
||||
sessions: [{ sessionId: "s1", cwd: "/repo", title: "One" }],
|
||||
nextCursor: "second",
|
||||
},
|
||||
second: { sessions: [{ sessionId: "s2", cwd: "/repo", title: "Two" }] },
|
||||
};
|
||||
const harness = connectorHarness({
|
||||
capabilities: { sessionCapabilities: { list: {} } },
|
||||
handleRequest(runtime, request) {
|
||||
if (request.method !== "session/list") return false;
|
||||
const { cursor } = request.params as { cursor?: string };
|
||||
runtime.respond(request, pages[cursor ?? "first"]);
|
||||
return true;
|
||||
},
|
||||
});
|
||||
const connection = await runAcpProvider({
|
||||
id: "paged-sessions",
|
||||
label: "Paged sessions",
|
||||
connector: harness.connector,
|
||||
}).connect({ versions: [1], capabilities: ["prompt.message", "session.list"] });
|
||||
const events: ProviderEvent[] = [];
|
||||
connection.onEvent((event) => events.push(event));
|
||||
try {
|
||||
await connection.send({ type: "sessions", requestId: "list" });
|
||||
const listed = await waitForEvent(events, (event) => event.type === "sessions");
|
||||
expect(listed.type === "sessions" && listed.sessions.map((session) => session.title)).toEqual(
|
||||
["One", "Two"],
|
||||
);
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("resumes the generic ACP adapter's saved Auto Accept toggle in the unattended mode", async () => {
|
||||
const harness = connectorHarness({
|
||||
configOptions: [
|
||||
{
|
||||
id: "edit_approval_policy",
|
||||
name: "Edits",
|
||||
category: "mode",
|
||||
type: "select",
|
||||
currentValue: "ask",
|
||||
options: [
|
||||
{ value: "ask", name: "Default" },
|
||||
{ value: "session", name: "Don't Ask" },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
const connection = await runAcpProvider({
|
||||
id: "former-generic",
|
||||
label: "Former generic",
|
||||
connector: harness.connector,
|
||||
acpOptions: {
|
||||
autoAcceptMode: { mode: { id: "full-access", label: "Full access" }, nativeMode: "ask" },
|
||||
},
|
||||
}).connect({ versions: [1], capabilities: ["prompt.message", "session.configure"] });
|
||||
const events: ProviderEvent[] = [];
|
||||
connection.onEvent((event) => events.push(event));
|
||||
try {
|
||||
const input = openInput();
|
||||
input.config.settings = { auto_accept: true };
|
||||
await connection.send(input);
|
||||
await waitForEvent(events, (event) => event.type === "session.ready");
|
||||
const configs = events.flatMap((event) =>
|
||||
event.type === "session.config" ? [event.config.mode] : [],
|
||||
);
|
||||
expect(configs.at(-1)).toBe("full-access");
|
||||
const sentOptions = harness.instances
|
||||
.flatMap((instance) => instance.requests)
|
||||
.filter((request) => request.method === "session/set_config_option")
|
||||
.map((request) => (request.params as { configId: string }).configId);
|
||||
expect(sentOptions).not.toContain("auto_accept");
|
||||
expect(events.some((event) => event.type === "request.failed")).toBe(false);
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps a mode chosen after the generic ACP adapter's Auto Accept toggle was saved", async () => {
|
||||
const harness = connectorHarness({
|
||||
configOptions: [
|
||||
{
|
||||
id: "edit_approval_policy",
|
||||
name: "Edits",
|
||||
category: "mode",
|
||||
type: "select",
|
||||
currentValue: "session",
|
||||
options: [
|
||||
{ value: "ask", name: "Default" },
|
||||
{ value: "session", name: "Don't Ask" },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
const connection = await runAcpProvider({
|
||||
id: "former-generic",
|
||||
label: "Former generic",
|
||||
connector: harness.connector,
|
||||
acpOptions: {
|
||||
autoAcceptMode: { mode: { id: "full-access", label: "Full access" }, nativeMode: "ask" },
|
||||
},
|
||||
}).connect({ versions: [1], capabilities: ["prompt.message", "session.configure"] });
|
||||
const events: ProviderEvent[] = [];
|
||||
connection.onEvent((event) => events.push(event));
|
||||
try {
|
||||
const input = openInput();
|
||||
input.config.mode = "ask";
|
||||
input.config.settings = { auto_accept: true };
|
||||
await connection.send(input);
|
||||
await waitForEvent(events, (event) => event.type === "session.ready");
|
||||
const configs = events.flatMap((event) =>
|
||||
event.type === "session.config" ? [event.config.mode] : [],
|
||||
);
|
||||
expect(configs.at(-1)).toBe("ask");
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -117,9 +117,14 @@ export interface AcpToolCallSnapshot {
|
||||
title: string;
|
||||
kind?: string;
|
||||
status: "pending" | "in_progress" | "completed" | "failed";
|
||||
/** The call's ACP `rawInput`. */
|
||||
input: JsonValue;
|
||||
/** The call's ACP `rawOutput`. */
|
||||
output: JsonValue;
|
||||
/** The call's ACP `content` blocks. An update that sends `content` replaces them. */
|
||||
content?: JsonValue;
|
||||
locations: readonly string[];
|
||||
/** The row Paseo shows. Without it, Paseo builds the standard row for the call's ACP `kind`. */
|
||||
detail?: ProviderToolCallDetail;
|
||||
}
|
||||
|
||||
@@ -150,9 +155,14 @@ export interface AcpTransformer {
|
||||
notification: { method: string; params: JsonValue },
|
||||
context: AcpContext,
|
||||
): AcpVendorUpdate | readonly AcpVendorUpdate[] | null;
|
||||
/** Rewrites each update of a tool call, merged with the call's earlier updates. */
|
||||
toolCall?(
|
||||
toolCall: AcpToolCallSnapshot,
|
||||
context: AcpContext & { mcpServerNames?: readonly string[] },
|
||||
context: AcpContext & {
|
||||
mcpServerNames?: readonly string[];
|
||||
/** The call as Paseo last presented it, after every transformer. Absent on its first update. */
|
||||
previous?: AcpToolCallSnapshot;
|
||||
},
|
||||
): AcpToolCallSnapshot;
|
||||
}
|
||||
|
||||
|
||||
@@ -368,6 +368,11 @@ export type ProviderInput =
|
||||
sessionId: string;
|
||||
changes: ProviderConfigChanges;
|
||||
}
|
||||
/**
|
||||
* Rewind to the supplied `token`. Completing the request (`request.completed`) guarantees the
|
||||
* plugin rewound to that exact point (removing that prompt and everything after it for
|
||||
* `"conversation"` and `"both"`).
|
||||
*/
|
||||
| {
|
||||
type: "session.revert";
|
||||
requestId: string;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user