mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-26 02:05:31 +00:00
Compare commits
44
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5fd6783c19 | ||
|
|
4719186fbb | ||
|
|
cd2bfa91a8 | ||
|
|
b26f19accd | ||
|
|
8aba8bde08 | ||
|
|
29c448ac96 | ||
|
|
e03503c0de | ||
|
|
16c8a188e0 | ||
|
|
325a65acac | ||
|
|
3c5654d2ab | ||
|
|
e531eb1f1a | ||
|
|
a462c43de2 | ||
|
|
511306bd25 | ||
|
|
eed84c01f1 | ||
|
|
6d21e28e06 | ||
|
|
4b42ae6c17 | ||
|
|
c228a3acac | ||
|
|
1b6308502f | ||
|
|
9e3107fcb7 | ||
|
|
5033ad0249 | ||
|
|
b7af3da71f | ||
|
|
2789421fbd | ||
|
|
b7b5acf086 | ||
|
|
bf83a03ce9 | ||
|
|
80240eb851 | ||
|
|
0c11263d4d | ||
|
|
28c9806da8 | ||
|
|
a0add767c0 | ||
|
|
25f637e57c | ||
|
|
53fa9524cf | ||
|
|
5a8383d237 | ||
|
|
cf3caefa14 | ||
|
|
c747a58871 | ||
|
|
c36d398829 | ||
|
|
183bc736ec | ||
|
|
c4ce21a237 | ||
|
|
9a2236dac3 | ||
|
|
ecd0dd083e | ||
|
|
10c443a32b | ||
|
|
457d8d6ec5 | ||
|
|
80879eaf7c | ||
|
|
dc85c2bfbc | ||
|
|
5ed1f8d108 | ||
|
|
4178497d3d |
@@ -55,6 +55,7 @@ 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/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-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/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-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/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, the vendored library fork, 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 |
|
||||||
|
|||||||
@@ -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,
|
processes and subscriptions while retaining its Paseo identity, persistence handle, timeline,
|
||||||
workspace, labels, title, usage, attention, timestamps, and parent relationship. Opening or prompting
|
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
|
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
|
same Paseo agent ID. Resume does not read provider history when the agent already has a timeline;
|
||||||
primed.
|
see [owned history](timeline-sync.md#owned-history).
|
||||||
|
|
||||||
Reload releases the old runtime before resuming its durable session: an idle provider process can
|
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
|
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 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
|
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.
|
`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.
|
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
|
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
|
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
|
`error` and `finished` otherwise, without sending a new notification. Opening a workspace restores
|
||||||
|
|||||||
@@ -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/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/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/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/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/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 |
|
| `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.
|
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.
|
- 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.
|
- 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
|
## Right-sidebar boundary: directory-backed vs workspace-owned
|
||||||
|
|
||||||
@@ -478,6 +479,7 @@ Providers that can accept native tool definitions should set `supportsNativePase
|
|||||||
```
|
```
|
||||||
$PASEO_HOME/
|
$PASEO_HOME/
|
||||||
├── agents/{cwd-with-dashes}/{agent-id}.json # Agent record
|
├── agents/{cwd-with-dashes}/{agent-id}.json # Agent record
|
||||||
|
├── paseo.db # Daemon database (SQLite): agent timelines
|
||||||
├── projects/projects.json # Project registry
|
├── projects/projects.json # Project registry
|
||||||
├── projects/workspaces.json # Workspace registry
|
├── projects/workspaces.json # Workspace registry
|
||||||
├── projects/icons/ # Custom project icon images
|
├── projects/icons/ # Custom project icon images
|
||||||
|
|||||||
+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
|
`worktreeRoot` after its last active reference disappears. Worktree recovery recreates that backing
|
||||||
checkout from `mainRepoRoot`, then restores the relative path from `worktreeRoot` to `cwd`.
|
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`).
|
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)
|
├── daemon-keypair.json # E2EE keypair for relay (mode 0600)
|
||||||
├── paseo.pid # Daemon PID lock file
|
├── paseo.pid # Daemon PID lock file
|
||||||
├── local-credential # Per-run local client credential (mode 0600)
|
├── 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)
|
├── daemon.log # Default log file (path configurable)
|
||||||
├── agents/
|
├── agents/
|
||||||
│ └── {sanitized-cwd}/
|
│ └── {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
|
## 2. Daemon Configuration
|
||||||
|
|
||||||
**Path:** `$PASEO_HOME/config.json`
|
**Path:** `$PASEO_HOME/config.json`
|
||||||
|
|||||||
@@ -10,7 +10,6 @@ Authoritative terminology. UI label wins. Don't invent synonyms; use what's here
|
|||||||
- **Agent** — See **Agent session**. UI still says "Agent" / "New Agent" in places, but moving toward **Agent session** as the canonical term. Code: `AgentSnapshotPayload` (`packages/protocol/src/messages.ts:608`). Forbidden: "Task", "Job", "Run".
|
- **Agent** — See **Agent session**. UI still says "Agent" / "New Agent" in places, but moving toward **Agent session** as the canonical term. Code: `AgentSnapshotPayload` (`packages/protocol/src/messages.ts:608`). Forbidden: "Task", "Job", "Run".
|
||||||
- **Daemon** — Local Paseo server process; identified by `serverId`. UI: "Daemon" (system contexts only). Code: `serverId` in `ServerInfoStatusPayloadSchema` (`packages/protocol/src/messages.ts:1936`), `DaemonClient` (`packages/client/src/daemon-client.ts`).
|
- **Daemon** — Local Paseo server process; identified by `serverId`. UI: "Daemon" (system contexts only). Code: `serverId` in `ServerInfoStatusPayloadSchema` (`packages/protocol/src/messages.ts:1936`), `DaemonClient` (`packages/client/src/daemon-client.ts`).
|
||||||
- **Host** — Client-side connection profile pointing at a daemon; bundles one or more `HostConnection`s. UI: "Host" / "Add host" / "Switch host". Code: `HostProfile` (`packages/app/src/types/host-connection.ts:37`). Forbidden: "Connection" (means `HostConnection`, not host).
|
- **Host** — Client-side connection profile pointing at a daemon; bundles one or more `HostConnection`s. UI: "Host" / "Add host" / "Switch host". Code: `HostProfile` (`packages/app/src/types/host-connection.ts:37`). Forbidden: "Connection" (means `HostConnection`, not host).
|
||||||
- **Device** — A computer or phone running a Paseo client. Open **Devices** in a host’s settings to connect another device.
|
|
||||||
- **Host badge** — The item on a sidebar workspace row's meta row naming which host that workspace lives on. Three things gate it, and they compose as a lattice rather than competing: the sidebar must span more than one host (automatic), **Show → Host** in the sidebar's display preferences must be on (global, all hosts at once), and then that host's own display mode decides _how_ it draws — **Name** / **Icon only** / **Hidden**. Name, color, and display mode are per-host, per-device, and live client-side on `HostProfile.appearance`; nothing about it reaches the daemon. Never add a fourth way to hide it. UI: the "Appearance" group on a host's settings page, and the "Show" submenu in the sidebar's display preferences. Code: `selectHostBadges` (`packages/app/src/hosts/appearance.ts`) takes the first two as its `enabled` input; `WorkspaceMetaRow` (`packages/app/src/components/sidebar/workspace-meta-row/index.tsx`) draws it. Don't confuse with **Status pill**, which reports state rather than identity.
|
- **Host badge** — The item on a sidebar workspace row's meta row naming which host that workspace lives on. Three things gate it, and they compose as a lattice rather than competing: the sidebar must span more than one host (automatic), **Show → Host** in the sidebar's display preferences must be on (global, all hosts at once), and then that host's own display mode decides _how_ it draws — **Name** / **Icon only** / **Hidden**. Name, color, and display mode are per-host, per-device, and live client-side on `HostProfile.appearance`; nothing about it reaches the daemon. Never add a fourth way to hide it. UI: the "Appearance" group on a host's settings page, and the "Show" submenu in the sidebar's display preferences. Code: `selectHostBadges` (`packages/app/src/hosts/appearance.ts`) takes the first two as its `enabled` input; `WorkspaceMetaRow` (`packages/app/src/components/sidebar/workspace-meta-row/index.tsx`) draws it. Don't confuse with **Status pill**, which reports state rather than identity.
|
||||||
- **Project host entry** — One row in a project for a single (project, daemon) pair, aggregating that daemon's workspaces in the project. Internal. Code: `ProjectHostEntry` (`packages/app/src/utils/projects.ts:11`). Don't introduce "Checkout" as a synonym.
|
- **Project host entry** — One row in a project for a single (project, daemon) pair, aggregating that daemon's workspaces in the project. Internal. Code: `ProjectHostEntry` (`packages/app/src/utils/projects.ts:11`). Don't introduce "Checkout" as a synonym.
|
||||||
- **Placement** — One workspace's stable foreign-key relationship to its project plus its git checkout snapshot. Internal. An explicit creation `projectId` is authoritative when active.
|
- **Placement** — One workspace's stable foreign-key relationship to its project plus its git checkout snapshot. Internal. An explicit creation `projectId` is authoritative when active.
|
||||||
|
|||||||
+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.
|
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.
|
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,
|
Pagination bounds each read, not total resident history. Streaming overhead must remain
|
||||||
then replaces the previous tool state or merges into the current text item. Intermediate payloads
|
proportional to the retained transcript. Cumulative text snapshots must be released after their
|
||||||
are never retained for history or catch-up. Provider history is the durable transcript authority
|
deltas have been consumed.
|
||||||
and rebuilds the projection when an agent resumes.
|
|
||||||
|
|
||||||
Pagination bounds each read, not total resident history. Active and idle agents retain their
|
|
||||||
projected transcript; archive releases it and later history reads rebuild it from the provider.
|
|
||||||
Streaming overhead must remain proportional to the retained transcript. Cumulative text snapshots
|
|
||||||
must be released after their deltas have been consumed.
|
|
||||||
|
|
||||||
The invariants are:
|
The invariants are:
|
||||||
|
|
||||||
@@ -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
|
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.
|
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
|
## Presence is not delivery
|
||||||
|
|
||||||
Client heartbeat reports presence:
|
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.
|
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
|
- 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.
|
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
|
latest tail. The replacement reconciles positioned live rows beyond its coverage and unresolved
|
||||||
local submissions; it never retains two discontiguous canonical ranges.
|
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
|
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.
|
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
|
## Provider child history
|
||||||
|
|
||||||
Child transcripts use the same projected-page reconciliation as the main conversation. The client
|
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.
|
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
|
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
|
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
|
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.
|
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
|
## Relevant code
|
||||||
|
|
||||||
|
- Server owned history: `packages/server/src/server/agent/timeline/`
|
||||||
- Server live stream forwarding: `packages/server/src/server/session.ts`
|
- Server live stream forwarding: `packages/server/src/server/session.ts`
|
||||||
- App sync planning: `packages/app/src/timeline/timeline-sync-plan.ts`
|
- App sync planning: `packages/app/src/timeline/timeline-sync-plan.ts`
|
||||||
- App viewed-agent synchronization: `packages/app/src/timeline/viewed-timeline-sync.ts`
|
- App viewed-agent synchronization: `packages/app/src/timeline/viewed-timeline-sync.ts`
|
||||||
|
|||||||
+1
-1
@@ -1 +1 @@
|
|||||||
sha256-TAVzJzziWDAapQkG4TLkLzOlodkdFNKSl3y/Tm9HB28=
|
sha256-IAhKhkolW4xvFvMaAEFdhYvPAhTm2azsqbGMKCKL3q0=
|
||||||
|
|||||||
Generated
+20
-2
@@ -45,6 +45,9 @@
|
|||||||
"react-dom": "19.2.3",
|
"react-dom": "19.2.3",
|
||||||
"typescript": "^5.9.3",
|
"typescript": "^5.9.3",
|
||||||
"ws": "^8.20.0"
|
"ws": "^8.20.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=22.16.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@0no-co/graphql.web": {
|
"node_modules/@0no-co/graphql.web": {
|
||||||
@@ -39719,6 +39722,9 @@
|
|||||||
"typescript": "^5.2.2",
|
"typescript": "^5.2.2",
|
||||||
"vitest": "^4.1.6",
|
"vitest": "^4.1.6",
|
||||||
"zx": "^8.8.5"
|
"zx": "^8.8.5"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=22.16.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"packages/cli/node_modules/@vitest/expect": {
|
"packages/cli/node_modules/@vitest/expect": {
|
||||||
@@ -40625,7 +40631,6 @@
|
|||||||
"p-limit": "^7.3.0",
|
"p-limit": "^7.3.0",
|
||||||
"p-memoize": "^8.0.0",
|
"p-memoize": "^8.0.0",
|
||||||
"p-throttle": "^8.1.0",
|
"p-throttle": "^8.1.0",
|
||||||
"parse5": "^7.3.0",
|
|
||||||
"pino": "^10.2.0",
|
"pino": "^10.2.0",
|
||||||
"pino-pretty": "^13.1.3",
|
"pino-pretty": "^13.1.3",
|
||||||
"qrcode": "^1.5.4",
|
"qrcode": "^1.5.4",
|
||||||
@@ -40647,7 +40652,7 @@
|
|||||||
"@playwright/test": "^1.56.1",
|
"@playwright/test": "^1.56.1",
|
||||||
"@types/express": "^4.17.20",
|
"@types/express": "^4.17.20",
|
||||||
"@types/markdown-it": "^14.2.0",
|
"@types/markdown-it": "^14.2.0",
|
||||||
"@types/node": "^20.9.0",
|
"@types/node": "^22.16.0",
|
||||||
"@types/qrcode": "^1.5.6",
|
"@types/qrcode": "^1.5.6",
|
||||||
"@types/uuid": "^9.0.7",
|
"@types/uuid": "^9.0.7",
|
||||||
"@types/ws": "^8.5.8",
|
"@types/ws": "^8.5.8",
|
||||||
@@ -40655,6 +40660,9 @@
|
|||||||
"cross-env": "^10.1.0",
|
"cross-env": "^10.1.0",
|
||||||
"tsx": "^4.6.0",
|
"tsx": "^4.6.0",
|
||||||
"vitest": "^4.1.6"
|
"vitest": "^4.1.6"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=22.16.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"packages/server/node_modules/@esbuild/aix-ppc64": {
|
"packages/server/node_modules/@esbuild/aix-ppc64": {
|
||||||
@@ -41102,6 +41110,16 @@
|
|||||||
"@types/mdurl": "^2"
|
"@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": {
|
"packages/server/node_modules/@vitest/expect": {
|
||||||
"version": "4.1.6",
|
"version": "4.1.6",
|
||||||
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.6.tgz",
|
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.6.tgz",
|
||||||
|
|||||||
@@ -169,5 +169,8 @@
|
|||||||
"tiny-async-pool": {
|
"tiny-async-pool": {
|
||||||
"semver@^5": "5.7.2"
|
"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 { expectNearBottom, scrollChatAwayFromBottom } from "../support/helpers/agent-bottom-anchor";
|
||||||
import { holdRewindCompletion } from "../support/helpers/agent-timeline-gate";
|
import { holdRewindCompletion } from "../support/helpers/agent-timeline-gate";
|
||||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
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(
|
async function completeSubmittedTurn(
|
||||||
page: Page,
|
page: Page,
|
||||||
@@ -48,26 +55,102 @@ async function expectTurnCompletesNormally(
|
|||||||
await expectAgentIdle(page);
|
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.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,
|
page,
|
||||||
}) => {
|
}) => {
|
||||||
test.setTimeout(90_000);
|
test.setTimeout(150_000);
|
||||||
const retainedPrompt = "Keep this completed turn after rewind.";
|
const retainedPrompt = "Keep this completed turn after rewind.";
|
||||||
const rewoundPrompt = "Remove 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 preservedDraft = "Keep this human draft after rewind.";
|
||||||
const agent = await seedMockAgentWorkspace({
|
const agent = await seedMockAgentWorkspace({
|
||||||
repoPrefix: "message-rewind-roundtrip-",
|
repoPrefix: "message-rewind-roundtrip-",
|
||||||
title: "Message rewind roundtrip",
|
title: "Message rewind roundtrip",
|
||||||
model: "ten-second-stream",
|
model: "ten-second-stream",
|
||||||
});
|
});
|
||||||
|
const otherClient = await page.context().newPage();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const rewindCompletion = await holdRewindCompletion(page, agent.agentId);
|
const rewindCompletion = await holdRewindCompletion(page, agent.agentId);
|
||||||
await openAgentRoute(page, agent);
|
await openAgentRoute(page, agent);
|
||||||
await expectComposerVisible(page);
|
await expectComposerVisible(page);
|
||||||
await completeSubmittedTurn(page, agent, retainedPrompt);
|
const retainedMessage = await completeSubmittedTurn(page, agent, retainedPrompt);
|
||||||
const userMessage = await completeSubmittedTurn(page, agent, rewoundPrompt);
|
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, {
|
await scrollChatAwayFromBottom(page, {
|
||||||
deltaY: -900,
|
deltaY: -900,
|
||||||
minDistanceFromBottom: 300,
|
minDistanceFromBottom: 300,
|
||||||
@@ -76,19 +159,92 @@ test.describe("Agent message rewind", () => {
|
|||||||
await blurComposerInput(page);
|
await blurComposerInput(page);
|
||||||
rewindCompletion.clearTimelineStreamCount();
|
rewindCompletion.clearTimelineStreamCount();
|
||||||
|
|
||||||
const rewind = rewindConversation(page, userMessage, rewoundPrompt);
|
await test.step("the rewind stays pending until the daemon answers", async () => {
|
||||||
await rewindCompletion.waitForDelayedResponse();
|
const rewind = rewindConversation(page, userMessage, rewoundPrompt);
|
||||||
await expect(page.getByTestId("rewind-menu-conversation")).toBeDisabled();
|
await rewindCompletion.waitForDelayedResponse();
|
||||||
expect(rewindCompletion.timelineStreamCount()).toBe(0);
|
await expect(page.getByTestId("rewind-menu-conversation")).toBeDisabled();
|
||||||
rewindCompletion.release();
|
expect(rewindCompletion.timelineStreamCount()).toBe(0);
|
||||||
await rewind;
|
rewindCompletion.release();
|
||||||
|
await rewind;
|
||||||
|
});
|
||||||
|
|
||||||
await expect(page.getByTestId("user-message").filter({ hasText: rewoundPrompt })).toHaveCount(
|
await test.step("the rewound turn leaves without reloading the chat", async () => {
|
||||||
0,
|
await expectPrompts(page, [retainedPrompt]);
|
||||||
);
|
await expectStillMounted(retainedMessage);
|
||||||
await expectComposerDraft(page, preservedDraft);
|
expect(rewindCompletion.timelineFetchCount()).toBe(0);
|
||||||
await expectComposerNotFocused(page);
|
await expectComposerDraft(page, preservedDraft);
|
||||||
await expectNearBottom(page);
|
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 {
|
} finally {
|
||||||
await agent.cleanup();
|
await agent.cleanup();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ import {
|
|||||||
closeRelayPairing,
|
closeRelayPairing,
|
||||||
emptyHome,
|
emptyHome,
|
||||||
loadingScreen,
|
loadingScreen,
|
||||||
expectTailscaleSwitchDisabled,
|
openTailscaleDocsFromSetup,
|
||||||
paseoToolsSwitch,
|
paseoToolsSwitch,
|
||||||
pickTheme,
|
pickTheme,
|
||||||
projectSuggestion,
|
projectSuggestion,
|
||||||
@@ -403,10 +403,12 @@ test("setup choices carry over to Settings and the phone step pairs over relay",
|
|||||||
await continueSetup(page);
|
await continueSetup(page);
|
||||||
});
|
});
|
||||||
|
|
||||||
await test.step("Phone shows a disabled Tailscale switch and pairs over relay", async () => {
|
await test.step("Phone offers Tailscale docs and pairs over relay in its own modal", async () => {
|
||||||
await expectSetupStep(page, "Take your agents with you");
|
await expectSetupStep(page, "Take your agents with you");
|
||||||
await page.screenshot({ path: testInfo.outputPath("5-phone.png") });
|
await page.screenshot({ path: testInfo.outputPath("5-phone.png") });
|
||||||
await expectTailscaleSwitchDisabled(page);
|
expect(await openTailscaleDocsFromSetup(page)).toBe(
|
||||||
|
"https://paseo.sh/docs/connectivity#tailscale",
|
||||||
|
);
|
||||||
const pairing = await openRelayPairingFromSetup(page);
|
const pairing = await openRelayPairingFromSetup(page);
|
||||||
await expect(pairing.getByText("Enable relay?", { exact: true })).toBeVisible();
|
await expect(pairing.getByText("Enable relay?", { exact: true })).toBeVisible();
|
||||||
await enableRelayAndExpectOffer(page);
|
await enableRelayAndExpectOffer(page);
|
||||||
|
|||||||
@@ -1,24 +1,7 @@
|
|||||||
import { gotoAppShell, openSettings } from "../support/helpers/app";
|
|
||||||
import {
|
|
||||||
addDirectHostFromSettings,
|
|
||||||
openSettingsHostSection,
|
|
||||||
selectSettingsHost,
|
|
||||||
} from "../support/helpers/settings";
|
|
||||||
import { test } from "../support/fixtures";
|
import { test } from "../support/fixtures";
|
||||||
import { startTailscaleTestDaemon } from "../support/helpers/tailscale-daemon";
|
|
||||||
import { startIsolatedHostDaemon } from "../support/helpers/isolated-host-daemon";
|
import { startIsolatedHostDaemon } from "../support/helpers/isolated-host-daemon";
|
||||||
import {
|
import {
|
||||||
expectPairingOffer,
|
expectPairingOffer,
|
||||||
cancelTailscaleTurnOff,
|
|
||||||
confirmTailscaleTurnOff,
|
|
||||||
connectThroughTailscale,
|
|
||||||
disableTailscale,
|
|
||||||
enableTailscale,
|
|
||||||
expectTailscaleAddress,
|
|
||||||
expectTailscaleRowLoadsOn,
|
|
||||||
openSetupMobileStep,
|
|
||||||
slowConnectionToHost,
|
|
||||||
expectTailscaleUpdateRequired,
|
|
||||||
expectCompletePairingQr,
|
expectCompletePairingQr,
|
||||||
expectRelayConsent,
|
expectRelayConsent,
|
||||||
openPairDeviceModal,
|
openPairDeviceModal,
|
||||||
@@ -54,59 +37,3 @@ test("keeps the pairing QR code inside its compact tile", async ({ page }, testI
|
|||||||
await daemon.close();
|
await daemon.close();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
test("asks for a host update when Tailscale controls are unavailable", async ({ page }) => {
|
|
||||||
const daemon = await startIsolatedHostDaemon("pair-device-browser-old-host", {
|
|
||||||
publishedVersion: "0.13.0-beta.2",
|
|
||||||
});
|
|
||||||
try {
|
|
||||||
await gotoAppShell(page);
|
|
||||||
await openSettings(page);
|
|
||||||
await addDirectHostFromSettings(page, { host: "127.0.0.1", port: daemon.port });
|
|
||||||
await selectSettingsHost(page, daemon.serverId);
|
|
||||||
await openSettingsHostSection(page, daemon.serverId, "devices");
|
|
||||||
await expectTailscaleUpdateRequired(page);
|
|
||||||
} finally {
|
|
||||||
await daemon.close();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
test("turns Tailscale on and off from Devices, asking first over Tailscale", async ({
|
|
||||||
page,
|
|
||||||
baseURL,
|
|
||||||
}, testInfo) => {
|
|
||||||
test.skip(process.platform !== "linux", "Uses a second IPv4 loopback address");
|
|
||||||
// The journey opens Devices or the setup six times, two of them over a slowed connection.
|
|
||||||
test.setTimeout(120_000);
|
|
||||||
if (!baseURL) throw new Error("Expected the app base URL");
|
|
||||||
const daemon = await startTailscaleTestDaemon(baseURL);
|
|
||||||
try {
|
|
||||||
await preparePairingHost(page, daemon);
|
|
||||||
await enableTailscale(page);
|
|
||||||
await expectTailscaleAddress(page, daemon.tailscaleAddress);
|
|
||||||
await page.screenshot({ path: testInfo.outputPath("devices.png") });
|
|
||||||
|
|
||||||
await test.step("While its status loads, the row never shows Tailscale off", async () => {
|
|
||||||
const address = daemon.tailscaleAddress;
|
|
||||||
await expectTailscaleRowLoadsOn(page, address, () => preparePairingHost(page, daemon));
|
|
||||||
await expectTailscaleRowLoadsOn(page, address, () => openSetupMobileStep(page, daemon));
|
|
||||||
const restoreSpeed = await slowConnectionToHost(page, daemon.port, 300);
|
|
||||||
await expectTailscaleRowLoadsOn(page, address, () => openSetupMobileStep(page, daemon));
|
|
||||||
await expectTailscaleRowLoadsOn(page, address, () => preparePairingHost(page, daemon));
|
|
||||||
restoreSpeed();
|
|
||||||
});
|
|
||||||
|
|
||||||
await disableTailscale(page, daemon.tailscaleAddress);
|
|
||||||
|
|
||||||
await test.step("Over Tailscale, turning it off asks first and Cancel changes nothing", async () => {
|
|
||||||
await enableTailscale(page);
|
|
||||||
await connectThroughTailscale(page, daemon);
|
|
||||||
await cancelTailscaleTurnOff(page, daemon.tailscaleAddress);
|
|
||||||
});
|
|
||||||
await test.step("Confirming turns it off and cuts this connection", async () => {
|
|
||||||
await confirmTailscaleTurnOff(page, daemon.tailscaleAddress);
|
|
||||||
});
|
|
||||||
} finally {
|
|
||||||
await daemon.close();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|||||||
@@ -235,7 +235,7 @@ test.describe("Rewind sheet", () => {
|
|||||||
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
|
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
|
||||||
await expect(userMessage(page, secondPrompt)).toHaveCount(0);
|
await expect(userMessage(page, secondPrompt)).toHaveCount(0);
|
||||||
await expect(page.getByText("Cycle 1", { exact: true })).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 expectComposerDraft(page, firstPrompt);
|
||||||
await expectComposerFocused(page);
|
await expectComposerFocused(page);
|
||||||
|
|
||||||
@@ -243,7 +243,7 @@ test.describe("Rewind sheet", () => {
|
|||||||
await expectUserMessageVisible(page, replacementPrompt);
|
await expectUserMessageVisible(page, replacementPrompt);
|
||||||
await expect(userMessage(page, secondPrompt)).toHaveCount(0);
|
await expect(userMessage(page, secondPrompt)).toHaveCount(0);
|
||||||
await expect(page.getByText("Cycle 1", { exact: true })).toHaveCount(0);
|
await expect(page.getByText("Cycle 1", { exact: true })).toHaveCount(0);
|
||||||
await expectUserMessageCount(page, 2);
|
await expectUserMessageCount(page, 1);
|
||||||
|
|
||||||
await fillComposerDraft(page, "");
|
await fillComposerDraft(page, "");
|
||||||
await composerLocator(page).evaluate((element) => element.blur());
|
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 expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
|
||||||
await expectComposerDraft(page, "");
|
await expectComposerDraft(page, "");
|
||||||
await expectComposerNotFocused(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 fillComposerDraft(page, "");
|
||||||
await composerLocator(page).evaluate((element) => element.blur());
|
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 expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
|
||||||
await expectComposerDraft(page, replacementPrompt);
|
await expectComposerDraft(page, replacementPrompt);
|
||||||
await expectComposerFocused(page);
|
await expectComposerFocused(page);
|
||||||
await expectUserMessageCount(page, 1);
|
await expectUserMessageCount(page, 0);
|
||||||
} finally {
|
} finally {
|
||||||
await session.cleanup();
|
await session.cleanup();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
// Start on Settings > Host > Devices with relay enabled in the Android app.
|
// Start on Settings > Host > Pair device with relay enabled in the Android app.
|
||||||
// node packages/app/e2e/mobile/pair-device/android.mjs <agent-device-session>
|
// node packages/app/e2e/mobile/pair-device/android.mjs <agent-device-session>
|
||||||
import assert from "node:assert/strict";
|
import assert from "node:assert/strict";
|
||||||
import { execFileSync } from "node:child_process";
|
import { execFileSync } from "node:child_process";
|
||||||
@@ -13,7 +13,11 @@ function ad(...args) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
ad("press", 'label="Relay"', "--settle");
|
ad(
|
||||||
|
"press",
|
||||||
|
'label="Pair a device, Scan a QR code or copy a link to connect your phone to this host"',
|
||||||
|
"--settle",
|
||||||
|
);
|
||||||
ad("wait", "text", "Pairing QR code", "10000");
|
ad("wait", "text", "Pairing QR code", "10000");
|
||||||
const { data } = JSON.parse(ad("snapshot", "-i", "--json"));
|
const { data } = JSON.parse(ad("snapshot", "-i", "--json"));
|
||||||
const sheet = data.nodes.find((node) => node.label === "Bottom Sheet");
|
const sheet = data.nodes.find((node) => node.label === "Bottom Sheet");
|
||||||
|
|||||||
@@ -31,6 +31,8 @@ export interface RewindCompletionGate {
|
|||||||
clearTimelineStreamCount(): void;
|
clearTimelineStreamCount(): void;
|
||||||
release(): void;
|
release(): void;
|
||||||
timelineStreamCount(): number;
|
timelineStreamCount(): number;
|
||||||
|
/** Timeline reads this page sent since the last clear. */
|
||||||
|
timelineFetchCount(): number;
|
||||||
waitForDelayedResponse(): Promise<void>;
|
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(
|
export async function holdRewindCompletion(
|
||||||
page: Page,
|
page: Page,
|
||||||
agentId: string,
|
agentId: string,
|
||||||
): Promise<RewindCompletionGate> {
|
): Promise<RewindCompletionGate> {
|
||||||
let released = false;
|
let released = false;
|
||||||
let timelineStreamCount = 0;
|
let timelineStreamCount = 0;
|
||||||
|
let timelineFetchCount = 0;
|
||||||
const delayedForwards: Array<() => void> = [];
|
const delayedForwards: Array<() => void> = [];
|
||||||
let resolveDelayedResponse: (() => void) | null = null;
|
let resolveDelayedResponse: (() => void) | null = null;
|
||||||
const delayedResponse = new Promise<void>((resolve) => {
|
const delayedResponse = new Promise<void>((resolve) => {
|
||||||
@@ -200,7 +210,16 @@ export async function holdRewindCompletion(
|
|||||||
|
|
||||||
await page.routeWebSocket(daemonWsRoutePattern(), (ws) => {
|
await page.routeWebSocket(daemonWsRoutePattern(), (ws) => {
|
||||||
const server = ws.connectToServer();
|
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) => {
|
server.onMessage((message) => {
|
||||||
const sessionMessage = getSessionMessage(message);
|
const sessionMessage = getSessionMessage(message);
|
||||||
const payload = sessionMessage ? getPayload(sessionMessage) : null;
|
const payload = sessionMessage ? getPayload(sessionMessage) : null;
|
||||||
@@ -216,11 +235,11 @@ export async function holdRewindCompletion(
|
|||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
!released &&
|
!released &&
|
||||||
(sessionMessage?.type === "agent.rewind.response" ||
|
sessionMessage &&
|
||||||
sessionMessage?.type === "agent.timeline.replacement") &&
|
REWIND_COMPLETION_MESSAGES.has(String(sessionMessage.type)) &&
|
||||||
payload?.agentId === agentId
|
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.
|
// Hold it with the response so the pending-state assertion observes a pending rewind.
|
||||||
delayedForwards.push(() => ws.send(message));
|
delayedForwards.push(() => ws.send(message));
|
||||||
if (sessionMessage.type === "agent.rewind.response") resolveDelayedResponse?.();
|
if (sessionMessage.type === "agent.rewind.response") resolveDelayedResponse?.();
|
||||||
@@ -233,6 +252,7 @@ export async function holdRewindCompletion(
|
|||||||
return {
|
return {
|
||||||
clearTimelineStreamCount() {
|
clearTimelineStreamCount() {
|
||||||
timelineStreamCount = 0;
|
timelineStreamCount = 0;
|
||||||
|
timelineFetchCount = 0;
|
||||||
},
|
},
|
||||||
release() {
|
release() {
|
||||||
released = true;
|
released = true;
|
||||||
@@ -241,6 +261,7 @@ export async function holdRewindCompletion(
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
timelineStreamCount: () => timelineStreamCount,
|
timelineStreamCount: () => timelineStreamCount,
|
||||||
|
timelineFetchCount: () => timelineFetchCount,
|
||||||
waitForDelayedResponse: () => delayedResponse,
|
waitForDelayedResponse: () => delayedResponse,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import { promisify } from "node:util";
|
import { promisify } from "node:util";
|
||||||
import { once } from "node:events";
|
|
||||||
import {
|
import {
|
||||||
spawn,
|
spawn,
|
||||||
execFile,
|
execFile,
|
||||||
@@ -12,7 +11,6 @@ import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
|||||||
import net from "node:net";
|
import net from "node:net";
|
||||||
import { tmpdir } from "node:os";
|
import { tmpdir } from "node:os";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { WebSocket } from "ws";
|
|
||||||
import { withDisabledE2ESpeechEnv } from "./speech-env";
|
import { withDisabledE2ESpeechEnv } from "./speech-env";
|
||||||
import { killProcessTree, spawnTsx } from "./spawn-node";
|
import { killProcessTree, spawnTsx } from "./spawn-node";
|
||||||
|
|
||||||
@@ -66,14 +64,12 @@ export async function getAvailableHostDaemonPort(): Promise<number> {
|
|||||||
* Resolves once this daemon answers on its port. An open TCP port is not
|
* Resolves once this daemon answers on its port. An open TCP port is not
|
||||||
* enough: the port is released before the daemon binds it, and whatever takes
|
* enough: the port is released before the daemon binds it, and whatever takes
|
||||||
* it in between also accepts connections while the daemon exits with
|
* it in between also accepts connections while the daemon exits with
|
||||||
* EADDRINUSE. Only the daemon's own status reports its server id. Published
|
* EADDRINUSE. Only the daemon's own status reports its server id.
|
||||||
* daemons can serve status before they accept WebSocket upgrades.
|
|
||||||
*/
|
*/
|
||||||
async function waitForServer(
|
async function waitForServer(
|
||||||
port: number,
|
port: number,
|
||||||
child: ChildProcess,
|
child: ChildProcess,
|
||||||
identity: { serverId: string; paseoHome: string },
|
identity: { serverId: string; paseoHome: string },
|
||||||
published: boolean,
|
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const deadline = Date.now() + 90_000;
|
const deadline = Date.now() + 90_000;
|
||||||
let lastError: unknown = null;
|
let lastError: unknown = null;
|
||||||
@@ -86,10 +82,7 @@ async function waitForServer(
|
|||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const serverId = await readServerId(port, identity.paseoHome);
|
const serverId = await readServerId(port, identity.paseoHome);
|
||||||
if (serverId === identity.serverId) {
|
if (serverId === identity.serverId) return;
|
||||||
if (published) await checkWebSocketUpgrade(port);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
lastError = new Error(`Port ${port} is served by ${serverId}, not ${identity.serverId}`);
|
lastError = new Error(`Port ${port} is served by ${serverId}, not ${identity.serverId}`);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
lastError = error;
|
lastError = error;
|
||||||
@@ -104,12 +97,6 @@ async function waitForServer(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function checkWebSocketUpgrade(port: number): Promise<void> {
|
|
||||||
const socket = new WebSocket(`ws://127.0.0.1:${port}/ws`, { handshakeTimeout: 1_000 });
|
|
||||||
await once(socket, "open");
|
|
||||||
socket.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Reads the server id from the daemon's status route. The route needs a bearer
|
* Reads the server id from the daemon's status route. The route needs a bearer
|
||||||
* on a password-protected daemon; the daemon accepts the local credential it
|
* on a password-protected daemon; the daemon accepts the local credential it
|
||||||
@@ -259,7 +246,7 @@ export async function startIsolatedHostDaemon(
|
|||||||
});
|
});
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await waitForServer(port, spawned, { serverId, paseoHome }, Boolean(publishedPackageRoot));
|
await waitForServer(port, spawned, { serverId, paseoHome });
|
||||||
return spawned;
|
return spawned;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
|
|||||||
@@ -161,7 +161,7 @@ export async function finishSetup(page: Page): Promise<void> {
|
|||||||
/** Opens the Phone step's Relay row: the pair device modal, over setup. */
|
/** Opens the Phone step's Relay row: the pair device modal, over setup. */
|
||||||
export async function openRelayPairingFromSetup(page: Page): Promise<Locator> {
|
export async function openRelayPairingFromSetup(page: Page): Promise<Locator> {
|
||||||
await setupModal(page).getByRole("button", { name: "Relay", exact: true }).click();
|
await setupModal(page).getByRole("button", { name: "Relay", exact: true }).click();
|
||||||
const pairing = page.getByTestId("devices-relay-pairing");
|
const pairing = page.getByTestId("onboarding-pair-device-card");
|
||||||
await expect(pairing).toBeVisible();
|
await expect(pairing).toBeVisible();
|
||||||
return pairing;
|
return pairing;
|
||||||
}
|
}
|
||||||
@@ -171,9 +171,20 @@ export async function closeRelayPairing(pairing: Locator): Promise<void> {
|
|||||||
await expect(pairing).toHaveCount(0);
|
await expect(pairing).toHaveCount(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function expectTailscaleSwitchDisabled(page: Page): Promise<void> {
|
/** Clicks the Phone step's Tailscale row and returns the docs page it opened. */
|
||||||
const setup = setupModal(page);
|
export async function openTailscaleDocsFromSetup(page: Page): Promise<string> {
|
||||||
await expect(setup.getByRole("switch", { name: "Tailscale", exact: true })).toBeDisabled();
|
await page
|
||||||
|
.context()
|
||||||
|
.route("https://paseo.sh/**", (route) =>
|
||||||
|
route.fulfill({ contentType: "text/html", body: "<title>Paseo docs</title>" }),
|
||||||
|
);
|
||||||
|
const popup = page.waitForEvent("popup");
|
||||||
|
await setupModal(page).getByRole("link", { name: "Tailscale, Docs", exact: true }).click();
|
||||||
|
const docs = await popup;
|
||||||
|
await docs.waitForLoadState("domcontentloaded");
|
||||||
|
const url = docs.url();
|
||||||
|
await docs.close();
|
||||||
|
return url;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface SetupHost {
|
export interface SetupHost {
|
||||||
|
|||||||
@@ -9,8 +9,6 @@ import {
|
|||||||
selectSettingsHost,
|
selectSettingsHost,
|
||||||
} from "./settings";
|
} from "./settings";
|
||||||
import { expectAppRoute } from "./route-assertions";
|
import { expectAppRoute } from "./route-assertions";
|
||||||
import { wsRoutePatternForPort } from "./daemon-port";
|
|
||||||
import { goToSetupStep, showSetupAgainFromSettings } from "./onboarding";
|
|
||||||
import { buildSettingsHostSectionRoute } from "@/utils/host-routes";
|
import { buildSettingsHostSectionRoute } from "@/utils/host-routes";
|
||||||
|
|
||||||
interface PairingHostInput {
|
interface PairingHostInput {
|
||||||
@@ -62,33 +60,9 @@ export async function prepareLocalPairingHost(
|
|||||||
await preparePairingHost(page, daemon, additionalHosts);
|
await preparePairingHost(page, daemon, additionalHosts);
|
||||||
}
|
}
|
||||||
|
|
||||||
type PairingHost =
|
|
||||||
| Pick<IsolatedHostDaemon, "serverId" | "port">
|
|
||||||
| Pick<OutdatedDaemon, "serverId" | "endpoint">;
|
|
||||||
|
|
||||||
export async function preparePairingHost(
|
export async function preparePairingHost(
|
||||||
page: Page,
|
page: Page,
|
||||||
daemon: PairingHost,
|
daemon: IsolatedHostDaemon | OutdatedDaemon,
|
||||||
additionalHosts: PairingHostInput[] = [],
|
|
||||||
): Promise<void> {
|
|
||||||
await openAppOnPairingHost(page, daemon, additionalHosts);
|
|
||||||
await openSettings(page);
|
|
||||||
await openSettingsHost(page, daemon.serverId);
|
|
||||||
await expect(page.getByTestId("devices-relay")).toHaveCount(0);
|
|
||||||
await openSettingsHostSection(page, daemon.serverId, "devices");
|
|
||||||
await expect(page.getByTestId("devices-relay")).toBeVisible();
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Loads the app afresh with `daemon` as its first host, then opens the setup's Mobile step. */
|
|
||||||
export async function openSetupMobileStep(page: Page, daemon: PairingHost): Promise<void> {
|
|
||||||
await openAppOnPairingHost(page, daemon);
|
|
||||||
await showSetupAgainFromSettings(page);
|
|
||||||
await goToSetupStep(page, "Mobile");
|
|
||||||
}
|
|
||||||
|
|
||||||
async function openAppOnPairingHost(
|
|
||||||
page: Page,
|
|
||||||
daemon: PairingHost,
|
|
||||||
additionalHosts: PairingHostInput[] = [],
|
additionalHosts: PairingHostInput[] = [],
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
await seedSavedSettingsHosts(page, [
|
await seedSavedSettingsHosts(page, [
|
||||||
@@ -100,271 +74,20 @@ async function openAppOnPairingHost(
|
|||||||
...additionalHosts,
|
...additionalHosts,
|
||||||
]);
|
]);
|
||||||
await gotoAppShell(page);
|
await gotoAppShell(page);
|
||||||
}
|
await openSettings(page);
|
||||||
|
await openSettingsHost(page, daemon.serverId);
|
||||||
export async function enableTailscale(page: Page): Promise<void> {
|
await expect(page.getByTestId("host-page-pair-device-row")).toHaveCount(0);
|
||||||
const toggle = page.getByRole("switch", { name: "Tailscale", exact: true });
|
await openSettingsHostSection(page, daemon.serverId, "pair-device");
|
||||||
await expect(toggle).toBeEnabled();
|
await expect(page.getByTestId("host-page-pair-device-row")).toBeVisible();
|
||||||
await expect(toggle).not.toBeChecked();
|
|
||||||
await toggle.click();
|
|
||||||
await expect(toggle).toBeChecked();
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function expectTailscaleAddress(page: Page, address: string): Promise<void> {
|
|
||||||
const row = tailscaleAddressRow(page, address);
|
|
||||||
await expect(row).toBeVisible();
|
|
||||||
await expect(
|
|
||||||
row.getByText("On a phone with Tailscale, add a host at this address"),
|
|
||||||
).toBeVisible();
|
|
||||||
await expect(row.getByRole("button", { name: "Copy", exact: true })).toBeVisible();
|
|
||||||
const response = await fetch(`http://${address}/api/health`);
|
|
||||||
expect(response.ok).toBe(true);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The switch shows off as soon as it is tapped; the host stops listening when its answer lands. */
|
|
||||||
async function expectHostUnreachableAt(address: string): Promise<void> {
|
|
||||||
await expect
|
|
||||||
.poll(() =>
|
|
||||||
fetch(`http://${address}/api/health`).then(
|
|
||||||
() => "reachable",
|
|
||||||
() => "unreachable",
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.toBe("unreachable");
|
|
||||||
}
|
|
||||||
|
|
||||||
function tailscaleAddressRow(page: Page, address: string) {
|
|
||||||
return page.getByTestId("devices-tailscale-address").filter({ hasText: address });
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function disableTailscale(page: Page, address: string): Promise<void> {
|
|
||||||
const toggle = page.getByRole("switch", { name: "Tailscale", exact: true });
|
|
||||||
await expect(toggle).toBeEnabled();
|
|
||||||
await toggle.click();
|
|
||||||
await expect(toggle).not.toBeChecked();
|
|
||||||
await expect(tailscaleAddressRow(page, address)).toHaveCount(0);
|
|
||||||
await expectHostUnreachableAt(address);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Reopens the host over its Tailscale address, as a phone on the tailnet would reach it. */
|
|
||||||
export async function connectThroughTailscale(
|
|
||||||
page: Page,
|
|
||||||
daemon: { serverId: string; tailscaleAddress: string },
|
|
||||||
): Promise<void> {
|
|
||||||
await preparePairingHost(page, { serverId: daemon.serverId, endpoint: daemon.tailscaleAddress });
|
|
||||||
await expectTailscaleAddress(page, daemon.tailscaleAddress);
|
|
||||||
}
|
|
||||||
|
|
||||||
const TURN_OFF_QUESTION =
|
|
||||||
"Turn off Tailscale?\n\nThis device is connected through Tailscale and will lose its connection to the host.";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Taps the switch off over the Tailscale connection and cancels the question. Every state the row
|
|
||||||
* commits from the tap to after Cancel must still show Tailscale on with its address: nothing
|
|
||||||
* changes until the user confirms.
|
|
||||||
*/
|
|
||||||
export async function cancelTailscaleTurnOff(page: Page, address: string): Promise<void> {
|
|
||||||
const row = await recordTailscaleRow(page);
|
|
||||||
const question = answerNextDialog(page, "dismiss");
|
|
||||||
await page.getByRole("switch", { name: "Tailscale", exact: true }).click();
|
|
||||||
expect(await question).toBe(TURN_OFF_QUESTION);
|
|
||||||
await page.waitForTimeout(500);
|
|
||||||
expect(new Set((await row()).map((state) => `${state.value} ${state.address}`))).toEqual(
|
|
||||||
new Set(["on true"]),
|
|
||||||
);
|
|
||||||
await expect(page.getByRole("switch", { name: "Tailscale", exact: true })).toBeChecked();
|
|
||||||
await expect(tailscaleAddressRow(page, address)).toBeVisible();
|
|
||||||
expect((await fetch(`http://${address}/api/health`)).ok).toBe(true);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Confirms turning Tailscale off over the Tailscale connection, which cuts this app off the host.
|
|
||||||
* Without the host the row shows no value at all, on or off.
|
|
||||||
*/
|
|
||||||
export async function confirmTailscaleTurnOff(page: Page, address: string): Promise<void> {
|
|
||||||
const question = answerNextDialog(page, "accept");
|
|
||||||
await page.getByRole("switch", { name: "Tailscale", exact: true }).click();
|
|
||||||
expect(await question).toBe(TURN_OFF_QUESTION);
|
|
||||||
await expect(page.getByText("Host is not connected", { exact: true })).toBeVisible();
|
|
||||||
await expect(page.getByRole("switch", { name: "Tailscale", exact: true })).toHaveCount(0);
|
|
||||||
await expectHostUnreachableAt(address);
|
|
||||||
}
|
|
||||||
|
|
||||||
function answerNextDialog(page: Page, answer: "accept" | "dismiss"): Promise<string> {
|
|
||||||
return new Promise((resolve) => {
|
|
||||||
page.once("dialog", async (dialog) => {
|
|
||||||
resolve(dialog.message());
|
|
||||||
await (answer === "accept" ? dialog.accept() : dialog.dismiss());
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
interface TailscaleRowState {
|
|
||||||
/** `none` while the row shows no value yet. */
|
|
||||||
value: "on" | "off" | "none";
|
|
||||||
address: boolean;
|
|
||||||
hint: string;
|
|
||||||
labelTop: number;
|
|
||||||
hintTop: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Records every state the Tailscale row commits, painted or not: from now on in this page, and
|
|
||||||
* from the first paint of every page load after it. Recording again starts a new record.
|
|
||||||
*/
|
|
||||||
async function recordTailscaleRow(page: Page): Promise<() => Promise<TailscaleRowState[]>> {
|
|
||||||
const record = () => {
|
|
||||||
const host = window as unknown as {
|
|
||||||
tailscaleRow?: { states: unknown[]; last: string; sample(): void };
|
|
||||||
};
|
|
||||||
if (host.tailscaleRow) {
|
|
||||||
host.tailscaleRow.states = [];
|
|
||||||
host.tailscaleRow.last = "";
|
|
||||||
host.tailscaleRow.sample();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const isVisibleText = (element: Element, text?: string) =>
|
|
||||||
element.childElementCount === 0 &&
|
|
||||||
(text === undefined
|
|
||||||
? (element.textContent ?? "").trim() !== ""
|
|
||||||
: element.textContent === text) &&
|
|
||||||
element.getBoundingClientRect().height > 0;
|
|
||||||
const readValue = (toggle: Element | null) => {
|
|
||||||
if (!toggle) return "none";
|
|
||||||
return toggle.getAttribute("aria-checked") === "true" ? "on" : "off";
|
|
||||||
};
|
|
||||||
const read = () => {
|
|
||||||
const label = [...document.querySelectorAll("div, span")].find((element) =>
|
|
||||||
isVisibleText(element, "Tailscale"),
|
|
||||||
);
|
|
||||||
if (!label) return null;
|
|
||||||
let row: Element = label;
|
|
||||||
while (row.parentElement && !(row as HTMLElement).innerText.includes("\n")) {
|
|
||||||
row = row.parentElement;
|
|
||||||
}
|
|
||||||
const hint = [...row.querySelectorAll("div, span")].find(
|
|
||||||
(element) => element !== label && isVisibleText(element),
|
|
||||||
);
|
|
||||||
const toggle = document.querySelector('[role="switch"][aria-label="Tailscale"]');
|
|
||||||
return {
|
|
||||||
value: readValue(toggle),
|
|
||||||
address: document.querySelector('[data-testid="devices-tailscale-address"]') !== null,
|
|
||||||
hint: hint?.textContent ?? "",
|
|
||||||
labelTop: Math.round(label.getBoundingClientRect().top),
|
|
||||||
hintTop: Math.round(hint?.getBoundingClientRect().top ?? -1),
|
|
||||||
};
|
|
||||||
};
|
|
||||||
const recorder = {
|
|
||||||
states: [] as unknown[],
|
|
||||||
last: "",
|
|
||||||
sample() {
|
|
||||||
const state = read();
|
|
||||||
const key = JSON.stringify(state);
|
|
||||||
if (state && key !== recorder.last) recorder.states.push(state);
|
|
||||||
recorder.last = key;
|
|
||||||
},
|
|
||||||
};
|
|
||||||
host.tailscaleRow = recorder;
|
|
||||||
new MutationObserver(() => recorder.sample()).observe(document, {
|
|
||||||
subtree: true,
|
|
||||||
childList: true,
|
|
||||||
characterData: true,
|
|
||||||
attributes: true,
|
|
||||||
});
|
|
||||||
};
|
|
||||||
await page.addInitScript(record);
|
|
||||||
await page.evaluate(record);
|
|
||||||
return () =>
|
|
||||||
page.evaluate(
|
|
||||||
() =>
|
|
||||||
(window as unknown as { tailscaleRow: { states: TailscaleRowState[] } }).tailscaleRow
|
|
||||||
.states,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Runs `open`, which first shows the Tailscale row of a host with Tailscale on, and checks the row
|
|
||||||
* from its first state to its last: it starts with no value, never shows Tailscale off, and its
|
|
||||||
* label and hint keep their text and place until it settles on, with the address below.
|
|
||||||
*/
|
|
||||||
export async function expectTailscaleRowLoadsOn(
|
|
||||||
page: Page,
|
|
||||||
address: string,
|
|
||||||
open: () => Promise<void>,
|
|
||||||
): Promise<void> {
|
|
||||||
const row = await recordTailscaleRow(page);
|
|
||||||
await open();
|
|
||||||
await expect(page.getByRole("switch", { name: "Tailscale", exact: true })).toBeChecked();
|
|
||||||
await expect(tailscaleAddressRow(page, address)).toBeVisible();
|
|
||||||
const states = await row();
|
|
||||||
expect(states[0]?.value).toBe("none");
|
|
||||||
expect(states.filter((state) => state.value === "off")).toEqual([]);
|
|
||||||
expect(
|
|
||||||
new Set(states.map(({ hint, labelTop, hintTop }) => `${hint} ${labelTop} ${hintTop}`)).size,
|
|
||||||
).toBe(1);
|
|
||||||
expect(states.at(-1)).toMatchObject({ value: "on", address: true });
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Holds every message between the app and the host on `port` for `ms` in each direction, as on a
|
|
||||||
* slow network. The returned function brings the connection back to full speed.
|
|
||||||
*/
|
|
||||||
export async function slowConnectionToHost(
|
|
||||||
page: Page,
|
|
||||||
port: number,
|
|
||||||
ms: number,
|
|
||||||
): Promise<() => void> {
|
|
||||||
let delay = ms;
|
|
||||||
await page.routeWebSocket(wsRoutePatternForPort(String(port)), (app) => {
|
|
||||||
const host = app.connectToServer();
|
|
||||||
app.onMessage(
|
|
||||||
deliverInOrderAfter(
|
|
||||||
() => delay,
|
|
||||||
(message) => host.send(message),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
host.onMessage(
|
|
||||||
deliverInOrderAfter(
|
|
||||||
() => delay,
|
|
||||||
(message) => app.send(message),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
return () => {
|
|
||||||
delay = 0;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function deliverInOrderAfter(
|
|
||||||
delay: () => number,
|
|
||||||
deliver: (message: string | Buffer) => void,
|
|
||||||
): (message: string | Buffer) => void {
|
|
||||||
const queue: { at: number; message: string | Buffer }[] = [];
|
|
||||||
let timer: ReturnType<typeof setTimeout> | null = null;
|
|
||||||
const flush = () => {
|
|
||||||
timer = null;
|
|
||||||
while (queue[0] && queue[0].at <= Date.now()) deliver(queue.shift()!.message);
|
|
||||||
if (queue[0]) timer = setTimeout(flush, queue[0].at - Date.now());
|
|
||||||
};
|
|
||||||
return (message) => {
|
|
||||||
queue.push({ at: Math.max(Date.now() + delay(), queue.at(-1)?.at ?? 0), message });
|
|
||||||
if (!timer) flush();
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function expectTailscaleUpdateRequired(page: Page): Promise<void> {
|
|
||||||
await expect(page.getByRole("switch", { name: "Tailscale", exact: true })).toBeDisabled();
|
|
||||||
await expect(page.getByText("Update this host to use Tailscale", { exact: true })).toBeVisible();
|
|
||||||
await expect(page.getByRole("link", { name: "How to update", exact: true })).toBeVisible();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function openPairDeviceModal(page: Page): Promise<void> {
|
export async function openPairDeviceModal(page: Page): Promise<void> {
|
||||||
await page.getByRole("button", { name: "Relay", exact: true }).click();
|
await page.getByRole("button", { name: /Pair a device/ }).click();
|
||||||
await expect(page.getByTestId("devices-relay-pairing")).toBeVisible();
|
await expect(page.getByTestId("host-page-pair-device-card")).toBeVisible();
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function expectRelayConsent(page: Page): Promise<void> {
|
export async function expectRelayConsent(page: Page): Promise<void> {
|
||||||
const modal = page.getByTestId("devices-relay-pairing");
|
const modal = page.getByTestId("host-page-pair-device-card");
|
||||||
await expect(modal.getByText("Enable relay?", { exact: true })).toBeVisible();
|
await expect(modal.getByText("Enable relay?", { exact: true })).toBeVisible();
|
||||||
await expect(modal.getByText(/end-to-end encrypted/)).toBeVisible();
|
await expect(modal.getByText(/end-to-end encrypted/)).toBeVisible();
|
||||||
await expect(modal.getByRole("link", { name: "Read how Paseo relay works" })).toBeVisible();
|
await expect(modal.getByRole("link", { name: "Read how Paseo relay works" })).toBeVisible();
|
||||||
@@ -376,7 +99,7 @@ export async function expectRelayConsent(page: Page): Promise<void> {
|
|||||||
|
|
||||||
export async function declineRelay(page: Page): Promise<void> {
|
export async function declineRelay(page: Page): Promise<void> {
|
||||||
await page.getByRole("button", { name: "Not now", exact: true }).click();
|
await page.getByRole("button", { name: "Not now", exact: true }).click();
|
||||||
await expect(page.getByTestId("devices-relay-pairing")).toHaveCount(0);
|
await expect(page.getByTestId("host-page-pair-device-card")).toHaveCount(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function enableRelayAndExpectOffer(page: Page): Promise<void> {
|
export async function enableRelayAndExpectOffer(page: Page): Promise<void> {
|
||||||
@@ -401,10 +124,10 @@ export async function expectPairingOffer(page: Page): Promise<void> {
|
|||||||
|
|
||||||
export async function closePairDeviceModal(page: Page): Promise<void> {
|
export async function closePairDeviceModal(page: Page): Promise<void> {
|
||||||
await page
|
await page
|
||||||
.getByTestId("devices-relay-pairing")
|
.getByTestId("host-page-pair-device-card")
|
||||||
.getByRole("button", { name: "Close", exact: true })
|
.getByRole("button", { name: "Close", exact: true })
|
||||||
.click();
|
.click();
|
||||||
await expect(page.getByTestId("devices-relay-pairing")).toHaveCount(0);
|
await expect(page.getByTestId("host-page-pair-device-card")).toHaveCount(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function reloadAndOpenPairDevice(page: Page): Promise<void> {
|
export async function reloadAndOpenPairDevice(page: Page): Promise<void> {
|
||||||
@@ -422,7 +145,7 @@ export async function enableRelayAndExpectFailure(
|
|||||||
expectedError = "Relay is controlled by a daemon launch override",
|
expectedError = "Relay is controlled by a daemon launch override",
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
await page.getByRole("button", { name: "Enable relay", exact: true }).click();
|
await page.getByRole("button", { name: "Enable relay", exact: true }).click();
|
||||||
const modal = page.getByTestId("devices-relay-pairing");
|
const modal = page.getByTestId("host-page-pair-device-card");
|
||||||
await expect(modal.getByRole("alert")).toContainText(expectedError);
|
await expect(modal.getByRole("alert")).toContainText(expectedError);
|
||||||
await expect(modal.getByRole("button", { name: "Retry", exact: true })).toBeEnabled();
|
await expect(modal.getByRole("button", { name: "Retry", exact: true })).toBeEnabled();
|
||||||
await expect(modal.getByRole("textbox", { name: "Pairing link" })).toHaveCount(0);
|
await expect(modal.getByRole("textbox", { name: "Pairing link" })).toHaveCount(0);
|
||||||
@@ -432,7 +155,7 @@ export async function retryRelayAndExpectFailure(
|
|||||||
page: Page,
|
page: Page,
|
||||||
expectedError = "Relay is controlled by a daemon launch override",
|
expectedError = "Relay is controlled by a daemon launch override",
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const modal = page.getByTestId("devices-relay-pairing");
|
const modal = page.getByTestId("host-page-pair-device-card");
|
||||||
await modal.getByRole("button", { name: "Retry", exact: true }).click();
|
await modal.getByRole("button", { name: "Retry", exact: true }).click();
|
||||||
await expect(modal.getByRole("alert")).toContainText(expectedError);
|
await expect(modal.getByRole("alert")).toContainText(expectedError);
|
||||||
await expect(modal.getByRole("button", { name: "Retry", exact: true })).toBeEnabled();
|
await expect(modal.getByRole("button", { name: "Retry", exact: true })).toBeEnabled();
|
||||||
@@ -450,7 +173,7 @@ export async function openPairDeviceFromHome(page: Page): Promise<void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function expectRelayUpdateRequired(page: Page): Promise<void> {
|
export async function expectRelayUpdateRequired(page: Page): Promise<void> {
|
||||||
const modal = page.getByTestId("devices-relay-pairing");
|
const modal = page.getByTestId("host-page-pair-device-card");
|
||||||
await expect(
|
await expect(
|
||||||
modal.getByText("Update the host to enable relay from Paseo Desktop."),
|
modal.getByText("Update the host to enable relay from Paseo Desktop."),
|
||||||
).toBeVisible();
|
).toBeVisible();
|
||||||
@@ -472,15 +195,15 @@ export function observePairingOfferRequests(page: Page, daemon: OutdatedDaemon):
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function expectPairingDisconnected(page: Page): Promise<void> {
|
export async function expectPairingDisconnected(page: Page): Promise<void> {
|
||||||
const modal = page.getByTestId("devices-relay-pairing");
|
const modal = page.getByTestId("host-page-pair-device-card");
|
||||||
await expect(modal.getByRole("alert")).toContainText("Host is not connected");
|
await expect(modal.getByRole("alert")).toContainText("Host is not connected");
|
||||||
await expect(modal.getByRole("button", { name: "Retry", exact: true })).toBeVisible();
|
await expect(modal.getByRole("button", { name: "Retry", exact: true })).toBeVisible();
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function switchPairDeviceToHost(page: Page, serverId: string): Promise<void> {
|
export async function switchPairDeviceToHost(page: Page, serverId: string): Promise<void> {
|
||||||
await selectSettingsHost(page, serverId);
|
await selectSettingsHost(page, serverId);
|
||||||
await expectAppRoute(page, buildSettingsHostSectionRoute(serverId, "devices"));
|
await expectAppRoute(page, buildSettingsHostSectionRoute(serverId, "pair-device"));
|
||||||
await expect(page.getByTestId("devices-relay")).toBeVisible();
|
await expect(page.getByTestId("host-page-pair-device-row")).toBeVisible();
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function openRelaySecurityDocs(page: Page): Promise<void> {
|
export async function openRelaySecurityDocs(page: Page): Promise<void> {
|
||||||
|
|||||||
@@ -66,7 +66,7 @@ export type SettingsSection = keyof typeof SECTION_LABELS;
|
|||||||
type HostSection =
|
type HostSection =
|
||||||
| "projects"
|
| "projects"
|
||||||
| "connections"
|
| "connections"
|
||||||
| "devices"
|
| "pair-device"
|
||||||
| "agents"
|
| "agents"
|
||||||
| "metadata"
|
| "metadata"
|
||||||
| "voice"
|
| "voice"
|
||||||
|
|||||||
@@ -1,33 +0,0 @@
|
|||||||
import { once } from "node:events";
|
|
||||||
import path from "node:path";
|
|
||||||
import { z } from "zod";
|
|
||||||
import { killProcessTree, spawnTsx } from "./spawn-node";
|
|
||||||
|
|
||||||
const readySchema = z.object({ port: z.number(), serverId: z.string() });
|
|
||||||
|
|
||||||
export async function startTailscaleTestDaemon(origin: string) {
|
|
||||||
const entrypoint = path.resolve(
|
|
||||||
__dirname,
|
|
||||||
"../../../../server/src/server/test-utils/tailscale-daemon.ts",
|
|
||||||
);
|
|
||||||
const child = spawnTsx(entrypoint, [origin], {
|
|
||||||
stdio: ["ignore", "inherit", "inherit", "ipc"],
|
|
||||||
});
|
|
||||||
const signal = AbortSignal.timeout(30_000);
|
|
||||||
try {
|
|
||||||
const ready = await Promise.race([
|
|
||||||
once(child, "message", { signal }).then(([message]) => readySchema.parse(message)),
|
|
||||||
once(child, "exit", { signal }).then(([code]) => {
|
|
||||||
throw new Error(`Tailscale test daemon exited before startup with code ${code}`);
|
|
||||||
}),
|
|
||||||
]);
|
|
||||||
return {
|
|
||||||
...ready,
|
|
||||||
tailscaleAddress: `127.0.0.2:${ready.port}`,
|
|
||||||
close: () => killProcessTree(child),
|
|
||||||
};
|
|
||||||
} catch (error) {
|
|
||||||
await killProcessTree(child);
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -56,6 +56,7 @@ export function ChatFind({
|
|||||||
agentId,
|
agentId,
|
||||||
serverId,
|
serverId,
|
||||||
epoch,
|
epoch,
|
||||||
|
rewindSeq,
|
||||||
items,
|
items,
|
||||||
viewportRef,
|
viewportRef,
|
||||||
revealLoadedMessage,
|
revealLoadedMessage,
|
||||||
@@ -95,8 +96,8 @@ export function ChatFind({
|
|||||||
);
|
);
|
||||||
const state = useSyncExternalStore(model.subscribe, model.getSnapshot, model.getSnapshot);
|
const state = useSyncExternalStore(model.subscribe, model.getSnapshot, model.getSnapshot);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
model.updateHistory(epoch, items);
|
model.updateHistory(epoch, items, rewindSeq);
|
||||||
}, [model, epoch, items]);
|
}, [model, epoch, items, rewindSeq]);
|
||||||
useEffect(() => () => model.close(), [model]);
|
useEffect(() => () => model.close(), [model]);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!active) model.close();
|
if (!active) model.close();
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ function message(seq: number, text = "target"): StreamItem {
|
|||||||
kind: "assistant_message",
|
kind: "assistant_message",
|
||||||
text,
|
text,
|
||||||
timestamp: new Date(0),
|
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) => ({
|
source.map((item, index) => ({
|
||||||
event: { type: "timeline" as const, provider: "claude" as const, item },
|
event: { type: "timeline" as const, provider: "claude" as const, item },
|
||||||
timestamp: new Date(0),
|
timestamp: new Date(0),
|
||||||
timelineCursor: { epoch: "epoch", seq: index + 1 },
|
timelineCursor: { epoch: "epoch", seq: index + 1, anchorSeq: index + 1 },
|
||||||
})),
|
})),
|
||||||
{ source: "canonical" },
|
{ source: "canonical" },
|
||||||
);
|
);
|
||||||
@@ -55,7 +55,7 @@ it("loads an older location and searches a response merged across suppressed tas
|
|||||||
},
|
},
|
||||||
async load(_epoch, seq) {
|
async load(_epoch, seq) {
|
||||||
loaded.push(seq);
|
loaded.push(seq);
|
||||||
model.updateHistory("epoch", history);
|
model.updateHistory("epoch", history, null);
|
||||||
},
|
},
|
||||||
async reveal(_id, _query, occurrence) {
|
async reveal(_id, _query, occurrence) {
|
||||||
revealed.push(occurrence);
|
revealed.push(occurrence);
|
||||||
@@ -64,7 +64,7 @@ it("loads an older location and searches a response merged across suppressed tas
|
|||||||
clear() {},
|
clear() {},
|
||||||
});
|
});
|
||||||
try {
|
try {
|
||||||
model.updateHistory("epoch", []);
|
model.updateHistory("epoch", [], null);
|
||||||
model.open();
|
model.open();
|
||||||
model.setQuery("target");
|
model.setQuery("target");
|
||||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
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() {},
|
clear() {},
|
||||||
});
|
});
|
||||||
try {
|
try {
|
||||||
model.updateHistory("epoch", [message(1), message(2)]);
|
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||||
model.open();
|
model.open();
|
||||||
model.setQuery("target");
|
model.setQuery("target");
|
||||||
await expect.poll(() => model.getSnapshot().selectedItemId).toBe("row-2");
|
await expect.poll(() => model.getSnapshot().selectedItemId).toBe("row-2");
|
||||||
@@ -129,7 +129,7 @@ it("ignores replies after closing and does not navigate", async () => {
|
|||||||
},
|
},
|
||||||
clear() {},
|
clear() {},
|
||||||
});
|
});
|
||||||
model.updateHistory("epoch", [message(1)]);
|
model.updateHistory("epoch", [message(1)], null);
|
||||||
model.open();
|
model.open();
|
||||||
model.setQuery("target");
|
model.setQuery("target");
|
||||||
await expect.poll(() => calls).toEqual(["search"]);
|
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);
|
const model = new ChatFindModel(operations);
|
||||||
try {
|
try {
|
||||||
model.updateHistory("epoch", []);
|
model.updateHistory("epoch", [], null);
|
||||||
model.open();
|
model.open();
|
||||||
model.setQuery("target");
|
model.setQuery("target");
|
||||||
await expect.poll(() => model.getSnapshot().phase).toBe("error");
|
await expect.poll(() => model.getSnapshot().phase).toBe("error");
|
||||||
@@ -185,7 +185,7 @@ it("reports a failed timeline load as a connection failure", async () => {
|
|||||||
clear() {},
|
clear() {},
|
||||||
});
|
});
|
||||||
try {
|
try {
|
||||||
model.updateHistory("epoch", []);
|
model.updateHistory("epoch", [], null);
|
||||||
model.open();
|
model.open();
|
||||||
model.setQuery("target");
|
model.setQuery("target");
|
||||||
await expect.poll(() => model.getSnapshot().phase).toBe("error");
|
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() {},
|
clear() {},
|
||||||
});
|
});
|
||||||
try {
|
try {
|
||||||
model.updateHistory("epoch", [message(1)]);
|
model.updateHistory("epoch", [message(1)], null);
|
||||||
model.open();
|
model.open();
|
||||||
model.setQuery("target");
|
model.setQuery("target");
|
||||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
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" });
|
expect(model.getSnapshot()).toMatchObject({ phase: "error", failure: "historyChanged" });
|
||||||
} finally {
|
} finally {
|
||||||
model.close();
|
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 () => {
|
it("can load a search location before the initial chat history has arrived", async () => {
|
||||||
const model = new ChatFindModel({
|
const model = new ChatFindModel({
|
||||||
async search() {
|
async search() {
|
||||||
return response([{ seq: 1, role: "assistant" }]);
|
return response([{ seq: 1, role: "assistant" }]);
|
||||||
},
|
},
|
||||||
async load() {
|
async load() {
|
||||||
model.updateHistory("epoch", [message(1)]);
|
model.updateHistory("epoch", [message(1)], null);
|
||||||
},
|
},
|
||||||
async reveal() {
|
async reveal() {
|
||||||
return { count: 1, occurrence: 0 };
|
return { count: 1, occurrence: 0 };
|
||||||
@@ -232,7 +368,7 @@ it("can load a search location before the initial chat history has arrived", asy
|
|||||||
clear() {},
|
clear() {},
|
||||||
});
|
});
|
||||||
try {
|
try {
|
||||||
model.updateHistory(null, []);
|
model.updateHistory(null, [], null);
|
||||||
model.open();
|
model.open();
|
||||||
model.setQuery("target");
|
model.setQuery("target");
|
||||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
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() {},
|
clear() {},
|
||||||
});
|
});
|
||||||
try {
|
try {
|
||||||
model.updateHistory("epoch", [message(1), message(2)]);
|
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||||
model.open();
|
model.open();
|
||||||
model.setQuery("target");
|
model.setQuery("target");
|
||||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
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() {},
|
clear() {},
|
||||||
});
|
});
|
||||||
try {
|
try {
|
||||||
model.updateHistory("epoch", [message(1), message(2)]);
|
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||||
model.open();
|
model.open();
|
||||||
model.setQuery("target");
|
model.setQuery("target");
|
||||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||||
|
|||||||
@@ -76,6 +76,10 @@ export class ChatFindModel {
|
|||||||
private items: StreamItem[] = [];
|
private items: StreamItem[] = [];
|
||||||
private epoch: string | null = null;
|
private epoch: string | null = null;
|
||||||
private resultEpoch: 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 locations: Location[] = [];
|
||||||
private resolved = new Map<Location, Target>();
|
private resolved = new Map<Location, Target>();
|
||||||
private current = -1;
|
private current = -1;
|
||||||
@@ -113,6 +117,7 @@ export class ChatFindModel {
|
|||||||
this.cancel();
|
this.cancel();
|
||||||
this.locations = [];
|
this.locations = [];
|
||||||
this.resultEpoch = null;
|
this.resultEpoch = null;
|
||||||
|
this.searchedRewindSeq = undefined;
|
||||||
this.resolved.clear();
|
this.resolved.clear();
|
||||||
this.current = -1;
|
this.current = -1;
|
||||||
this.inMessage = { occurrence: 0, count: 0 };
|
this.inMessage = { occurrence: 0, count: 0 };
|
||||||
@@ -144,6 +149,7 @@ export class ChatFindModel {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
private async search(signal: AbortSignal) {
|
private async search(signal: AbortSignal) {
|
||||||
|
this.searchedRewindSeq = this.rewindSeq;
|
||||||
try {
|
try {
|
||||||
let cursor: number | undefined;
|
let cursor: number | undefined;
|
||||||
do {
|
do {
|
||||||
@@ -168,15 +174,14 @@ export class ChatFindModel {
|
|||||||
this.fail(error, signal);
|
this.fail(error, signal);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
updateHistory(epoch: string | null, items: StreamItem[]) {
|
/** `rewindSeq` is the sequence number of the latest rewind applied to this history. */
|
||||||
if (
|
updateHistory(epoch: string | null, items: StreamItem[], rewindSeq: number | null) {
|
||||||
this.resultEpoch !== null &&
|
const replaced = this.resultEpoch !== null && epoch !== null && epoch !== this.resultEpoch;
|
||||||
epoch !== null &&
|
const rewound = this.searchedRewindSeq !== undefined && rewindSeq !== this.searchedRewindSeq;
|
||||||
epoch !== this.resultEpoch &&
|
if ((replaced || rewound) && this.state.open) {
|
||||||
this.state.open
|
|
||||||
) {
|
|
||||||
this.fail(new ChatFindFailureError("historyChanged"), this.abort.signal);
|
this.fail(new ChatFindFailureError("historyChanged"), this.abort.signal);
|
||||||
}
|
}
|
||||||
|
this.rewindSeq = rewindSeq;
|
||||||
this.epoch = epoch;
|
this.epoch = epoch;
|
||||||
this.items = items;
|
this.items = items;
|
||||||
this.historyListeners.forEach((listener) => listener());
|
this.historyListeners.forEach((listener) => listener());
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ export interface ChatFindProps {
|
|||||||
agentId: string;
|
agentId: string;
|
||||||
serverId: string;
|
serverId: string;
|
||||||
epoch: string | null;
|
epoch: string | null;
|
||||||
|
/** The sequence number of the latest rewind applied to this history, if any. */
|
||||||
|
rewindSeq: number | null;
|
||||||
items: StreamItem[];
|
items: StreamItem[];
|
||||||
viewportRef: RefObject<StreamViewportHandle | null>;
|
viewportRef: RefObject<StreamViewportHandle | null>;
|
||||||
revealLoadedMessage(messageId: string): boolean;
|
revealLoadedMessage(messageId: string): boolean;
|
||||||
|
|||||||
@@ -139,7 +139,7 @@ describe("useChatOutline", () => {
|
|||||||
kind: "user_message",
|
kind: "user_message",
|
||||||
text: "live prompt",
|
text: "live prompt",
|
||||||
timestamp: new Date(seq),
|
timestamp: new Date(seq),
|
||||||
timelineCursor: { epoch: "epoch-1", seq },
|
timelineCursor: { epoch: "epoch-1", seq, anchorSeq: seq },
|
||||||
});
|
});
|
||||||
rerender({ tail: [loadedPrompt(2)] });
|
rerender({ tail: [loadedPrompt(2)] });
|
||||||
await waitFor(() => expect(runtime.listAgentTimelinePrompts).toHaveBeenCalledTimes(2));
|
await waitFor(() => expect(runtime.listAgentTimelinePrompts).toHaveBeenCalledTimes(2));
|
||||||
@@ -198,7 +198,7 @@ describe("useChatOutline", () => {
|
|||||||
kind: "assistant_message",
|
kind: "assistant_message",
|
||||||
text: "chunk",
|
text: "chunk",
|
||||||
timestamp: new Date(),
|
timestamp: new Date(),
|
||||||
timelineCursor: { epoch: "epoch-1", seq: 2 },
|
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
timelineEpoch: "epoch-1",
|
timelineEpoch: "epoch-1",
|
||||||
@@ -219,7 +219,7 @@ describe("useChatOutline", () => {
|
|||||||
kind: "user_message",
|
kind: "user_message",
|
||||||
text: "Replaced conversation",
|
text: "Replaced conversation",
|
||||||
timestamp: new Date(2),
|
timestamp: new Date(2),
|
||||||
timelineCursor: { epoch: "epoch-2", seq: 1 },
|
timelineCursor: { epoch: "epoch-2", seq: 1, anchorSeq: 1 },
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
timelineEpoch: "epoch-2",
|
timelineEpoch: "epoch-2",
|
||||||
@@ -275,7 +275,7 @@ describe("useChatOutline", () => {
|
|||||||
kind: "user_message" as const,
|
kind: "user_message" as const,
|
||||||
text: "prompt",
|
text: "prompt",
|
||||||
timestamp: new Date(1),
|
timestamp: new Date(1),
|
||||||
timelineCursor: { epoch: "epoch-1", seq: 1 },
|
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
const { result, rerender } = renderHook(
|
const { result, rerender } = renderHook(
|
||||||
@@ -326,7 +326,7 @@ describe("useChatOutline", () => {
|
|||||||
kind: "user_message" as const,
|
kind: "user_message" as const,
|
||||||
text: "prompt",
|
text: "prompt",
|
||||||
timestamp: new Date(1),
|
timestamp: new Date(1),
|
||||||
timelineCursor: { epoch: "epoch-1", seq: 1 },
|
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
|
||||||
};
|
};
|
||||||
const { result, rerender } = renderHook(
|
const { result, rerender } = renderHook(
|
||||||
({ tail, mountedHistoryMessageIds }) =>
|
({ tail, mountedHistoryMessageIds }) =>
|
||||||
@@ -381,7 +381,7 @@ describe("useChatOutline", () => {
|
|||||||
kind: "user_message" as const,
|
kind: "user_message" as const,
|
||||||
text: "prompt",
|
text: "prompt",
|
||||||
timestamp: new Date(2),
|
timestamp: new Date(2),
|
||||||
timelineCursor: { epoch: "epoch-1", seq: 2 },
|
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
|
||||||
};
|
};
|
||||||
const revealLoadedMessage = vi.fn();
|
const revealLoadedMessage = vi.fn();
|
||||||
revealLoadedMessage.mockReturnValue(false);
|
revealLoadedMessage.mockReturnValue(false);
|
||||||
|
|||||||
@@ -320,7 +320,7 @@ describe("stream presentation through installed plugins", () => {
|
|||||||
const source = harness.source();
|
const source = harness.source();
|
||||||
const live = source.head[0];
|
const live = source.head[0];
|
||||||
if (live?.kind !== "assistant_message") throw new Error("Expected a live assistant message");
|
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();
|
const present = createStreamPresentation();
|
||||||
present({ ...presentationOptions, tail: [], head: [live], transform: undefined });
|
present({ ...presentationOptions, tail: [], head: [live], transform: undefined });
|
||||||
const repointed = rows(
|
const repointed = rows(
|
||||||
@@ -330,7 +330,7 @@ describe("stream presentation through installed plugins", () => {
|
|||||||
{
|
{
|
||||||
id: streamed[0]!.id,
|
id: streamed[0]!.id,
|
||||||
text: "Streamed answer",
|
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",
|
messageId: "provider-message",
|
||||||
clientMessageId: "client-message",
|
clientMessageId: "client-message",
|
||||||
turnId: "turn-1",
|
turnId: "turn-1",
|
||||||
timelineCursor: { epoch: "epoch", seq: 12 },
|
timelineCursor: { epoch: "epoch", seq: 12, anchorSeq: 12 },
|
||||||
});
|
});
|
||||||
const presentMessage = () =>
|
const presentMessage = () =>
|
||||||
present({
|
present({
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
|
|||||||
it("forks a failed assistant turn from its Paseo timeline cursor without a provider message id", () => {
|
it("forks a failed assistant turn from its Paseo timeline cursor without a provider message id", () => {
|
||||||
const failedTurn = {
|
const failedTurn = {
|
||||||
...assistantMessage("assistant-error", 2),
|
...assistantMessage("assistant-error", 2),
|
||||||
timelineCursor: { epoch: "timeline-1", seq: 42 },
|
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
|
||||||
};
|
};
|
||||||
|
|
||||||
expect(
|
expect(
|
||||||
@@ -50,7 +50,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
|
|||||||
it("includes the provider message id with a supported timeline cursor", () => {
|
it("includes the provider message id with a supported timeline cursor", () => {
|
||||||
const selected = {
|
const selected = {
|
||||||
...assistantMessage("assistant-1", 2, "msg-assistant-1"),
|
...assistantMessage("assistant-1", 2, "msg-assistant-1"),
|
||||||
timelineCursor: { epoch: "timeline-1", seq: 42 },
|
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
|
||||||
};
|
};
|
||||||
|
|
||||||
expect(
|
expect(
|
||||||
@@ -68,7 +68,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
|
|||||||
it("falls back to the provider message id when timeline cursors are unsupported", () => {
|
it("falls back to the provider message id when timeline cursors are unsupported", () => {
|
||||||
const selected = {
|
const selected = {
|
||||||
...assistantMessage("assistant-1", 2, "msg-assistant-1"),
|
...assistantMessage("assistant-1", 2, "msg-assistant-1"),
|
||||||
timelineCursor: { epoch: "timeline-1", seq: 42 },
|
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
|
||||||
};
|
};
|
||||||
|
|
||||||
expect(
|
expect(
|
||||||
@@ -116,7 +116,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
|
|||||||
it("resolves a fork boundary from the reply a plugin card replaced", () => {
|
it("resolves a fork boundary from the reply a plugin card replaced", () => {
|
||||||
const reply = {
|
const reply = {
|
||||||
...assistantMessage("assistant-1", 2, "msg-assistant-1"),
|
...assistantMessage("assistant-1", 2, "msg-assistant-1"),
|
||||||
timelineCursor: { epoch: "timeline-1", seq: 42 },
|
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
|
||||||
};
|
};
|
||||||
const card: StreamItem = {
|
const card: StreamItem = {
|
||||||
kind: "plugin",
|
kind: "plugin",
|
||||||
@@ -154,7 +154,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
|
|||||||
const appended: StreamItem = {
|
const appended: StreamItem = {
|
||||||
kind: "plugin",
|
kind: "plugin",
|
||||||
id: "plugin/card-1",
|
id: "plugin/card-1",
|
||||||
timelineCursor: { epoch: "timeline-1", seq: 42 },
|
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
|
||||||
timestamp: timestamp(2),
|
timestamp: timestamp(2),
|
||||||
pluginId: "plugin",
|
pluginId: "plugin",
|
||||||
pluginItemId: "card-1",
|
pluginItemId: "card-1",
|
||||||
|
|||||||
@@ -1,7 +1,13 @@
|
|||||||
import { getAssistantReply, type StreamItem, type TimelinePosition } from "@/types/stream";
|
import { getAssistantReply, 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 =
|
export type AssistantTurnForkBoundary =
|
||||||
| { boundaryCursor: TimelinePosition; boundaryMessageId?: string }
|
| { boundaryCursor: TimelineBoundaryCursor; boundaryMessageId?: string }
|
||||||
| { boundaryCursor?: undefined; boundaryMessageId: string };
|
| { boundaryCursor?: undefined; boundaryMessageId: string };
|
||||||
|
|
||||||
export function resolveAssistantTurnForkBoundary(input: {
|
export function resolveAssistantTurnForkBoundary(input: {
|
||||||
@@ -15,7 +21,7 @@ export function resolveAssistantTurnForkBoundary(input: {
|
|||||||
}
|
}
|
||||||
if (input.supportsTimelineCursor && reply.timelineCursor) {
|
if (input.supportsTimelineCursor && reply.timelineCursor) {
|
||||||
return {
|
return {
|
||||||
boundaryCursor: reply.timelineCursor,
|
boundaryCursor: { epoch: reply.timelineCursor.epoch, seq: reply.timelineCursor.seq },
|
||||||
...(reply.messageId ? { boundaryMessageId: reply.messageId } : {}),
|
...(reply.messageId ? { boundaryMessageId: reply.messageId } : {}),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -139,7 +139,7 @@ describe("collapseTurns", () => {
|
|||||||
it("stands at its host's timeline position, taking a new row when that position lands", () => {
|
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")]);
|
const live = collapse([user("u1"), shell("c1"), reply("r1")]);
|
||||||
expect(live.summaryRowsByHostId.get("u1")).not.toHaveProperty("timelineCursor");
|
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 placed = [{ ...user("u1"), timelineCursor: cursor }, shell("c1"), reply("r1")];
|
||||||
const canonical = collapse(placed, { previousSummaryRowsByHostId: live.summaryRowsByHostId });
|
const canonical = collapse(placed, { previousSummaryRowsByHostId: live.summaryRowsByHostId });
|
||||||
expect(canonical.summaryRowsByHostId.get("u1")).not.toBe(live.summaryRowsByHostId.get("u1"));
|
expect(canonical.summaryRowsByHostId.get("u1")).not.toBe(live.summaryRowsByHostId.get("u1"));
|
||||||
|
|||||||
@@ -159,10 +159,10 @@ const projectedReply: StreamItem = {
|
|||||||
id: "reply",
|
id: "reply",
|
||||||
messageId: "provider-reply-1",
|
messageId: "provider-reply-1",
|
||||||
text: 'Done.\n\n```ui\nCard("Summary", [])\n```',
|
text: 'Done.\n\n```ui\nCard("Summary", [])\n```',
|
||||||
timelineCursor: { epoch: "e1", seq: 5 },
|
timelineCursor: { epoch: "e1", seq: 5, anchorSeq: 5 },
|
||||||
timestamp: FRIDAY_NIGHT,
|
timestamp: FRIDAY_NIGHT,
|
||||||
},
|
},
|
||||||
timelineCursor: { epoch: "e1", seq: 5 },
|
timelineCursor: { epoch: "e1", seq: 5, anchorSeq: 5 },
|
||||||
timestamp: FRIDAY_NIGHT,
|
timestamp: FRIDAY_NIGHT,
|
||||||
pluginId: "genui",
|
pluginId: "genui",
|
||||||
pluginItemId: "reply/1",
|
pluginItemId: "reply/1",
|
||||||
|
|||||||
@@ -408,6 +408,10 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
|||||||
const timelineEpoch = useSessionStore(
|
const timelineEpoch = useSessionStore(
|
||||||
(state) => state.sessions[resolvedServerId]?.agentTimelineCursor.get(agentId)?.epoch ?? null,
|
(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(
|
const isTimelineDetached = useSessionStore(
|
||||||
(state) => state.sessions[resolvedServerId]?.agentTimelineHasNewer.get(agentId) === true,
|
(state) => state.sessions[resolvedServerId]?.agentTimelineHasNewer.get(agentId) === true,
|
||||||
);
|
);
|
||||||
@@ -1166,6 +1170,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
|||||||
agentId={agentId}
|
agentId={agentId}
|
||||||
serverId={resolvedServerId}
|
serverId={resolvedServerId}
|
||||||
epoch={timelineEpoch}
|
epoch={timelineEpoch}
|
||||||
|
rewindSeq={timelineRewindSeq}
|
||||||
items={findItems}
|
items={findItems}
|
||||||
viewportRef={viewportRef}
|
viewportRef={viewportRef}
|
||||||
revealLoadedMessage={revealLoadedMessage}
|
revealLoadedMessage={revealLoadedMessage}
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import { Redirect, useLocalSearchParams } from "expo-router";
|
import { useLocalSearchParams } from "expo-router";
|
||||||
import { useMemo } from "react";
|
import { useMemo } from "react";
|
||||||
import { HostRouteBootstrapBoundary } from "@/components/host-route-bootstrap-boundary";
|
import { HostRouteBootstrapBoundary } from "@/components/host-route-bootstrap-boundary";
|
||||||
import SettingsScreen from "@/screens/settings-screen";
|
import SettingsScreen from "@/screens/settings-screen";
|
||||||
import { buildSettingsHostSectionRoute, normalizeHostSectionSlug } from "@/utils/host-routes";
|
import { normalizeHostSectionSlug } from "@/utils/host-routes";
|
||||||
|
|
||||||
export default function SettingsHostSectionRoute() {
|
export default function SettingsHostSectionRoute() {
|
||||||
const params = useLocalSearchParams<{ serverId?: string; hostSection?: string }>();
|
const params = useLocalSearchParams<{ serverId?: string; hostSection?: string }>();
|
||||||
@@ -11,10 +11,6 @@ export default function SettingsHostSectionRoute() {
|
|||||||
const section = normalizeHostSectionSlug(rawSection) ?? "connections";
|
const section = normalizeHostSectionSlug(rawSection) ?? "connections";
|
||||||
const view = useMemo(() => ({ kind: "host" as const, serverId, section }), [serverId, section]);
|
const view = useMemo(() => ({ kind: "host" as const, serverId, section }), [serverId, section]);
|
||||||
|
|
||||||
if (rawSection === "pair-device" && serverId) {
|
|
||||||
return <Redirect href={buildSettingsHostSectionRoute(serverId, "devices")} />;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<HostRouteBootstrapBoundary>
|
<HostRouteBootstrapBoundary>
|
||||||
<SettingsScreen view={view} />
|
<SettingsScreen view={view} />
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { FOOTER_HEIGHT } from "@/constants/layout";
|
|||||||
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
|
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
|
||||||
import { KeyboardTranslateView } from "@/keyboard/shift";
|
import { KeyboardTranslateView } from "@/keyboard/shift";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { useToast } from "@/contexts/toast-context";
|
||||||
import type { Theme } from "@/styles/theme";
|
import type { Theme } from "@/styles/theme";
|
||||||
import { toErrorMessage } from "@/utils/error-messages";
|
import { toErrorMessage } from "@/utils/error-messages";
|
||||||
|
|
||||||
@@ -19,6 +20,7 @@ export function ArchivedAgentCallout({ serverId, agentId }: ArchivedAgentCallout
|
|||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const client = useHostRuntimeClient(serverId);
|
const client = useHostRuntimeClient(serverId);
|
||||||
const isConnected = useHostRuntimeIsConnected(serverId);
|
const isConnected = useHostRuntimeIsConnected(serverId);
|
||||||
|
const toast = useToast();
|
||||||
const [isUnarchiving, setIsUnarchiving] = useState(false);
|
const [isUnarchiving, setIsUnarchiving] = useState(false);
|
||||||
const [unarchiveError, setUnarchiveError] = useState<string | null>(null);
|
const [unarchiveError, setUnarchiveError] = useState<string | null>(null);
|
||||||
|
|
||||||
@@ -27,12 +29,15 @@ export function ArchivedAgentCallout({ serverId, agentId }: ArchivedAgentCallout
|
|||||||
setIsUnarchiving(true);
|
setIsUnarchiving(true);
|
||||||
setUnarchiveError(null);
|
setUnarchiveError(null);
|
||||||
try {
|
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) {
|
} catch (error) {
|
||||||
setUnarchiveError(toErrorMessage(error));
|
setUnarchiveError(toErrorMessage(error));
|
||||||
setIsUnarchiving(false);
|
setIsUnarchiving(false);
|
||||||
}
|
}
|
||||||
}, [client, isConnected, isUnarchiving, agentId]);
|
}, [client, isConnected, isUnarchiving, agentId, toast, t]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<KeyboardTranslateView style={styles.container}>
|
<KeyboardTranslateView style={styles.container}>
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import { useRewindComposerRestore } from "./composer-restore";
|
|||||||
import { useSessionStore } from "@/stores/session-store";
|
import { useSessionStore } from "@/stores/session-store";
|
||||||
import { shouldRestoreComposerForRewindMode } from "./rewind-mode";
|
import { shouldRestoreComposerForRewindMode } from "./rewind-mode";
|
||||||
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
||||||
|
import { hostSupportsFeature } from "@/runtime/host-features";
|
||||||
|
|
||||||
interface UseRewindAgentMutationInput {
|
interface UseRewindAgentMutationInput {
|
||||||
serverId?: string;
|
serverId?: string;
|
||||||
@@ -42,7 +43,16 @@ export function useRewindAgentMutation(input: UseRewindAgentMutationInput): {
|
|||||||
throw new Error(t("common.errors.daemonClientUnavailable"));
|
throw new Error(t("common.errors.daemonClientUnavailable"));
|
||||||
}
|
}
|
||||||
await input.client.rewindAgent(input.agentId, input.messageId, mode);
|
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
|
const cursor = input.serverId
|
||||||
? useSessionStore
|
? useSessionStore
|
||||||
.getState()
|
.getState()
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
import { useCallback, useMemo, useState, type ReactNode } from "react";
|
import { Children, isValidElement, useCallback, useMemo, useState, type ReactNode } from "react";
|
||||||
import { View } from "react-native";
|
import { View } from "react-native";
|
||||||
|
import { StyleSheet } from "react-native-unistyles";
|
||||||
import { isWeb } from "@/constants/platform";
|
import { isWeb } from "@/constants/platform";
|
||||||
import { SettingsRowChildren } from "./row-children";
|
import { settingsStyles } from "@/styles/settings";
|
||||||
|
import { NestedSettingsRows } from "./row-density";
|
||||||
import { SettingsRowHeader } from "./row-header";
|
import { SettingsRowHeader } from "./row-header";
|
||||||
|
|
||||||
interface SettingsCollapsibleRowProps {
|
interface SettingsCollapsibleRowProps {
|
||||||
@@ -46,7 +48,27 @@ export function SettingsCollapsibleRow({
|
|||||||
webAccessibilityProps={webExpandedProps}
|
webAccessibilityProps={webExpandedProps}
|
||||||
testID={testID ? `${testID}-toggle` : undefined}
|
testID={testID ? `${testID}-toggle` : undefined}
|
||||||
/>
|
/>
|
||||||
{expanded ? <SettingsRowChildren>{children}</SettingsRowChildren> : null}
|
{expanded ? (
|
||||||
|
<View style={styles.children}>
|
||||||
|
<NestedSettingsRows>
|
||||||
|
{Children.toArray(children).map((child, index) => (
|
||||||
|
<View
|
||||||
|
key={isValidElement(child) ? child.key : index}
|
||||||
|
style={settingsStyles.rowBorder}
|
||||||
|
>
|
||||||
|
{child}
|
||||||
|
</View>
|
||||||
|
))}
|
||||||
|
</NestedSettingsRows>
|
||||||
|
</View>
|
||||||
|
) : null}
|
||||||
</View>
|
</View>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const styles = StyleSheet.create((theme) => ({
|
||||||
|
// The revealed rows keep the card's rails; the tint is what groups them under their header.
|
||||||
|
children: {
|
||||||
|
backgroundColor: theme.colors.surface0,
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|||||||
@@ -25,10 +25,7 @@ import { DropdownTrigger } from "@/components/ui/dropdown-trigger";
|
|||||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||||
import { settingsStyles } from "@/styles/settings";
|
import { settingsStyles } from "@/styles/settings";
|
||||||
import { ControlSizeProvider } from "@/components/ui/control-size";
|
import { ControlSizeProvider } from "@/components/ui/control-size";
|
||||||
import { ExternalLink, type ExternalLinkProps } from "@/components/ui/external-link";
|
|
||||||
import { useSettingsRowLayout } from "./row-density";
|
import { useSettingsRowLayout } from "./row-density";
|
||||||
import { SettingsRowTitle } from "./row-label";
|
|
||||||
export { SettingsRowChildren } from "./row-children";
|
|
||||||
export { SettingsGroup } from "./headings/settings-group";
|
export { SettingsGroup } from "./headings/settings-group";
|
||||||
export { SettingsSection } from "./headings/settings-section";
|
export { SettingsSection } from "./headings/settings-section";
|
||||||
export { SettingsCollapsibleRow } from "./collapsible-row";
|
export { SettingsCollapsibleRow } from "./collapsible-row";
|
||||||
@@ -39,16 +36,11 @@ export { SettingsBackLink, SettingsDetailHeader } from "./detail-header";
|
|||||||
export { SettingsInfoTip } from "./headings/settings-info-tip";
|
export { SettingsInfoTip } from "./headings/settings-info-tip";
|
||||||
export { MenuSettingsRows } from "./row-density";
|
export { MenuSettingsRows } from "./row-density";
|
||||||
|
|
||||||
/**
|
/** What app screens can add to a plugin-facing row: an accessory beside the label, such as an info tip. */
|
||||||
* What app screens can add to a plugin-facing row: an accessory beside the label, such as an info
|
|
||||||
* tip, an icon before the label, and a link to a page outside the app under the hint.
|
|
||||||
*/
|
|
||||||
interface AppRowExtras {
|
interface AppRowExtras {
|
||||||
labelAccessory?: ReactNode;
|
labelAccessory?: ReactNode;
|
||||||
/** An icon before the label, such as the thing the row is about. */
|
/** An icon before the label, such as the thing the row is about. */
|
||||||
leading?: ReactNode;
|
leading?: ReactNode;
|
||||||
/** A page outside the app that helps with this row, drawn under the hint as "Label ↗". */
|
|
||||||
link?: Pick<ExternalLinkProps, "href" | "label" | "accessibilityLabel">;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
interface AppSettingsRowProps extends Omit<SettingsRowProps, "hint">, AppRowExtras {
|
interface AppSettingsRowProps extends Omit<SettingsRowProps, "hint">, AppRowExtras {
|
||||||
@@ -75,7 +67,6 @@ export function SettingsRow({
|
|||||||
leading,
|
leading,
|
||||||
labelAccessory,
|
labelAccessory,
|
||||||
hint,
|
hint,
|
||||||
link,
|
|
||||||
error,
|
error,
|
||||||
children,
|
children,
|
||||||
testID,
|
testID,
|
||||||
@@ -83,17 +74,20 @@ export function SettingsRow({
|
|||||||
const compact = useIsCompactFormFactor();
|
const compact = useIsCompactFormFactor();
|
||||||
const layout = useSettingsRowLayout();
|
const layout = useSettingsRowLayout();
|
||||||
const rowStyle = useMemo(() => [layout.row, compact && styles.compactRow], [compact, layout]);
|
const rowStyle = useMemo(() => [layout.row, compact && styles.compactRow], [compact, layout]);
|
||||||
|
const accessoryTitleStyle = useMemo(() => [layout.title, styles.accessoryLabel], [layout]);
|
||||||
return (
|
return (
|
||||||
<View style={rowStyle} testID={testID}>
|
<View style={rowStyle} testID={testID}>
|
||||||
{leading ? <View style={styles.leading}>{leading}</View> : null}
|
{leading ? <View style={styles.leading}>{leading}</View> : null}
|
||||||
<View style={styles.label}>
|
<View style={styles.label}>
|
||||||
<SettingsRowTitle label={label} accessory={labelAccessory} />
|
{labelAccessory ? (
|
||||||
{typeof hint === "string" ? <Text style={layout.hint}>{hint}</Text> : hint}
|
<View style={styles.labelRow}>
|
||||||
{link ? (
|
<Text style={accessoryTitleStyle}>{label}</Text>
|
||||||
<View style={styles.link}>
|
{labelAccessory}
|
||||||
<ExternalLink {...link} />
|
|
||||||
</View>
|
</View>
|
||||||
) : null}
|
) : (
|
||||||
|
<Text style={layout.title}>{label}</Text>
|
||||||
|
)}
|
||||||
|
{typeof hint === "string" ? <Text style={layout.hint}>{hint}</Text> : hint}
|
||||||
{error ? (
|
{error ? (
|
||||||
<Text accessibilityRole="alert" style={settingsStyles.rowError}>
|
<Text accessibilityRole="alert" style={settingsStyles.rowError}>
|
||||||
{error}
|
{error}
|
||||||
@@ -109,15 +103,7 @@ export function SettingsRow({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A switch row. App screens may pass `null` while the value is not known yet; see `Switch`. */
|
export function SettingsSwitch({ value, onValueChange, disabled, ...row }: SettingsSwitchProps) {
|
||||||
export function SettingsSwitch({
|
|
||||||
value,
|
|
||||||
onValueChange,
|
|
||||||
disabled,
|
|
||||||
...row
|
|
||||||
}: Omit<SettingsSwitchProps, "onValueChange" | "value"> &
|
|
||||||
Partial<Pick<SettingsSwitchProps, "onValueChange">> &
|
|
||||||
AppRowExtras & { value: boolean | null }) {
|
|
||||||
return (
|
return (
|
||||||
<SettingsRow {...row}>
|
<SettingsRow {...row}>
|
||||||
<Switch
|
<Switch
|
||||||
@@ -218,12 +204,7 @@ export function SettingsInput({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function SettingsAction({
|
export function SettingsAction({ actionLabel, onPress, disabled, ...row }: SettingsActionProps) {
|
||||||
actionLabel,
|
|
||||||
onPress,
|
|
||||||
disabled,
|
|
||||||
...row
|
|
||||||
}: SettingsActionProps & AppRowExtras) {
|
|
||||||
return (
|
return (
|
||||||
<SettingsRow {...row}>
|
<SettingsRow {...row}>
|
||||||
<Button variant="outline" onPress={onPress} disabled={disabled}>
|
<Button variant="outline" onPress={onPress} disabled={disabled}>
|
||||||
@@ -240,7 +221,13 @@ const styles = StyleSheet.create((theme) => ({
|
|||||||
// The same leading slot as `SettingsRowHeader`, so icons and labels share rails across row kinds.
|
// The same leading slot as `SettingsRowHeader`, so icons and labels share rails across row kinds.
|
||||||
leading: { marginRight: theme.spacing[3], alignItems: "center", justifyContent: "center" },
|
leading: { marginRight: theme.spacing[3], alignItems: "center", justifyContent: "center" },
|
||||||
label: { flexGrow: 1, flexShrink: 1, flexBasis: 160, marginRight: theme.spacing[3] },
|
label: { flexGrow: 1, flexShrink: 1, flexBasis: 160, marginRight: theme.spacing[3] },
|
||||||
link: { alignItems: "flex-start", marginTop: theme.spacing[1] },
|
labelRow: {
|
||||||
|
flexDirection: "row",
|
||||||
|
flexWrap: "wrap",
|
||||||
|
alignItems: "center",
|
||||||
|
gap: theme.spacing[2],
|
||||||
|
},
|
||||||
|
accessoryLabel: { flexShrink: 1, minWidth: 0 },
|
||||||
control: { flexShrink: 1, maxWidth: "100%" },
|
control: { flexShrink: 1, maxWidth: "100%" },
|
||||||
input: { minWidth: 180 },
|
input: { minWidth: 180 },
|
||||||
}));
|
}));
|
||||||
|
|||||||
@@ -1,30 +0,0 @@
|
|||||||
import { Children, isValidElement, type ReactNode } from "react";
|
|
||||||
import { View } from "react-native";
|
|
||||||
import { StyleSheet } from "react-native-unistyles";
|
|
||||||
import { settingsStyles } from "@/styles/settings";
|
|
||||||
import { NestedSettingsRows } from "./row-density";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Rows that belong to the row above them, such as the rows an expanded row reveals or the details
|
|
||||||
* a switch turns on. They sit in the same card on a tinted band, laid out as nested rows.
|
|
||||||
*/
|
|
||||||
export function SettingsRowChildren({ children }: { children: ReactNode }) {
|
|
||||||
return (
|
|
||||||
<View style={styles.band}>
|
|
||||||
<NestedSettingsRows>
|
|
||||||
{Children.toArray(children).map((child, index) => (
|
|
||||||
<View key={isValidElement(child) ? child.key : index} style={settingsStyles.rowBorder}>
|
|
||||||
{child}
|
|
||||||
</View>
|
|
||||||
))}
|
|
||||||
</NestedSettingsRows>
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const styles = StyleSheet.create((theme) => ({
|
|
||||||
// The rows keep the card's rails; the tint is what groups them under the row above.
|
|
||||||
band: {
|
|
||||||
backgroundColor: theme.colors.surface0,
|
|
||||||
},
|
|
||||||
}));
|
|
||||||
@@ -11,7 +11,6 @@ import { SkeletonPulse, useSkeletonPulse } from "@/components/ui/skeleton";
|
|||||||
import { settingsStyles } from "@/styles/settings";
|
import { settingsStyles } from "@/styles/settings";
|
||||||
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||||
import { useSettingsRowLayout, type SettingsRowLayout } from "./row-density";
|
import { useSettingsRowLayout, type SettingsRowLayout } from "./row-density";
|
||||||
import { SettingsRowTitle } from "./row-label";
|
|
||||||
|
|
||||||
const ThemedChevron = withUnistyles(ChevronRight);
|
const ThemedChevron = withUnistyles(ChevronRight);
|
||||||
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
|
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
|
||||||
@@ -119,8 +118,9 @@ export function SettingsRowHeader({
|
|||||||
</View>
|
</View>
|
||||||
) : null}
|
) : null}
|
||||||
<View style={[contentStyle, styles.passThrough]}>
|
<View style={[contentStyle, styles.passThrough]}>
|
||||||
<View {...HIDDEN_FROM_ASSISTIVE_TECH}>
|
<View style={labelAccessory ? styles.labelRow : undefined} {...HIDDEN_FROM_ASSISTIVE_TECH}>
|
||||||
<SettingsRowTitle label={label} accessory={labelAccessory} />
|
<Text style={layout.title}>{label}</Text>
|
||||||
|
{labelAccessory}
|
||||||
</View>
|
</View>
|
||||||
{hintStatus ? (
|
{hintStatus ? (
|
||||||
<RowHintLine hint={hint} status={hintStatus} hintStyle={layout.hint} />
|
<RowHintLine hint={hint} status={hintStatus} hintStyle={layout.hint} />
|
||||||
@@ -293,6 +293,7 @@ const styles = StyleSheet.create((theme) => ({
|
|||||||
borderRadius: theme.borderRadius.sm,
|
borderRadius: theme.borderRadius.sm,
|
||||||
backgroundColor: theme.colors.surface2,
|
backgroundColor: theme.colors.surface2,
|
||||||
},
|
},
|
||||||
|
labelRow: { flexDirection: "row", alignItems: "center", gap: theme.spacing[2] },
|
||||||
summary: {
|
summary: {
|
||||||
flexShrink: 1,
|
flexShrink: 1,
|
||||||
color: theme.colors.foregroundMuted,
|
color: theme.colors.foregroundMuted,
|
||||||
|
|||||||
@@ -1,34 +0,0 @@
|
|||||||
import { useMemo, type ReactNode } from "react";
|
|
||||||
import { Text, View } from "react-native";
|
|
||||||
import { StyleSheet } from "react-native-unistyles";
|
|
||||||
import { useSettingsRowLayout } from "./row-density";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A row's label line: the label, and beside it an accessory such as a badge or an info tip. Rows
|
|
||||||
* with inline controls and rows that lead somewhere both draw it, so their labels and hints keep
|
|
||||||
* the same distances whether or not a row carries an accessory.
|
|
||||||
*/
|
|
||||||
export function SettingsRowTitle({ label, accessory }: { label: string; accessory?: ReactNode }) {
|
|
||||||
const layout = useSettingsRowLayout();
|
|
||||||
const titleStyle = useMemo(() => [layout.title, styles.title], [layout]);
|
|
||||||
if (!accessory) return <Text style={layout.title}>{label}</Text>;
|
|
||||||
return (
|
|
||||||
<View style={styles.line}>
|
|
||||||
<Text style={titleStyle}>{label}</Text>
|
|
||||||
<View style={styles.accessory}>{accessory}</View>
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const styles = StyleSheet.create((theme) => ({
|
|
||||||
line: {
|
|
||||||
flexDirection: "row",
|
|
||||||
flexWrap: "wrap",
|
|
||||||
alignItems: "center",
|
|
||||||
gap: theme.spacing[2],
|
|
||||||
},
|
|
||||||
title: { flexShrink: 1, minWidth: 0 },
|
|
||||||
// An accessory is taller than the label's line. It hangs into the row's padding instead, so the
|
|
||||||
// label and hint keep the distances of a row without one.
|
|
||||||
accessory: { marginVertical: -theme.spacing[1] },
|
|
||||||
}));
|
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
import { useCallback, useMemo } from "react";
|
import { useCallback, useMemo } from "react";
|
||||||
import {
|
import {
|
||||||
Pressable,
|
Pressable,
|
||||||
View,
|
|
||||||
type GestureResponderEvent,
|
type GestureResponderEvent,
|
||||||
type StyleProp,
|
type StyleProp,
|
||||||
type ViewStyle,
|
type ViewStyle,
|
||||||
@@ -20,11 +19,7 @@ import { useIsCompactFormFactor } from "@/constants/layout";
|
|||||||
import type { Theme } from "@/styles/theme";
|
import type { Theme } from "@/styles/theme";
|
||||||
|
|
||||||
interface SwitchProps {
|
interface SwitchProps {
|
||||||
/**
|
value: boolean;
|
||||||
* `null` while the value is not known yet, such as while it loads from a host. The switch's space
|
|
||||||
* stays reserved and empty, so the switch takes it when the value arrives and nothing moves.
|
|
||||||
*/
|
|
||||||
value: boolean | null;
|
|
||||||
onValueChange?: (value: boolean) => void;
|
onValueChange?: (value: boolean) => void;
|
||||||
disabled?: boolean;
|
disabled?: boolean;
|
||||||
accessibilityLabel?: string;
|
accessibilityLabel?: string;
|
||||||
@@ -114,7 +109,7 @@ export function Switch({
|
|||||||
const handlePress = useCallback(
|
const handlePress = useCallback(
|
||||||
(event: GestureResponderEvent) => {
|
(event: GestureResponderEvent) => {
|
||||||
event.stopPropagation();
|
event.stopPropagation();
|
||||||
if (disabled || value === null) return;
|
if (disabled) return;
|
||||||
onValueChange?.(!value);
|
onValueChange?.(!value);
|
||||||
},
|
},
|
||||||
[disabled, onValueChange, value],
|
[disabled, onValueChange, value],
|
||||||
@@ -124,10 +119,7 @@ export function Switch({
|
|||||||
const isCompact = useIsCompactFormFactor();
|
const isCompact = useIsCompactFormFactor();
|
||||||
const geometry = useMemo(() => switchGeometryForLayout(size, isCompact), [size, isCompact]);
|
const geometry = useMemo(() => switchGeometryForLayout(size, isCompact), [size, isCompact]);
|
||||||
|
|
||||||
const accessibilityState = useMemo(
|
const accessibilityState = useMemo(() => ({ checked: value, disabled }), [value, disabled]);
|
||||||
() => ({ checked: value === true, disabled }),
|
|
||||||
[value, disabled],
|
|
||||||
);
|
|
||||||
const pressableStyle = useMemo(
|
const pressableStyle = useMemo(
|
||||||
() => [
|
() => [
|
||||||
styles.switchControl,
|
styles.switchControl,
|
||||||
@@ -142,12 +134,6 @@ export function Switch({
|
|||||||
],
|
],
|
||||||
[disabled, geometry.hitHeight, geometry.trackHeight, style],
|
[disabled, geometry.hitHeight, geometry.trackHeight, style],
|
||||||
);
|
);
|
||||||
const unknownStyle = useMemo(
|
|
||||||
() => [{ width: geometry.trackWidth, minHeight: geometry.trackHeight }, style],
|
|
||||||
[geometry.trackWidth, geometry.trackHeight, style],
|
|
||||||
);
|
|
||||||
|
|
||||||
if (value === null) return <View style={unknownStyle} testID={testID} />;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Pressable
|
<Pressable
|
||||||
|
|||||||
@@ -385,6 +385,16 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
|
|||||||
console.warn("[Session] timeline replacement refresh failed", { serverId, error });
|
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, {
|
const sync = getHostRuntimeStore().createViewedTimelineOwner(serverId, {
|
||||||
canCheckFreshness: () =>
|
canCheckFreshness: () =>
|
||||||
client.getLastServerInfoMessage()?.features?.timelineFreshnessCheck === true,
|
client.getLastServerInfoMessage()?.features?.timelineFreshnessCheck === true,
|
||||||
@@ -395,6 +405,7 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
|
|||||||
update: (message) => {
|
update: (message) => {
|
||||||
if (message.type === "agent_stream") onStream(message);
|
if (message.type === "agent_stream") onStream(message);
|
||||||
else if (message.type === "agent.timeline.replacement") onReplacement(message);
|
else if (message.type === "agent.timeline.replacement") onReplacement(message);
|
||||||
|
else if (message.type === "agent.timeline.rewind") onRewind(message);
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
return observation;
|
return observation;
|
||||||
|
|||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
import { useMemo } from "react";
|
import { useMemo } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
|
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
|
||||||
import { PairDeviceSection } from "@/devices/pair-device-section";
|
import { PairDeviceSection } from "@/desktop/components/pair-device-section";
|
||||||
|
|
||||||
export interface PairDeviceModalProps {
|
export interface PairDeviceModalProps {
|
||||||
serverId: string;
|
serverId: string;
|
||||||
+1
-1
@@ -23,7 +23,7 @@ import {
|
|||||||
|
|
||||||
const RELAY_DOCS_URL = "https://paseo.sh/docs/security";
|
const RELAY_DOCS_URL = "https://paseo.sh/docs/security";
|
||||||
export const CONNECTIVITY_DOCS_URL = "https://paseo.sh/docs/connectivity";
|
export const CONNECTIVITY_DOCS_URL = "https://paseo.sh/docs/connectivity";
|
||||||
const TAILSCALE_DOCS_URL = `${CONNECTIVITY_DOCS_URL}#tailscale`;
|
export const TAILSCALE_DOCS_URL = `${CONNECTIVITY_DOCS_URL}#tailscale`;
|
||||||
const FLEX_ONE_STYLE = { flex: 1 } as const;
|
const FLEX_ONE_STYLE = { flex: 1 } as const;
|
||||||
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
|
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
|
||||||
const ThemedShieldCheck = withUnistyles(ShieldCheck);
|
const ThemedShieldCheck = withUnistyles(ShieldCheck);
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
export { PairDeviceModal } from "./pair-device-modal";
|
|
||||||
export { WaysToConnect } from "./ways-to-connect";
|
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
|
||||||
import type { TailscaleStatus } from "@getpaseo/protocol/messages";
|
|
||||||
import { i18n } from "@/i18n/i18next";
|
|
||||||
import { describeTailscale } from "./tailscale-hint";
|
|
||||||
|
|
||||||
// Statuses as the host reports them; see `createDaemonListeners` in the server's listeners.ts.
|
|
||||||
const off: TailscaleStatus = { ip: "100.101.102.103", address: null, state: "off" };
|
|
||||||
|
|
||||||
describe("the Tailscale row's hint", () => {
|
|
||||||
it("says why Tailscale stays off when the host listens on a socket", () => {
|
|
||||||
const socketHint = "Off, because this host listens on a local socket";
|
|
||||||
expect(describeTailscale({ ...off, lockedBy: "main", mainIsSocket: true }, i18n.t)).toBe(
|
|
||||||
socketHint,
|
|
||||||
);
|
|
||||||
expect(describeTailscale({ ...off, lockedBy: "launch", mainIsSocket: true }, i18n.t)).toBe(
|
|
||||||
socketHint,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("keeps the hint of every other state", () => {
|
|
||||||
const hint = (status: TailscaleStatus) => describeTailscale(status, i18n.t);
|
|
||||||
expect(hint(off)).toBe("Direct over your tailnet, enter an address");
|
|
||||||
expect(hint({ ip: null, address: null, state: "unavailable", lockedBy: "launch" })).toBe(
|
|
||||||
"Tailscale is not running on this host",
|
|
||||||
);
|
|
||||||
expect(hint({ ...off, state: "waiting", address: "100.101.102.103:6767" })).toBe(
|
|
||||||
"Waiting for Tailscale to start on this host",
|
|
||||||
);
|
|
||||||
expect(hint({ ...off, state: "on", address: "100.101.102.103:6767", lockedBy: "main" })).toBe(
|
|
||||||
"Always on, because this host already accepts Tailscale connections",
|
|
||||||
);
|
|
||||||
expect(hint({ ...off, lockedBy: "launch" })).toBe(
|
|
||||||
"Controlled by the command that starts this host",
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
import type { TailscaleStatus } from "@getpaseo/protocol/messages";
|
|
||||||
import type { TFunction } from "i18next";
|
|
||||||
|
|
||||||
/** The line under the Tailscale label for each state the host reports, most specific first. */
|
|
||||||
export function describeTailscale(status: TailscaleStatus, t: TFunction): string {
|
|
||||||
if (status.state === "unavailable") return t("devices.tailscale.unavailable");
|
|
||||||
if (status.state === "waiting") return t("devices.tailscale.waiting");
|
|
||||||
// A socket is why Tailscale cannot be on, even when the launch command also fixes the address.
|
|
||||||
if (status.mainIsSocket) return t("devices.tailscale.socket");
|
|
||||||
if (status.lockedBy === "launch") return t("devices.tailscale.launch");
|
|
||||||
if (status.lockedBy === "main") return t("devices.tailscale.alwaysOn");
|
|
||||||
return t("devices.tailscale.hint");
|
|
||||||
}
|
|
||||||
@@ -1,202 +0,0 @@
|
|||||||
import { useCallback, useMemo } from "react";
|
|
||||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
|
||||||
import { useTranslation } from "react-i18next";
|
|
||||||
import { SettingsAction, SettingsRowChildren, SettingsSwitch } from "@/components/settings";
|
|
||||||
import { useToast } from "@/contexts/toast-context";
|
|
||||||
import { useFetchQuery } from "@/data/query";
|
|
||||||
import { useHostRuntimeClient, useHostRuntimeSnapshot } from "@/runtime/host-runtime";
|
|
||||||
import { useSessionStore } from "@/stores/session-store";
|
|
||||||
import { confirmDialog } from "@/utils/confirm-dialog";
|
|
||||||
import { copyToClipboard } from "@/utils/copy-to-clipboard";
|
|
||||||
import { describeTailscale } from "./tailscale-hint";
|
|
||||||
|
|
||||||
const UPDATES_DOCS_URL = "https://paseo.sh/docs/updates";
|
|
||||||
const TAILSCALE_DOWNLOAD_URL = "https://tailscale.com/download";
|
|
||||||
// A product name, the same in every language.
|
|
||||||
const LABEL = "Tailscale";
|
|
||||||
|
|
||||||
type HostClient = NonNullable<ReturnType<typeof useHostRuntimeClient>>;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Turns Tailscale on or off for a host and shows the address a phone on the tailnet adds. Renders
|
|
||||||
* as a row inside a `SettingsCard`; when Tailscale is on, the address is a nested row under it.
|
|
||||||
*/
|
|
||||||
export function TailscaleRow({ serverId }: { serverId: string }) {
|
|
||||||
const { t } = useTranslation();
|
|
||||||
const client = useHostRuntimeClient(serverId);
|
|
||||||
const connection = useHostRuntimeSnapshot(serverId)?.connectionStatus;
|
|
||||||
const serverInfo = useSessionStore((state) => state.sessions[serverId]?.serverInfo);
|
|
||||||
const updateLink = useMemo(
|
|
||||||
() => ({ href: UPDATES_DOCS_URL, label: t("devices.tailscale.updateDocs") }),
|
|
||||||
[t],
|
|
||||||
);
|
|
||||||
// COMPAT(tailscale): added in v0.16.0, remove after 2027-05-25 once daemon floor >= v0.16.0.
|
|
||||||
if (serverInfo && serverInfo.features?.tailscale !== true) {
|
|
||||||
return (
|
|
||||||
<SettingsSwitch
|
|
||||||
label={LABEL}
|
|
||||||
hint={t("devices.tailscale.update")}
|
|
||||||
link={updateLink}
|
|
||||||
value={false}
|
|
||||||
disabled
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (client && connection === "online" && serverInfo) {
|
|
||||||
return <TailscaleControl serverId={serverId} client={client} />;
|
|
||||||
}
|
|
||||||
// Without the host the row shows no value: the switch's space stays empty. A host the app has
|
|
||||||
// reached before keeps its server info, so while the app retries it still reads as disconnected.
|
|
||||||
const lost = connection === "offline" || connection === "error" || Boolean(serverInfo);
|
|
||||||
return (
|
|
||||||
<SettingsSwitch
|
|
||||||
label={LABEL}
|
|
||||||
hint={t(lost ? "workspace.terminal.hostDisconnected" : "devices.tailscale.hint")}
|
|
||||||
value={null}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function TailscaleControl({ serverId, client }: { serverId: string; client: HostClient }) {
|
|
||||||
const { t } = useTranslation();
|
|
||||||
const tailscale = useTailscale(serverId, client);
|
|
||||||
const { status } = tailscale;
|
|
||||||
const installLink = useMemo(
|
|
||||||
() => ({ href: TAILSCALE_DOWNLOAD_URL, label: t("devices.tailscale.install") }),
|
|
||||||
[t],
|
|
||||||
);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
<SettingsSwitch
|
|
||||||
label={LABEL}
|
|
||||||
hint={status ? describeTailscale(status, t) : t("devices.tailscale.hint")}
|
|
||||||
link={status?.state === "unavailable" ? installLink : undefined}
|
|
||||||
error={tailscale.error}
|
|
||||||
value={tailscale.value}
|
|
||||||
disabled={!status || status.state === "unavailable" || Boolean(status.lockedBy)}
|
|
||||||
onValueChange={tailscale.setEnabled}
|
|
||||||
/>
|
|
||||||
{tailscale.address ? <TailscaleAddress address={tailscale.address} /> : null}
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function TailscaleAddress({ address }: { address: string }) {
|
|
||||||
const { t } = useTranslation();
|
|
||||||
const toast = useToast();
|
|
||||||
const copy = useCallback(() => {
|
|
||||||
void copyToClipboard(address)
|
|
||||||
.then(() => toast.copied())
|
|
||||||
.catch(() => toast.error(t("common.errors.error")));
|
|
||||||
}, [address, t, toast]);
|
|
||||||
return (
|
|
||||||
<SettingsRowChildren>
|
|
||||||
<SettingsAction
|
|
||||||
label={address}
|
|
||||||
hint={t("devices.tailscale.address")}
|
|
||||||
actionLabel={t("common.actions.copy")}
|
|
||||||
onPress={copy}
|
|
||||||
testID="devices-tailscale-address"
|
|
||||||
/>
|
|
||||||
</SettingsRowChildren>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
interface TailscaleChange {
|
|
||||||
enabled: boolean;
|
|
||||||
confirmed: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The host's Tailscale state and the one way to change it. While a change is in flight the switch
|
|
||||||
* already shows where it is going, so a tap answers at once; the host's answer then settles it.
|
|
||||||
* Turning Tailscale off over the connection it would cut asks first, and nothing changes on screen
|
|
||||||
* until the user confirms.
|
|
||||||
*/
|
|
||||||
function useTailscale(serverId: string, client: HostClient) {
|
|
||||||
const { t } = useTranslation();
|
|
||||||
const queryClient = useQueryClient();
|
|
||||||
const queryKey = useMemo(() => ["tailscale-status", serverId], [serverId]);
|
|
||||||
|
|
||||||
const query = useFetchQuery({
|
|
||||||
queryKey,
|
|
||||||
queryFn: async () => {
|
|
||||||
const { tailscale } = await client.getDaemonStatus({ includeProviders: false });
|
|
||||||
if (!tailscale) throw new Error("Host did not report Tailscale status");
|
|
||||||
return tailscale;
|
|
||||||
},
|
|
||||||
// Tailscale can come up after the host does; polling moves "waiting" to "on" on its own.
|
|
||||||
refetchInterval: 2_000,
|
|
||||||
staleTimeMs: 0,
|
|
||||||
dataShape: "value",
|
|
||||||
});
|
|
||||||
|
|
||||||
const change = useMutation({
|
|
||||||
mutationFn: async ({ enabled, confirmed }: TailscaleChange) => {
|
|
||||||
await queryClient.cancelQueries({ queryKey });
|
|
||||||
return client.setTailscaleEnabled(enabled, confirmed);
|
|
||||||
},
|
|
||||||
onSuccess: (result) => queryClient.setQueryData(queryKey, result.tailscale),
|
|
||||||
});
|
|
||||||
|
|
||||||
const status = query.data;
|
|
||||||
const pending = change.isPending ? change.variables.enabled : undefined;
|
|
||||||
const on = status?.state === "on" || status?.state === "waiting";
|
|
||||||
// Not known until the host first answers.
|
|
||||||
const value = pending ?? (status ? on : null);
|
|
||||||
|
|
||||||
const { mutate } = change;
|
|
||||||
const confirmTurnOff = useCallback(
|
|
||||||
() =>
|
|
||||||
confirmDialog({
|
|
||||||
title: t("devices.tailscale.confirmTitle"),
|
|
||||||
message: t("devices.tailscale.confirmMessage"),
|
|
||||||
confirmLabel: t("devices.tailscale.confirmAction"),
|
|
||||||
cancelLabel: t("common.actions.cancel"),
|
|
||||||
destructive: true,
|
|
||||||
}),
|
|
||||||
[t],
|
|
||||||
);
|
|
||||||
const turnOffConfirmed = useCallback(async () => {
|
|
||||||
if (await confirmTurnOff()) mutate({ enabled: false, confirmed: true });
|
|
||||||
}, [confirmTurnOff, mutate]);
|
|
||||||
const disconnects = status?.disconnectsCurrentConnection === true;
|
|
||||||
const setEnabled = useCallback(
|
|
||||||
(enabled: boolean) => {
|
|
||||||
if (!enabled && disconnects) {
|
|
||||||
void turnOffConfirmed();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
mutate(
|
|
||||||
{ enabled, confirmed: false },
|
|
||||||
{
|
|
||||||
// The status was stale: the host would cut this connection after all. Its answer has
|
|
||||||
// already put the row back to on, so the question is asked over what is true.
|
|
||||||
onSuccess: (result) => {
|
|
||||||
if (result.confirmationRequired) void turnOffConfirmed();
|
|
||||||
},
|
|
||||||
},
|
|
||||||
);
|
|
||||||
},
|
|
||||||
[disconnects, mutate, turnOffConfirmed],
|
|
||||||
);
|
|
||||||
|
|
||||||
let error: string | undefined;
|
|
||||||
if (change.isError) {
|
|
||||||
error = t(
|
|
||||||
change.variables.enabled ? "devices.tailscale.turnOnError" : "devices.tailscale.turnOffError",
|
|
||||||
);
|
|
||||||
} else if (query.isError && !status) {
|
|
||||||
error = t("devices.tailscale.statusError");
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
status,
|
|
||||||
value,
|
|
||||||
error,
|
|
||||||
// A tap is ignored until the host answers the one before it.
|
|
||||||
setEnabled: change.isPending ? undefined : setEnabled,
|
|
||||||
address: status?.state === "on" && value ? status.address : null,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,51 +0,0 @@
|
|||||||
import { useCallback, useMemo, useState } from "react";
|
|
||||||
import { useTranslation } from "react-i18next";
|
|
||||||
import { SettingsCard, SettingsDetailRow, SettingsSection } from "@/components/settings";
|
|
||||||
import { StatusBadge } from "@/components/ui/status-badge";
|
|
||||||
import { PairDeviceModal } from "./pair-device-modal";
|
|
||||||
import { CONNECTIVITY_DOCS_URL } from "./pair-device-section";
|
|
||||||
import { TailscaleRow } from "./tailscale-row";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The ways another device can connect to a host: Relay, which pairs through a QR code in a sheet,
|
|
||||||
* and Tailscale, a switch and an address. Settings and the setup's phone step show this same block.
|
|
||||||
*/
|
|
||||||
export function WaysToConnect({ serverId }: { serverId: string }) {
|
|
||||||
const { t } = useTranslation();
|
|
||||||
const [pairing, setPairing] = useState(false);
|
|
||||||
const openPairing = useCallback(() => setPairing(true), []);
|
|
||||||
const closePairing = useCallback(() => setPairing(false), []);
|
|
||||||
const recommended = useMemo(
|
|
||||||
() => <StatusBadge size="xs" variant="success" label={t("devices.recommended")} />,
|
|
||||||
[t],
|
|
||||||
);
|
|
||||||
const docsLink = useMemo(
|
|
||||||
() => ({
|
|
||||||
href: CONNECTIVITY_DOCS_URL,
|
|
||||||
label: t("devices.docs"),
|
|
||||||
accessibilityLabel: t("devices.docsAccessibility"),
|
|
||||||
}),
|
|
||||||
[t],
|
|
||||||
);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<SettingsSection title={t("devices.waysToConnect")} link={docsLink}>
|
|
||||||
<SettingsCard>
|
|
||||||
<SettingsDetailRow
|
|
||||||
label={t("devices.relay.title")}
|
|
||||||
labelAccessory={recommended}
|
|
||||||
hint={t("devices.relay.hint")}
|
|
||||||
onPress={openPairing}
|
|
||||||
testID="devices-relay"
|
|
||||||
/>
|
|
||||||
<TailscaleRow serverId={serverId} />
|
|
||||||
</SettingsCard>
|
|
||||||
<PairDeviceModal
|
|
||||||
serverId={serverId}
|
|
||||||
visible={pairing}
|
|
||||||
onClose={closePairing}
|
|
||||||
testID="devices-relay-pairing"
|
|
||||||
/>
|
|
||||||
</SettingsSection>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -166,7 +166,7 @@ describe("ensureAgentIsInitialized", () => {
|
|||||||
kind: "assistant_message",
|
kind: "assistant_message",
|
||||||
id: "canonical-item",
|
id: "canonical-item",
|
||||||
text: "Canonical before restart",
|
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"),
|
timestamp: new Date("2026-07-27T10:00:00.000Z"),
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -741,6 +741,8 @@ export const ar: TranslationResources = {
|
|||||||
resumeCommandUnavailable: "أمر الاستئناف غير متوفر",
|
resumeCommandUnavailable: "أمر الاستئناف غير متوفر",
|
||||||
reloadingAgent: "وكيل إعادة التحميل...",
|
reloadingAgent: "وكيل إعادة التحميل...",
|
||||||
reloadedAgent: "وكيل إعادة تحميل",
|
reloadedAgent: "وكيل إعادة تحميل",
|
||||||
|
reloadedAgentHistoryDiverged:
|
||||||
|
"تمت إعادة تحميل الوكيل، لكن سجل المزوّد لا يطابق هذه المحادثة، لذا لم تتم مزامنته",
|
||||||
failedToReloadAgent: "فشل في إعادة تحميل الوكيل",
|
failedToReloadAgent: "فشل في إعادة تحميل الوكيل",
|
||||||
failedToCloseAgent: "فشل في إغلاق الوكيل",
|
failedToCloseAgent: "فشل في إغلاق الوكيل",
|
||||||
},
|
},
|
||||||
@@ -1791,6 +1793,12 @@ export const ar: TranslationResources = {
|
|||||||
"يتيح لك تطبيق الجوال الأصلي كامل الميزات التحكم في أي كمبيوتر يعمل عليه Paseo من هاتفك",
|
"يتيح لك تطبيق الجوال الأصلي كامل الميزات التحكم في أي كمبيوتر يعمل عليه Paseo من هاتفك",
|
||||||
appStore: "App Store",
|
appStore: "App Store",
|
||||||
googlePlay: "Google Play",
|
googlePlay: "Google Play",
|
||||||
|
connectTitle: "اختر طريقة الاتصال",
|
||||||
|
connectDocs: "الوثائق",
|
||||||
|
openConnectDocs: "افتح وثائق الاتصال",
|
||||||
|
recommended: "موصى به",
|
||||||
|
relay: { title: "التتابع", hint: "مشفّر من طرف إلى طرف، امسح رمز QR" },
|
||||||
|
tailscale: { title: "Tailscale", hint: "يتطلب بعض الإعداد" },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -1869,32 +1877,6 @@ export const ar: TranslationResources = {
|
|||||||
hostDisconnected: "Host غير متصل",
|
hostDisconnected: "Host غير متصل",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
devices: {
|
|
||||||
title: "الأجهزة",
|
|
||||||
waysToConnect: "طرق الاتصال",
|
|
||||||
docs: "الوثائق",
|
|
||||||
docsAccessibility: "افتح وثائق الاتصال",
|
|
||||||
recommended: "موصى به",
|
|
||||||
relay: { title: "التتابع", hint: "مشفّر من طرف إلى طرف، امسح رمز QR" },
|
|
||||||
tailscale: {
|
|
||||||
hint: "اتصال مباشر عبر شبكة tailnet الخاصة بك، أدخل عنوانًا",
|
|
||||||
unavailable: "Tailscale لا يعمل على هذا المضيف",
|
|
||||||
install: "احصل على Tailscale",
|
|
||||||
waiting: "في انتظار بدء Tailscale على هذا المضيف",
|
|
||||||
alwaysOn: "مفعّل دائمًا، لأن هذا المضيف يقبل اتصالات Tailscale بالفعل",
|
|
||||||
socket: "متوقف، لأن هذا المضيف يستمع على مقبس محلي",
|
|
||||||
launch: "يتحكم فيه الأمر الذي يشغّل هذا المضيف",
|
|
||||||
update: "حدّث هذا المضيف لاستخدام Tailscale",
|
|
||||||
updateDocs: "طريقة التحديث",
|
|
||||||
address: "على هاتف متصل بـ Tailscale، أضف مضيفًا بهذا العنوان",
|
|
||||||
statusError: "تعذّر التحقق من Tailscale",
|
|
||||||
turnOnError: "تعذّر تشغيل Tailscale",
|
|
||||||
turnOffError: "تعذّر إيقاف Tailscale",
|
|
||||||
confirmTitle: "إيقاف Tailscale؟",
|
|
||||||
confirmMessage: "هذا الجهاز متصل عبر Tailscale وسيفقد اتصاله بالمضيف.",
|
|
||||||
confirmAction: "إيقاف",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
pairing: {
|
pairing: {
|
||||||
hostPassword: {
|
hostPassword: {
|
||||||
title: "كلمة المرور لـ {{host}}",
|
title: "كلمة المرور لـ {{host}}",
|
||||||
@@ -2949,7 +2931,9 @@ export const ar: TranslationResources = {
|
|||||||
timeout: "نفذ الوقت",
|
timeout: "نفذ الوقت",
|
||||||
},
|
},
|
||||||
pairDevices: {
|
pairDevices: {
|
||||||
|
title: "إقران الأجهزة",
|
||||||
rowTitle: "إقران جهاز",
|
rowTitle: "إقران جهاز",
|
||||||
|
rowHint: "امسح رمز QR ضوئيًا أو انسخ رابطًا لتوصيل هاتفك بهذا المضيف",
|
||||||
},
|
},
|
||||||
skills: {
|
skills: {
|
||||||
...en.settings.host.skills,
|
...en.settings.host.skills,
|
||||||
|
|||||||
@@ -740,6 +740,8 @@ export const en = {
|
|||||||
resumeCommandUnavailable: "Resume command not available",
|
resumeCommandUnavailable: "Resume command not available",
|
||||||
reloadingAgent: "Reloading agent...",
|
reloadingAgent: "Reloading agent...",
|
||||||
reloadedAgent: "Reloaded 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",
|
failedToReloadAgent: "Failed to reload agent",
|
||||||
failedToCloseAgent: "Failed to close agent",
|
failedToCloseAgent: "Failed to close agent",
|
||||||
},
|
},
|
||||||
@@ -1820,6 +1822,12 @@ export const en = {
|
|||||||
"The fully featured native mobile app allows you to control any Paseo computer from your phone",
|
"The fully featured native mobile app allows you to control any Paseo computer from your phone",
|
||||||
appStore: "App Store",
|
appStore: "App Store",
|
||||||
googlePlay: "Google Play",
|
googlePlay: "Google Play",
|
||||||
|
connectTitle: "Choose how to connect",
|
||||||
|
connectDocs: "Docs",
|
||||||
|
openConnectDocs: "Open connectivity documentation",
|
||||||
|
recommended: "Recommended",
|
||||||
|
relay: { title: "Relay", hint: "End-to-end encrypted, scan a QR code" },
|
||||||
|
tailscale: { title: "Tailscale", hint: "Requires some setup" },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -1898,33 +1906,6 @@ export const en = {
|
|||||||
hostDisconnected: "Host is not connected",
|
hostDisconnected: "Host is not connected",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
devices: {
|
|
||||||
title: "Devices",
|
|
||||||
waysToConnect: "Ways to connect",
|
|
||||||
docs: "Docs",
|
|
||||||
docsAccessibility: "Open connectivity documentation",
|
|
||||||
recommended: "Recommended",
|
|
||||||
relay: { title: "Relay", hint: "End-to-end encrypted, scan a QR code" },
|
|
||||||
tailscale: {
|
|
||||||
hint: "Direct over your tailnet, enter an address",
|
|
||||||
unavailable: "Tailscale is not running on this host",
|
|
||||||
install: "Get Tailscale",
|
|
||||||
waiting: "Waiting for Tailscale to start on this host",
|
|
||||||
alwaysOn: "Always on, because this host already accepts Tailscale connections",
|
|
||||||
socket: "Off, because this host listens on a local socket",
|
|
||||||
launch: "Controlled by the command that starts this host",
|
|
||||||
update: "Update this host to use Tailscale",
|
|
||||||
updateDocs: "How to update",
|
|
||||||
address: "On a phone with Tailscale, add a host at this address",
|
|
||||||
statusError: "Could not check Tailscale",
|
|
||||||
turnOnError: "Could not turn on Tailscale",
|
|
||||||
turnOffError: "Could not turn off Tailscale",
|
|
||||||
confirmTitle: "Turn off Tailscale?",
|
|
||||||
confirmMessage:
|
|
||||||
"This device is connected through Tailscale and will lose its connection to the host.",
|
|
||||||
confirmAction: "Turn off",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
pairing: {
|
pairing: {
|
||||||
hostPassword: {
|
hostPassword: {
|
||||||
title: "Password for {{host}}",
|
title: "Password for {{host}}",
|
||||||
@@ -3045,7 +3026,9 @@ export const en = {
|
|||||||
timeout: "Timeout",
|
timeout: "Timeout",
|
||||||
},
|
},
|
||||||
pairDevices: {
|
pairDevices: {
|
||||||
|
title: "Pair devices",
|
||||||
rowTitle: "Pair a device",
|
rowTitle: "Pair a device",
|
||||||
|
rowHint: "Scan a QR code or copy a link to connect your phone to this host",
|
||||||
},
|
},
|
||||||
skills: {
|
skills: {
|
||||||
sectionTitle: "Orchestration skills",
|
sectionTitle: "Orchestration skills",
|
||||||
|
|||||||
@@ -748,6 +748,8 @@ export const es: TranslationResources = {
|
|||||||
resumeCommandUnavailable: "Comando de reanudación no disponible",
|
resumeCommandUnavailable: "Comando de reanudación no disponible",
|
||||||
reloadingAgent: "Agente de recarga...",
|
reloadingAgent: "Agente de recarga...",
|
||||||
reloadedAgent: "Agente recargado",
|
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",
|
failedToReloadAgent: "No se pudo recargar el agente",
|
||||||
failedToCloseAgent: "No se pudo cerrar el agente",
|
failedToCloseAgent: "No se pudo cerrar el agente",
|
||||||
},
|
},
|
||||||
@@ -1839,6 +1841,12 @@ export const es: TranslationResources = {
|
|||||||
"La app móvil nativa completa te permite controlar cualquier ordenador con Paseo desde tu teléfono",
|
"La app móvil nativa completa te permite controlar cualquier ordenador con Paseo desde tu teléfono",
|
||||||
appStore: "App Store",
|
appStore: "App Store",
|
||||||
googlePlay: "Google Play",
|
googlePlay: "Google Play",
|
||||||
|
connectTitle: "Elige cómo conectarte",
|
||||||
|
connectDocs: "Docs",
|
||||||
|
openConnectDocs: "Abrir la documentación de conectividad",
|
||||||
|
recommended: "Recomendado",
|
||||||
|
relay: { title: "Relé", hint: "Cifrado de extremo a extremo, escanea un código QR" },
|
||||||
|
tailscale: { title: "Tailscale", hint: "Requiere algo de configuración" },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -1917,33 +1925,6 @@ export const es: TranslationResources = {
|
|||||||
hostDisconnected: "Hostno está conectado",
|
hostDisconnected: "Hostno está conectado",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
devices: {
|
|
||||||
title: "Dispositivos",
|
|
||||||
waysToConnect: "Formas de conectarse",
|
|
||||||
docs: "Docs",
|
|
||||||
docsAccessibility: "Abrir la documentación de conectividad",
|
|
||||||
recommended: "Recomendado",
|
|
||||||
relay: { title: "Relé", hint: "Cifrado de extremo a extremo, escanea un código QR" },
|
|
||||||
tailscale: {
|
|
||||||
hint: "Conexión directa por tu tailnet, introduce una dirección",
|
|
||||||
unavailable: "Tailscale no se está ejecutando en este host",
|
|
||||||
install: "Obtener Tailscale",
|
|
||||||
waiting: "Esperando a que Tailscale se inicie en este host",
|
|
||||||
alwaysOn: "Siempre activado, porque este host ya acepta conexiones de Tailscale",
|
|
||||||
socket: "Desactivado, porque este host escucha en un socket local",
|
|
||||||
launch: "Lo controla el comando que inicia este host",
|
|
||||||
update: "Actualiza este host para usar Tailscale",
|
|
||||||
updateDocs: "Cómo actualizar",
|
|
||||||
address: "En un teléfono con Tailscale, añade un host con esta dirección",
|
|
||||||
statusError: "No se pudo comprobar Tailscale",
|
|
||||||
turnOnError: "No se pudo activar Tailscale",
|
|
||||||
turnOffError: "No se pudo desactivar Tailscale",
|
|
||||||
confirmTitle: "¿Desactivar Tailscale?",
|
|
||||||
confirmMessage:
|
|
||||||
"Este dispositivo está conectado mediante Tailscale y perderá la conexión con el host.",
|
|
||||||
confirmAction: "Desactivar",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
pairing: {
|
pairing: {
|
||||||
hostPassword: {
|
hostPassword: {
|
||||||
title: "Contraseña de {{host}}",
|
title: "Contraseña de {{host}}",
|
||||||
@@ -2974,7 +2955,9 @@ export const es: TranslationResources = {
|
|||||||
timeout: "Se acabó el tiempo",
|
timeout: "Se acabó el tiempo",
|
||||||
},
|
},
|
||||||
pairDevices: {
|
pairDevices: {
|
||||||
|
title: "Emparejar dispositivos",
|
||||||
rowTitle: "Emparejar un dispositivo",
|
rowTitle: "Emparejar un dispositivo",
|
||||||
|
rowHint: "Escanee un códigoQRo copie un enlace para conectar su teléfono a este host",
|
||||||
},
|
},
|
||||||
skills: {
|
skills: {
|
||||||
...en.settings.host.skills,
|
...en.settings.host.skills,
|
||||||
|
|||||||
@@ -748,6 +748,8 @@ export const fr: TranslationResources = {
|
|||||||
resumeCommandUnavailable: "Commande de reprise indisponible",
|
resumeCommandUnavailable: "Commande de reprise indisponible",
|
||||||
reloadingAgent: "Rechargement de l’agent…",
|
reloadingAgent: "Rechargement de l’agent…",
|
||||||
reloadedAgent: "Agent rechargé",
|
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",
|
failedToReloadAgent: "Impossible de recharger l’agent",
|
||||||
failedToCloseAgent: "Impossible de fermer l’agent",
|
failedToCloseAgent: "Impossible de fermer l’agent",
|
||||||
},
|
},
|
||||||
@@ -1837,6 +1839,12 @@ export const fr: TranslationResources = {
|
|||||||
"L'application mobile native complète vous permet de contrôler n'importe quel ordinateur Paseo depuis votre téléphone",
|
"L'application mobile native complète vous permet de contrôler n'importe quel ordinateur Paseo depuis votre téléphone",
|
||||||
appStore: "App Store",
|
appStore: "App Store",
|
||||||
googlePlay: "Google Play",
|
googlePlay: "Google Play",
|
||||||
|
connectTitle: "Choisissez comment vous connecter",
|
||||||
|
connectDocs: "Docs",
|
||||||
|
openConnectDocs: "Ouvrir la documentation sur la connectivité",
|
||||||
|
recommended: "Recommandé",
|
||||||
|
relay: { title: "Relais", hint: "Chiffré de bout en bout, scannez un QR code" },
|
||||||
|
tailscale: { title: "Tailscale", hint: "Demande un peu de configuration" },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -1915,32 +1923,6 @@ export const fr: TranslationResources = {
|
|||||||
hostDisconnected: "L’hôte n’est pas connecté",
|
hostDisconnected: "L’hôte n’est pas connecté",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
devices: {
|
|
||||||
title: "Appareils",
|
|
||||||
waysToConnect: "Moyens de connexion",
|
|
||||||
docs: "Docs",
|
|
||||||
docsAccessibility: "Ouvrir la documentation sur la connectivité",
|
|
||||||
recommended: "Recommandé",
|
|
||||||
relay: { title: "Relais", hint: "Chiffré de bout en bout, scannez un QR code" },
|
|
||||||
tailscale: {
|
|
||||||
hint: "Connexion directe via votre tailnet, saisissez une adresse",
|
|
||||||
unavailable: "Tailscale ne fonctionne pas sur cet hôte",
|
|
||||||
install: "Obtenir Tailscale",
|
|
||||||
waiting: "En attente du démarrage de Tailscale sur cet hôte",
|
|
||||||
alwaysOn: "Toujours activé, car cet hôte accepte déjà les connexions Tailscale",
|
|
||||||
socket: "Désactivé, car cet hôte écoute sur un socket local",
|
|
||||||
launch: "Contrôlé par la commande qui démarre cet hôte",
|
|
||||||
update: "Mettez cet hôte à jour pour utiliser Tailscale",
|
|
||||||
updateDocs: "Comment mettre à jour",
|
|
||||||
address: "Sur un téléphone avec Tailscale, ajoutez un hôte à cette adresse",
|
|
||||||
statusError: "Impossible de vérifier Tailscale",
|
|
||||||
turnOnError: "Impossible d’activer Tailscale",
|
|
||||||
turnOffError: "Impossible de désactiver Tailscale",
|
|
||||||
confirmTitle: "Désactiver Tailscale ?",
|
|
||||||
confirmMessage: "Cet appareil est connecté via Tailscale et perdra sa connexion à l’hôte.",
|
|
||||||
confirmAction: "Désactiver",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
pairing: {
|
pairing: {
|
||||||
hostPassword: {
|
hostPassword: {
|
||||||
title: "Mot de passe pour {{host}}",
|
title: "Mot de passe pour {{host}}",
|
||||||
@@ -2975,7 +2957,9 @@ export const fr: TranslationResources = {
|
|||||||
timeout: "Délai dépassé",
|
timeout: "Délai dépassé",
|
||||||
},
|
},
|
||||||
pairDevices: {
|
pairDevices: {
|
||||||
|
title: "Associer des appareils",
|
||||||
rowTitle: "Associer un appareil",
|
rowTitle: "Associer un appareil",
|
||||||
|
rowHint: "Scannez un QR code ou copiez un lien pour connecter votre téléphone à cet hôte",
|
||||||
},
|
},
|
||||||
skills: {
|
skills: {
|
||||||
...en.settings.host.skills,
|
...en.settings.host.skills,
|
||||||
|
|||||||
@@ -748,6 +748,8 @@ export const ja: TranslationResources = {
|
|||||||
resumeCommandUnavailable: "再開コマンドが利用できません",
|
resumeCommandUnavailable: "再開コマンドが利用できません",
|
||||||
reloadingAgent: "エージェントを再読み込み中...",
|
reloadingAgent: "エージェントを再読み込み中...",
|
||||||
reloadedAgent: "エージェントを再読み込みしました",
|
reloadedAgent: "エージェントを再読み込みしました",
|
||||||
|
reloadedAgentHistoryDiverged:
|
||||||
|
"エージェントを再読み込みしましたが、プロバイダーの履歴がこのチャットと一致しないため同期しませんでした",
|
||||||
failedToReloadAgent: "エージェントの再読み込みに失敗しました",
|
failedToReloadAgent: "エージェントの再読み込みに失敗しました",
|
||||||
failedToCloseAgent: "エージェントを閉じられませんでした",
|
failedToCloseAgent: "エージェントを閉じられませんでした",
|
||||||
},
|
},
|
||||||
@@ -1811,6 +1813,12 @@ export const ja: TranslationResources = {
|
|||||||
"フル機能のネイティブモバイルアプリで、スマートフォンからどの Paseo コンピューターでも操作できます",
|
"フル機能のネイティブモバイルアプリで、スマートフォンからどの Paseo コンピューターでも操作できます",
|
||||||
appStore: "App Store",
|
appStore: "App Store",
|
||||||
googlePlay: "Google Play",
|
googlePlay: "Google Play",
|
||||||
|
connectTitle: "接続方法を選択",
|
||||||
|
connectDocs: "ドキュメント",
|
||||||
|
openConnectDocs: "接続のドキュメントを開く",
|
||||||
|
recommended: "おすすめ",
|
||||||
|
relay: { title: "リレー", hint: "エンドツーエンド暗号化、QR コードをスキャン" },
|
||||||
|
tailscale: { title: "Tailscale", hint: "少し設定が必要です" },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -1889,32 +1897,6 @@ export const ja: TranslationResources = {
|
|||||||
hostDisconnected: "ホストが接続されていません",
|
hostDisconnected: "ホストが接続されていません",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
devices: {
|
|
||||||
title: "デバイス",
|
|
||||||
waysToConnect: "接続方法",
|
|
||||||
docs: "ドキュメント",
|
|
||||||
docsAccessibility: "接続のドキュメントを開く",
|
|
||||||
recommended: "おすすめ",
|
|
||||||
relay: { title: "リレー", hint: "エンドツーエンド暗号化、QR コードをスキャン" },
|
|
||||||
tailscale: {
|
|
||||||
hint: "tailnet 経由で直接接続、アドレスを入力",
|
|
||||||
unavailable: "このホストで Tailscale が動作していません",
|
|
||||||
install: "Tailscale を入手",
|
|
||||||
waiting: "このホストで Tailscale が起動するのを待っています",
|
|
||||||
alwaysOn: "常にオン。このホストはすでに Tailscale からの接続を受け付けています",
|
|
||||||
socket: "オフ。このホストはローカルソケットで待ち受けています",
|
|
||||||
launch: "このホストを起動するコマンドで制御されています",
|
|
||||||
update: "Tailscale を使うにはこのホストを更新してください",
|
|
||||||
updateDocs: "更新方法",
|
|
||||||
address: "Tailscale を使うスマートフォンで、このアドレスのホストを追加してください",
|
|
||||||
statusError: "Tailscale を確認できませんでした",
|
|
||||||
turnOnError: "Tailscale をオンにできませんでした",
|
|
||||||
turnOffError: "Tailscale をオフにできませんでした",
|
|
||||||
confirmTitle: "Tailscale をオフにしますか?",
|
|
||||||
confirmMessage: "このデバイスは Tailscale 経由で接続しているため、ホストとの接続が切れます。",
|
|
||||||
confirmAction: "オフにする",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
pairing: {
|
pairing: {
|
||||||
hostPassword: {
|
hostPassword: {
|
||||||
title: "{{host}} のパスワード",
|
title: "{{host}} のパスワード",
|
||||||
@@ -2941,7 +2923,9 @@ export const ja: TranslationResources = {
|
|||||||
timeout: "タイムアウト",
|
timeout: "タイムアウト",
|
||||||
},
|
},
|
||||||
pairDevices: {
|
pairDevices: {
|
||||||
|
title: "デバイスをペアリング",
|
||||||
rowTitle: "デバイスをペアリング",
|
rowTitle: "デバイスをペアリング",
|
||||||
|
rowHint: "QRコードをスキャンするかリンクをコピーしてスマートフォンをこのホストに接続",
|
||||||
},
|
},
|
||||||
skills: {
|
skills: {
|
||||||
...en.settings.host.skills,
|
...en.settings.host.skills,
|
||||||
|
|||||||
@@ -743,6 +743,8 @@ export const ko: TranslationResources = {
|
|||||||
resumeCommandUnavailable: "재개 명령을 사용할 수 없습니다",
|
resumeCommandUnavailable: "재개 명령을 사용할 수 없습니다",
|
||||||
reloadingAgent: "에이전트 다시 로드 중...",
|
reloadingAgent: "에이전트 다시 로드 중...",
|
||||||
reloadedAgent: "에이전트를 다시 로드했습니다",
|
reloadedAgent: "에이전트를 다시 로드했습니다",
|
||||||
|
reloadedAgentHistoryDiverged:
|
||||||
|
"에이전트를 다시 로드했지만 제공자 기록이 이 채팅과 일치하지 않아 동기화하지 않았습니다",
|
||||||
failedToReloadAgent: "에이전트를 다시 로드하지 못했습니다",
|
failedToReloadAgent: "에이전트를 다시 로드하지 못했습니다",
|
||||||
failedToCloseAgent: "에이전트를 닫지 못했습니다",
|
failedToCloseAgent: "에이전트를 닫지 못했습니다",
|
||||||
},
|
},
|
||||||
@@ -1802,6 +1804,12 @@ export const ko: TranslationResources = {
|
|||||||
"모든 기능을 갖춘 네이티브 모바일 앱으로 휴대폰에서 어떤 Paseo 컴퓨터든 제어할 수 있습니다",
|
"모든 기능을 갖춘 네이티브 모바일 앱으로 휴대폰에서 어떤 Paseo 컴퓨터든 제어할 수 있습니다",
|
||||||
appStore: "App Store",
|
appStore: "App Store",
|
||||||
googlePlay: "Google Play",
|
googlePlay: "Google Play",
|
||||||
|
connectTitle: "연결 방법 선택",
|
||||||
|
connectDocs: "문서",
|
||||||
|
openConnectDocs: "연결 문서 열기",
|
||||||
|
recommended: "권장",
|
||||||
|
relay: { title: "릴레이", hint: "엔드투엔드 암호화, QR 코드를 스캔하세요" },
|
||||||
|
tailscale: { title: "Tailscale", hint: "약간의 설정이 필요합니다" },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -1880,32 +1888,6 @@ export const ko: TranslationResources = {
|
|||||||
hostDisconnected: "호스트가 연결되어 있지 않습니다",
|
hostDisconnected: "호스트가 연결되어 있지 않습니다",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
devices: {
|
|
||||||
title: "기기",
|
|
||||||
waysToConnect: "연결 방법",
|
|
||||||
docs: "문서",
|
|
||||||
docsAccessibility: "연결 문서 열기",
|
|
||||||
recommended: "권장",
|
|
||||||
relay: { title: "릴레이", hint: "엔드투엔드 암호화, QR 코드를 스캔하세요" },
|
|
||||||
tailscale: {
|
|
||||||
hint: "tailnet으로 직접 연결, 주소 입력",
|
|
||||||
unavailable: "이 호스트에서 Tailscale이 실행 중이 아닙니다",
|
|
||||||
install: "Tailscale 받기",
|
|
||||||
waiting: "이 호스트에서 Tailscale이 시작되기를 기다리는 중",
|
|
||||||
alwaysOn: "항상 켜짐. 이 호스트가 이미 Tailscale 연결을 받고 있습니다",
|
|
||||||
socket: "꺼짐. 이 호스트가 로컬 소켓에서 수신 대기 중입니다",
|
|
||||||
launch: "이 호스트를 시작하는 명령이 제어합니다",
|
|
||||||
update: "Tailscale을 사용하려면 이 호스트를 업데이트하세요",
|
|
||||||
updateDocs: "업데이트 방법",
|
|
||||||
address: "Tailscale을 사용하는 휴대전화에서 이 주소로 호스트를 추가하세요",
|
|
||||||
statusError: "Tailscale을 확인하지 못했습니다",
|
|
||||||
turnOnError: "Tailscale을 켜지 못했습니다",
|
|
||||||
turnOffError: "Tailscale을 끄지 못했습니다",
|
|
||||||
confirmTitle: "Tailscale을 끌까요?",
|
|
||||||
confirmMessage: "이 기기는 Tailscale로 연결되어 있어 호스트와의 연결이 끊깁니다.",
|
|
||||||
confirmAction: "끄기",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
pairing: {
|
pairing: {
|
||||||
hostPassword: {
|
hostPassword: {
|
||||||
title: "{{host}}의 비밀번호",
|
title: "{{host}}의 비밀번호",
|
||||||
@@ -2927,7 +2909,9 @@ export const ko: TranslationResources = {
|
|||||||
timeout: "시간 초과",
|
timeout: "시간 초과",
|
||||||
},
|
},
|
||||||
pairDevices: {
|
pairDevices: {
|
||||||
|
title: "기기 페어링",
|
||||||
rowTitle: "기기 페어링",
|
rowTitle: "기기 페어링",
|
||||||
|
rowHint: "QR 코드를 스캔하거나 링크를 복사하여 휴대폰을 이 호스트에 연결하세요",
|
||||||
},
|
},
|
||||||
skills: {
|
skills: {
|
||||||
...en.settings.host.skills,
|
...en.settings.host.skills,
|
||||||
|
|||||||
@@ -746,6 +746,8 @@ export const ptBR: TranslationResources = {
|
|||||||
resumeCommandUnavailable: "Comando de retomada indisponível",
|
resumeCommandUnavailable: "Comando de retomada indisponível",
|
||||||
reloadingAgent: "Recarregando agente...",
|
reloadingAgent: "Recarregando agente...",
|
||||||
reloadedAgent: "Agente recarregado",
|
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",
|
failedToReloadAgent: "Falha ao recarregar agente",
|
||||||
failedToCloseAgent: "Falha ao fechar agente",
|
failedToCloseAgent: "Falha ao fechar agente",
|
||||||
},
|
},
|
||||||
@@ -1824,6 +1826,12 @@ export const ptBR: TranslationResources = {
|
|||||||
"O app móvel nativo completo permite controlar qualquer computador com Paseo pelo seu celular",
|
"O app móvel nativo completo permite controlar qualquer computador com Paseo pelo seu celular",
|
||||||
appStore: "App Store",
|
appStore: "App Store",
|
||||||
googlePlay: "Google Play",
|
googlePlay: "Google Play",
|
||||||
|
connectTitle: "Escolha como se conectar",
|
||||||
|
connectDocs: "Docs",
|
||||||
|
openConnectDocs: "Abrir documentação de conectividade",
|
||||||
|
recommended: "Recomendado",
|
||||||
|
relay: { title: "Relay", hint: "Criptografia de ponta a ponta, escaneie um código QR" },
|
||||||
|
tailscale: { title: "Tailscale", hint: "Requer alguma configuração" },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -1902,33 +1910,6 @@ export const ptBR: TranslationResources = {
|
|||||||
hostDisconnected: "Host não está conectado",
|
hostDisconnected: "Host não está conectado",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
devices: {
|
|
||||||
title: "Dispositivos",
|
|
||||||
waysToConnect: "Formas de conexão",
|
|
||||||
docs: "Docs",
|
|
||||||
docsAccessibility: "Abrir documentação de conectividade",
|
|
||||||
recommended: "Recomendado",
|
|
||||||
relay: { title: "Relay", hint: "Criptografia de ponta a ponta, escaneie um código QR" },
|
|
||||||
tailscale: {
|
|
||||||
hint: "Conexão direta pela sua tailnet, digite um endereço",
|
|
||||||
unavailable: "O Tailscale não está em execução neste host",
|
|
||||||
install: "Baixar o Tailscale",
|
|
||||||
waiting: "Aguardando o Tailscale iniciar neste host",
|
|
||||||
alwaysOn: "Sempre ativado, porque este host já aceita conexões do Tailscale",
|
|
||||||
socket: "Desativado, porque este host escuta em um socket local",
|
|
||||||
launch: "Controlado pelo comando que inicia este host",
|
|
||||||
update: "Atualize este host para usar o Tailscale",
|
|
||||||
updateDocs: "Como atualizar",
|
|
||||||
address: "Em um celular com Tailscale, adicione um host com este endereço",
|
|
||||||
statusError: "Não foi possível verificar o Tailscale",
|
|
||||||
turnOnError: "Não foi possível ativar o Tailscale",
|
|
||||||
turnOffError: "Não foi possível desativar o Tailscale",
|
|
||||||
confirmTitle: "Desativar o Tailscale?",
|
|
||||||
confirmMessage:
|
|
||||||
"Este dispositivo está conectado pelo Tailscale e perderá a conexão com o host.",
|
|
||||||
confirmAction: "Desativar",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
pairing: {
|
pairing: {
|
||||||
hostPassword: {
|
hostPassword: {
|
||||||
title: "Senha de {{host}}",
|
title: "Senha de {{host}}",
|
||||||
@@ -2955,7 +2936,9 @@ export const ptBR: TranslationResources = {
|
|||||||
timeout: "Timeout",
|
timeout: "Timeout",
|
||||||
},
|
},
|
||||||
pairDevices: {
|
pairDevices: {
|
||||||
|
title: "Parear dispositivos",
|
||||||
rowTitle: "Parear um dispositivo",
|
rowTitle: "Parear um dispositivo",
|
||||||
|
rowHint: "Escaneie um QR code ou copie um link para conectar seu celular a este host",
|
||||||
},
|
},
|
||||||
skills: {
|
skills: {
|
||||||
...en.settings.host.skills,
|
...en.settings.host.skills,
|
||||||
|
|||||||
@@ -749,6 +749,8 @@ export const ru: TranslationResources = {
|
|||||||
resumeCommandUnavailable: "Команда возобновления недоступна",
|
resumeCommandUnavailable: "Команда возобновления недоступна",
|
||||||
reloadingAgent: "Перезагрузка агента...",
|
reloadingAgent: "Перезагрузка агента...",
|
||||||
reloadedAgent: "Агент перезагружен",
|
reloadedAgent: "Агент перезагружен",
|
||||||
|
reloadedAgentHistoryDiverged:
|
||||||
|
"Агент перезагружен, но история провайдера не совпадает с этим чатом, поэтому она не синхронизирована",
|
||||||
failedToReloadAgent: "Не удалось перезагрузить агента",
|
failedToReloadAgent: "Не удалось перезагрузить агента",
|
||||||
failedToCloseAgent: "Не удалось закрыть агента",
|
failedToCloseAgent: "Не удалось закрыть агента",
|
||||||
},
|
},
|
||||||
@@ -1824,6 +1826,12 @@ export const ru: TranslationResources = {
|
|||||||
"Полнофункциональное нативное мобильное приложение позволяет управлять любым компьютером с Paseo с телефона",
|
"Полнофункциональное нативное мобильное приложение позволяет управлять любым компьютером с Paseo с телефона",
|
||||||
appStore: "App Store",
|
appStore: "App Store",
|
||||||
googlePlay: "Google Play",
|
googlePlay: "Google Play",
|
||||||
|
connectTitle: "Выберите способ подключения",
|
||||||
|
connectDocs: "Документация",
|
||||||
|
openConnectDocs: "Открыть документацию по подключению",
|
||||||
|
recommended: "Рекомендуется",
|
||||||
|
relay: { title: "Ретранслятор", hint: "Сквозное шифрование, отсканируйте QR-код" },
|
||||||
|
tailscale: { title: "Tailscale", hint: "Требует небольшой настройки" },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -1902,32 +1910,6 @@ export const ru: TranslationResources = {
|
|||||||
hostDisconnected: "Хост не подключён",
|
hostDisconnected: "Хост не подключён",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
devices: {
|
|
||||||
title: "Устройства",
|
|
||||||
waysToConnect: "Способы подключения",
|
|
||||||
docs: "Документация",
|
|
||||||
docsAccessibility: "Открыть документацию по подключению",
|
|
||||||
recommended: "Рекомендуется",
|
|
||||||
relay: { title: "Ретранслятор", hint: "Сквозное шифрование, отсканируйте QR-код" },
|
|
||||||
tailscale: {
|
|
||||||
hint: "Прямое подключение через ваш tailnet, по адресу",
|
|
||||||
unavailable: "Tailscale не запущен на этом хосте",
|
|
||||||
install: "Скачать Tailscale",
|
|
||||||
waiting: "Ожидаем запуска Tailscale на этом хосте",
|
|
||||||
alwaysOn: "Всегда включено, так как хост уже принимает подключения Tailscale",
|
|
||||||
socket: "Выключено, так как хост слушает локальный сокет",
|
|
||||||
launch: "Управляется командой, которая запускает этот хост",
|
|
||||||
update: "Обновите этот хост, чтобы использовать Tailscale",
|
|
||||||
updateDocs: "Как обновить",
|
|
||||||
address: "На телефоне с Tailscale добавьте хост с этим адресом",
|
|
||||||
statusError: "Не удалось проверить Tailscale",
|
|
||||||
turnOnError: "Не удалось включить Tailscale",
|
|
||||||
turnOffError: "Не удалось выключить Tailscale",
|
|
||||||
confirmTitle: "Выключить Tailscale?",
|
|
||||||
confirmMessage: "Это устройство подключено через Tailscale и потеряет соединение с хостом.",
|
|
||||||
confirmAction: "Выключить",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
pairing: {
|
pairing: {
|
||||||
hostPassword: {
|
hostPassword: {
|
||||||
title: "Пароль для {{host}}",
|
title: "Пароль для {{host}}",
|
||||||
@@ -2962,7 +2944,10 @@ export const ru: TranslationResources = {
|
|||||||
timeout: "Время ожидания истекло",
|
timeout: "Время ожидания истекло",
|
||||||
},
|
},
|
||||||
pairDevices: {
|
pairDevices: {
|
||||||
|
title: "Подключение устройств",
|
||||||
rowTitle: "Подключить устройство",
|
rowTitle: "Подключить устройство",
|
||||||
|
rowHint:
|
||||||
|
"Отсканируйте QR-код или скопируйте ссылку, чтобы подключить телефон к этому хосту.",
|
||||||
},
|
},
|
||||||
skills: {
|
skills: {
|
||||||
sectionTitle: "Навыки оркестрации",
|
sectionTitle: "Навыки оркестрации",
|
||||||
|
|||||||
@@ -741,6 +741,8 @@ export const zhCN: TranslationResources = {
|
|||||||
resumeCommandUnavailable: "恢复命令不可用",
|
resumeCommandUnavailable: "恢复命令不可用",
|
||||||
reloadingAgent: "正在重新加载 Agent...",
|
reloadingAgent: "正在重新加载 Agent...",
|
||||||
reloadedAgent: "已重新加载 Agent",
|
reloadedAgent: "已重新加载 Agent",
|
||||||
|
reloadedAgentHistoryDiverged:
|
||||||
|
"已重新加载 Agent,但提供方的历史记录与此对话不一致,因此未同步",
|
||||||
failedToReloadAgent: "重新加载 Agent 失败",
|
failedToReloadAgent: "重新加载 Agent 失败",
|
||||||
failedToCloseAgent: "关闭 Agent 失败",
|
failedToCloseAgent: "关闭 Agent 失败",
|
||||||
},
|
},
|
||||||
@@ -1773,6 +1775,12 @@ export const zhCN: TranslationResources = {
|
|||||||
description: "功能完整的原生移动应用让你可以在手机上控制任意一台 Paseo 电脑",
|
description: "功能完整的原生移动应用让你可以在手机上控制任意一台 Paseo 电脑",
|
||||||
appStore: "App Store",
|
appStore: "App Store",
|
||||||
googlePlay: "Google Play",
|
googlePlay: "Google Play",
|
||||||
|
connectTitle: "选择连接方式",
|
||||||
|
connectDocs: "文档",
|
||||||
|
openConnectDocs: "打开连接文档",
|
||||||
|
recommended: "推荐",
|
||||||
|
relay: { title: "中继", hint: "端到端加密,扫描二维码" },
|
||||||
|
tailscale: { title: "Tailscale", hint: "需要一些设置" },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -1851,32 +1859,6 @@ export const zhCN: TranslationResources = {
|
|||||||
hostDisconnected: "Host 未连接",
|
hostDisconnected: "Host 未连接",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
devices: {
|
|
||||||
title: "设备",
|
|
||||||
waysToConnect: "连接方式",
|
|
||||||
docs: "文档",
|
|
||||||
docsAccessibility: "打开连接文档",
|
|
||||||
recommended: "推荐",
|
|
||||||
relay: { title: "中继", hint: "端到端加密,扫描二维码" },
|
|
||||||
tailscale: {
|
|
||||||
hint: "通过你的 tailnet 直连,输入地址即可",
|
|
||||||
unavailable: "此主机未运行 Tailscale",
|
|
||||||
install: "获取 Tailscale",
|
|
||||||
waiting: "正在等待此主机上的 Tailscale 启动",
|
|
||||||
alwaysOn: "始终开启,因为此主机已接受 Tailscale 连接",
|
|
||||||
socket: "已关闭,因为此主机监听的是本地套接字",
|
|
||||||
launch: "由启动此主机的命令控制",
|
|
||||||
update: "更新此主机以使用 Tailscale",
|
|
||||||
updateDocs: "如何更新",
|
|
||||||
address: "在已连接 Tailscale 的手机上,用此地址添加主机",
|
|
||||||
statusError: "无法检查 Tailscale",
|
|
||||||
turnOnError: "无法开启 Tailscale",
|
|
||||||
turnOffError: "无法关闭 Tailscale",
|
|
||||||
confirmTitle: "关闭 Tailscale?",
|
|
||||||
confirmMessage: "此设备通过 Tailscale 连接,关闭后将与主机断开连接。",
|
|
||||||
confirmAction: "关闭",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
pairing: {
|
pairing: {
|
||||||
hostPassword: {
|
hostPassword: {
|
||||||
title: "{{host}} 的密码",
|
title: "{{host}} 的密码",
|
||||||
@@ -2883,7 +2865,9 @@ export const zhCN: TranslationResources = {
|
|||||||
timeout: "超时",
|
timeout: "超时",
|
||||||
},
|
},
|
||||||
pairDevices: {
|
pairDevices: {
|
||||||
|
title: "配对设备",
|
||||||
rowTitle: "配对设备",
|
rowTitle: "配对设备",
|
||||||
|
rowHint: "扫描二维码或复制链接,将手机连接到这个 Host",
|
||||||
},
|
},
|
||||||
skills: {
|
skills: {
|
||||||
...en.settings.host.skills,
|
...en.settings.host.skills,
|
||||||
|
|||||||
@@ -1,11 +1,17 @@
|
|||||||
import { useCallback } from "react";
|
import { useCallback, useMemo, useState } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { View } from "react-native";
|
import { View } from "react-native";
|
||||||
import { StyleSheet } from "react-native-unistyles";
|
import { StyleSheet } from "react-native-unistyles";
|
||||||
import { AppleIcon } from "@/components/icons/apple-icon";
|
import { AppleIcon } from "@/components/icons/apple-icon";
|
||||||
import { GooglePlayIcon } from "@/components/icons/google-play-icon";
|
import { GooglePlayIcon } from "@/components/icons/google-play-icon";
|
||||||
|
import { SettingsCard, SettingsDetailRow, SettingsSection } from "@/components/settings";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { WaysToConnect } from "@/devices";
|
import { StatusBadge } from "@/components/ui/status-badge";
|
||||||
|
import { PairDeviceModal } from "@/desktop/components/pair-device-modal";
|
||||||
|
import {
|
||||||
|
CONNECTIVITY_DOCS_URL,
|
||||||
|
TAILSCALE_DOCS_URL,
|
||||||
|
} from "@/desktop/components/pair-device-section";
|
||||||
import { ICON_SIZE } from "@/styles/theme";
|
import { ICON_SIZE } from "@/styles/theme";
|
||||||
import { openExternalUrl } from "@/utils/open-external-url";
|
import { openExternalUrl } from "@/utils/open-external-url";
|
||||||
|
|
||||||
@@ -20,11 +26,33 @@ function openUrl(url: string) {
|
|||||||
void openExternalUrl(url).catch(console.error);
|
void openExternalUrl(url).catch(console.error);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Get the app, then connect it the same ways the host's Devices settings offer. */
|
/** Get the app, then connect it: the relay pairs in a modal, Tailscale is a docs page away. */
|
||||||
export function PhoneStep({ serverId }: { serverId: string }) {
|
export function PhoneStep({ serverId }: { serverId: string }) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
const [isPairing, setIsPairing] = useState(false);
|
||||||
const openAppStore = useCallback(() => openUrl(APP_STORE_URL), []);
|
const openAppStore = useCallback(() => openUrl(APP_STORE_URL), []);
|
||||||
const openPlayStore = useCallback(() => openUrl(PLAY_STORE_URL), []);
|
const openPlayStore = useCallback(() => openUrl(PLAY_STORE_URL), []);
|
||||||
|
const openTailscaleDocs = useCallback(() => openUrl(TAILSCALE_DOCS_URL), []);
|
||||||
|
const openPairing = useCallback(() => setIsPairing(true), []);
|
||||||
|
const closePairing = useCallback(() => setIsPairing(false), []);
|
||||||
|
const recommendedBadge = useMemo(
|
||||||
|
() => (
|
||||||
|
<StatusBadge
|
||||||
|
size="xs"
|
||||||
|
variant="success"
|
||||||
|
label={t("onboarding.setup.steps.phone.recommended")}
|
||||||
|
/>
|
||||||
|
),
|
||||||
|
[t],
|
||||||
|
);
|
||||||
|
const docsLink = useMemo(
|
||||||
|
() => ({
|
||||||
|
href: CONNECTIVITY_DOCS_URL,
|
||||||
|
label: t("onboarding.setup.steps.phone.connectDocs"),
|
||||||
|
accessibilityLabel: t("onboarding.setup.steps.phone.openConnectDocs"),
|
||||||
|
}),
|
||||||
|
[t],
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<View style={styles.container}>
|
<View style={styles.container}>
|
||||||
@@ -36,7 +64,31 @@ export function PhoneStep({ serverId }: { serverId: string }) {
|
|||||||
{t("onboarding.setup.steps.phone.googlePlay")}
|
{t("onboarding.setup.steps.phone.googlePlay")}
|
||||||
</Button>
|
</Button>
|
||||||
</View>
|
</View>
|
||||||
<WaysToConnect serverId={serverId} />
|
<SettingsSection title={t("onboarding.setup.steps.phone.connectTitle")} link={docsLink}>
|
||||||
|
<SettingsCard>
|
||||||
|
<SettingsDetailRow
|
||||||
|
label={t("onboarding.setup.steps.phone.relay.title")}
|
||||||
|
labelAccessory={recommendedBadge}
|
||||||
|
hint={t("onboarding.setup.steps.phone.relay.hint")}
|
||||||
|
onPress={openPairing}
|
||||||
|
testID="onboarding-phone-relay"
|
||||||
|
/>
|
||||||
|
<SettingsDetailRow
|
||||||
|
label={t("onboarding.setup.steps.phone.tailscale.title")}
|
||||||
|
hint={t("onboarding.setup.steps.phone.tailscale.hint")}
|
||||||
|
summary={t("onboarding.setup.steps.phone.connectDocs")}
|
||||||
|
onPress={openTailscaleDocs}
|
||||||
|
external
|
||||||
|
testID="onboarding-phone-tailscale"
|
||||||
|
/>
|
||||||
|
</SettingsCard>
|
||||||
|
</SettingsSection>
|
||||||
|
<PairDeviceModal
|
||||||
|
serverId={serverId}
|
||||||
|
visible={isPairing}
|
||||||
|
onClose={closePairing}
|
||||||
|
testID="onboarding-pair-device-card"
|
||||||
|
/>
|
||||||
</View>
|
</View>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -197,7 +197,7 @@ describe("plugin timeline projection", () => {
|
|||||||
kind: "assistant_message",
|
kind: "assistant_message",
|
||||||
id: "assistant-1",
|
id: "assistant-1",
|
||||||
messageId: "provider-msg-1",
|
messageId: "provider-msg-1",
|
||||||
timelineCursor: { epoch: "e1", seq: 7 },
|
timelineCursor: { epoch: "e1", seq: 7, anchorSeq: 7 },
|
||||||
turnId: "turn-1",
|
turnId: "turn-1",
|
||||||
text: 'Summary\n\n```ui\nCard("Hi", [])\n```',
|
text: 'Summary\n\n```ui\nCard("Hi", [])\n```',
|
||||||
timestamp: new Date("2026-01-01T00:00:02.000Z"),
|
timestamp: new Date("2026-01-01T00:00:02.000Z"),
|
||||||
@@ -226,13 +226,13 @@ describe("plugin timeline projection", () => {
|
|||||||
{
|
{
|
||||||
kind: "plugin",
|
kind: "plugin",
|
||||||
id: "genui/assistant-1/text",
|
id: "genui/assistant-1/text",
|
||||||
timelineCursor: { epoch: "e1", seq: 7 },
|
timelineCursor: { epoch: "e1", seq: 7, anchorSeq: 7 },
|
||||||
turnId: "turn-1",
|
turnId: "turn-1",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
kind: "plugin",
|
kind: "plugin",
|
||||||
id: "genui/assistant-1/card",
|
id: "genui/assistant-1/card",
|
||||||
timelineCursor: { epoch: "e1", seq: 7 },
|
timelineCursor: { epoch: "e1", seq: 7, anchorSeq: 7 },
|
||||||
turnId: "turn-1",
|
turnId: "turn-1",
|
||||||
},
|
},
|
||||||
]);
|
]);
|
||||||
|
|||||||
@@ -91,7 +91,7 @@ describe("AgentDirectoryReplica", () => {
|
|||||||
id: "reply",
|
id: "reply",
|
||||||
text: "server history",
|
text: "server history",
|
||||||
timestamp: new Date(),
|
timestamp: new Date(),
|
||||||
timelineCursor: { epoch: "e", seq: 1 },
|
timelineCursor: { epoch: "e", seq: 1, anchorSeq: 1 },
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
head: [],
|
head: [],
|
||||||
|
|||||||
@@ -255,6 +255,7 @@ const PROBE_INACTIVE_WHILE_ONLINE_MAX_MS = 30 * 60_000;
|
|||||||
const ACTIVE_RTT_WINDOW_MS = 60_000;
|
const ACTIVE_RTT_WINDOW_MS = 60_000;
|
||||||
const ADAPTIVE_SWITCH_THRESHOLD_MS = 40;
|
const ADAPTIVE_SWITCH_THRESHOLD_MS = 40;
|
||||||
const ADAPTIVE_SWITCH_MIN_IMPROVEMENT_RATIO = 0.35;
|
const ADAPTIVE_SWITCH_MIN_IMPROVEMENT_RATIO = 0.35;
|
||||||
|
const MAX_STALE_TIMELINE_PAGE_ATTEMPTS = 3;
|
||||||
const ADAPTIVE_SWITCH_CONSECUTIVE_PROBES = 3;
|
const ADAPTIVE_SWITCH_CONSECUTIVE_PROBES = 3;
|
||||||
const CONFIGURED_OVERRIDE_BOOTSTRAP_RETRY_MS = 1_000;
|
const CONFIGURED_OVERRIDE_BOOTSTRAP_RETRY_MS = 1_000;
|
||||||
|
|
||||||
@@ -3128,12 +3129,19 @@ export class HostRuntimeStore {
|
|||||||
const directory = this.directorySyncByServer.get(serverId);
|
const directory = this.directorySyncByServer.get(serverId);
|
||||||
if (!directory) throw new Error(`Unknown host runtime for serverId ${serverId}`);
|
if (!directory) throw new Error(`Unknown host runtime for serverId ${serverId}`);
|
||||||
const owner = useSessionStore.getState().sessions[serverId]?.viewedTimelineSync;
|
const owner = useSessionStore.getState().sessions[serverId]?.viewedTimelineSync;
|
||||||
const page = await directory.fetchTimeline(agentId, request);
|
// A page served before a rewind this client applied is asked for again. Seqs only grow within
|
||||||
if (owner && useSessionStore.getState().sessions[serverId]?.viewedTimelineSync === owner) {
|
// 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.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(
|
createViewedTimelineOwner(
|
||||||
|
|||||||
@@ -189,7 +189,7 @@ function timelineItem(text = "Cached"): StreamItem {
|
|||||||
id: "message-1",
|
id: "message-1",
|
||||||
text,
|
text,
|
||||||
timestamp: new Date("2026-07-18T08:02:00.000Z"),
|
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,
|
version: 1,
|
||||||
data: { passed: 4, failed: 0 },
|
data: { passed: 4, failed: 0 },
|
||||||
timestamp: new Date("2026-07-18T08:02:00.000Z"),
|
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", {
|
writer.commitTimeline(SERVER_ID, "agent-1", {
|
||||||
agentId: "agent-1",
|
agentId: "agent-1",
|
||||||
@@ -885,6 +885,32 @@ describe("ReplicaCache", () => {
|
|||||||
expect(await createCache(storage).readTimeline(SERVER_ID, "agent-1")).toBeUndefined();
|
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 () => {
|
it("refetches old cached Markdown fragments instead of offering them as whole messages", async () => {
|
||||||
const storage = new MemoryStorage();
|
const storage = new MemoryStorage();
|
||||||
const writer = createCache(storage);
|
const writer = createCache(storage);
|
||||||
@@ -1355,7 +1381,7 @@ it("retains semantic agent messages across disk-cache reconstruction", async ()
|
|||||||
kind: "tool_call",
|
kind: "tool_call",
|
||||||
id: "delivery",
|
id: "delivery",
|
||||||
timestamp: new Date(1),
|
timestamp: new Date(1),
|
||||||
timelineCursor: { epoch: "epoch-1", seq: 12 },
|
timelineCursor: { epoch: "epoch-1", seq: 12, anchorSeq: 12 },
|
||||||
payload: {
|
payload: {
|
||||||
source: "agent",
|
source: "agent",
|
||||||
data: {
|
data: {
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ import {
|
|||||||
isUnreconciledLocalUserMessage,
|
isUnreconciledLocalUserMessage,
|
||||||
type AgentToolCallData,
|
type AgentToolCallData,
|
||||||
type StreamItem,
|
type StreamItem,
|
||||||
|
type TimelinePosition,
|
||||||
} from "@/types/stream";
|
} from "@/types/stream";
|
||||||
import type { UnsettledTurn } from "@/timeline/turn-liveness";
|
import type { UnsettledTurn } from "@/timeline/turn-liveness";
|
||||||
import { normalizeAgentSnapshot } from "@/utils/agent-snapshots";
|
import { normalizeAgentSnapshot } from "@/utils/agent-snapshots";
|
||||||
@@ -82,7 +83,15 @@ const IsoDateSchema = z.iso.datetime();
|
|||||||
const TimelinePositionSchema = z.strictObject({
|
const TimelinePositionSchema = z.strictObject({
|
||||||
epoch: z.string(),
|
epoch: z.string(),
|
||||||
seq: z.number().int().nonnegative(),
|
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(() =>
|
const PluginTimelineDataSchema: z.ZodType<PluginTimelineData> = z.lazy(() =>
|
||||||
z.union([
|
z.union([
|
||||||
z.null(),
|
z.null(),
|
||||||
@@ -423,6 +432,10 @@ function deserializeTimeline(stored: StoredTimeline | null): CachedTimeline | nu
|
|||||||
if (!stored) {
|
if (!stored) {
|
||||||
return null;
|
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 {
|
return {
|
||||||
agentId: stored.agentId,
|
agentId: stored.agentId,
|
||||||
items: stored.items.map(deserializeTimelineItem),
|
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 {
|
function deserializeTimelineItem(item: StoredTimelineItem): StreamItem {
|
||||||
if (item.kind === "plugin") {
|
if (item.kind === "plugin") {
|
||||||
return {
|
return {
|
||||||
id: item.id,
|
id: item.id,
|
||||||
...(item.timelineCursor ? { timelineCursor: item.timelineCursor } : {}),
|
...anchoredPosition(item.timelineCursor),
|
||||||
...(item.turnId ? { turnId: item.turnId } : {}),
|
...(item.turnId ? { turnId: item.turnId } : {}),
|
||||||
timestamp: new Date(item.timestamp),
|
timestamp: new Date(item.timestamp),
|
||||||
kind: item.kind,
|
kind: item.kind,
|
||||||
@@ -562,7 +584,7 @@ function deserializeBuiltinTimelineItem(
|
|||||||
): StreamItem {
|
): StreamItem {
|
||||||
const base = {
|
const base = {
|
||||||
id: item.id,
|
id: item.id,
|
||||||
...(item.timelineCursor ? { timelineCursor: item.timelineCursor } : {}),
|
...anchoredPosition(item.timelineCursor),
|
||||||
...(item.turnId ? { turnId: item.turnId } : {}),
|
...(item.turnId ? { turnId: item.turnId } : {}),
|
||||||
timestamp: new Date(item.timestamp),
|
timestamp: new Date(item.timestamp),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ import {
|
|||||||
HEADER_TOP_PADDING_MOBILE,
|
HEADER_TOP_PADDING_MOBILE,
|
||||||
} from "@/constants/layout";
|
} from "@/constants/layout";
|
||||||
import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
|
import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
|
||||||
import { PairDeviceModal } from "@/devices";
|
import { PairDeviceModal } from "@/desktop/components/pair-device-modal";
|
||||||
import { buildSettingsHostSectionRoute } from "@/utils/host-routes";
|
import { buildSettingsHostSectionRoute } from "@/utils/host-routes";
|
||||||
import { WINDOW_CONTENT_DATASET } from "@/components/desktop/titlebar-drag-region";
|
import { WINDOW_CONTENT_DATASET } from "@/components/desktop/titlebar-drag-region";
|
||||||
|
|
||||||
|
|||||||
@@ -102,7 +102,7 @@ import {
|
|||||||
} from "@/i18n/locales";
|
} from "@/i18n/locales";
|
||||||
import {
|
import {
|
||||||
HostConnectionsPage,
|
HostConnectionsPage,
|
||||||
HostDevicesPage,
|
HostPairDevicePage,
|
||||||
HostAgentsPage,
|
HostAgentsPage,
|
||||||
HostAgentProfilesPage,
|
HostAgentProfilesPage,
|
||||||
HostSettingsPage,
|
HostSettingsPage,
|
||||||
@@ -250,7 +250,7 @@ const HOST_SECTION_ITEMS: HostSectionItem[] = [
|
|||||||
{ id: "host", labelKey: "settings.hostSections.host", icon: Server },
|
{ id: "host", labelKey: "settings.hostSections.host", icon: Server },
|
||||||
{ id: "projects", labelKey: "settings.hostSections.projects", icon: FolderGit2 },
|
{ id: "projects", labelKey: "settings.hostSections.projects", icon: FolderGit2 },
|
||||||
{ id: "connections", labelKey: "settings.hostSections.connections", icon: Network },
|
{ id: "connections", labelKey: "settings.hostSections.connections", icon: Network },
|
||||||
{ id: "devices", labelKey: "devices.title", icon: Smartphone },
|
{ id: "pair-device", labelKey: "openProject.tiles.pairDevice.title", icon: Smartphone },
|
||||||
{ id: "agents", labelKey: "settings.hostSections.agents", icon: Bot },
|
{ id: "agents", labelKey: "settings.hostSections.agents", icon: Bot },
|
||||||
{ id: "agent-profiles", labelKey: "settings.hostSections.agentProfiles", icon: Layers },
|
{ id: "agent-profiles", labelKey: "settings.hostSections.agentProfiles", icon: Layers },
|
||||||
{ id: "metadata", labelKey: "settings.hostSections.metadata", icon: Sparkles },
|
{ id: "metadata", labelKey: "settings.hostSections.metadata", icon: Sparkles },
|
||||||
@@ -271,8 +271,8 @@ function renderHostSettingsContent(
|
|||||||
return <ProjectsScreen serverId={view.serverId} />;
|
return <ProjectsScreen serverId={view.serverId} />;
|
||||||
case "connections":
|
case "connections":
|
||||||
return <HostConnectionsPage serverId={view.serverId} />;
|
return <HostConnectionsPage serverId={view.serverId} />;
|
||||||
case "devices":
|
case "pair-device":
|
||||||
return <HostDevicesPage serverId={view.serverId} />;
|
return <HostPairDevicePage serverId={view.serverId} />;
|
||||||
case "agents":
|
case "agents":
|
||||||
return <HostAgentsPage serverId={view.serverId} />;
|
return <HostAgentsPage serverId={view.serverId} />;
|
||||||
case "agent-profiles":
|
case "agent-profiles":
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import {
|
|||||||
ArrowDown,
|
ArrowDown,
|
||||||
ArrowUp,
|
ArrowUp,
|
||||||
ArrowUpToLine,
|
ArrowUpToLine,
|
||||||
|
ChevronRight,
|
||||||
Globe,
|
Globe,
|
||||||
Monitor,
|
Monitor,
|
||||||
Pencil,
|
Pencil,
|
||||||
@@ -13,7 +14,7 @@ import {
|
|||||||
import type { TFunction } from "i18next";
|
import type { TFunction } from "i18next";
|
||||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { Alert, Text, View } from "react-native";
|
import { Alert, Pressable, Text, View } from "react-native";
|
||||||
import { StyleSheet, useUnistyles, withUnistyles } from "react-native-unistyles";
|
import { StyleSheet, useUnistyles, withUnistyles } from "react-native-unistyles";
|
||||||
import type { TerminalProfile } from "@getpaseo/protocol/messages";
|
import type { TerminalProfile } from "@getpaseo/protocol/messages";
|
||||||
import {
|
import {
|
||||||
@@ -37,7 +38,7 @@ import { startDesktopDaemon, stopDesktopDaemon } from "@/desktop/daemon/desktop-
|
|||||||
import { LocalDaemonSection } from "@/desktop/components/desktop-updates-section";
|
import { LocalDaemonSection } from "@/desktop/components/desktop-updates-section";
|
||||||
import { useDaemonStatus } from "@/desktop/hooks/use-daemon-status";
|
import { useDaemonStatus } from "@/desktop/hooks/use-daemon-status";
|
||||||
import { useDesktopSettings } from "@/desktop/settings/desktop-settings";
|
import { useDesktopSettings } from "@/desktop/settings/desktop-settings";
|
||||||
import { WaysToConnect } from "@/devices";
|
import { PairDeviceModal } from "@/desktop/components/pair-device-modal";
|
||||||
import { useDaemonConfig } from "@/hooks/use-daemon-config";
|
import { useDaemonConfig } from "@/hooks/use-daemon-config";
|
||||||
import { useIsLocalDaemon } from "@/hooks/use-is-local-daemon";
|
import { useIsLocalDaemon } from "@/hooks/use-is-local-daemon";
|
||||||
import {
|
import {
|
||||||
@@ -264,14 +265,19 @@ export function HostConnectionsPage({ serverId }: { serverId: string }) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function HostDevicesPage({ serverId }: { serverId: string }) {
|
export function HostPairDevicePage({ serverId }: { serverId: string }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
const host = useHostProfile(serverId);
|
const host = useHostProfile(serverId);
|
||||||
|
|
||||||
if (!host) {
|
if (!host) {
|
||||||
return <HostNotFound />;
|
return <HostNotFound />;
|
||||||
}
|
}
|
||||||
|
|
||||||
return <WaysToConnect serverId={serverId} />;
|
return (
|
||||||
|
<SettingsSection title={t("settings.host.pairDevices.title")}>
|
||||||
|
<PairDeviceRow serverId={serverId} />
|
||||||
|
</SettingsSection>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function HostAgentsPage({ serverId }: { serverId: string }) {
|
export function HostAgentsPage({ serverId }: { serverId: string }) {
|
||||||
@@ -1124,6 +1130,39 @@ function AppendSystemPromptCard({ serverId }: { serverId: string }) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function PairDeviceRow({ serverId }: { serverId: string }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const { theme } = useUnistyles();
|
||||||
|
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||||
|
|
||||||
|
const handleOpen = useCallback(() => setIsModalOpen(true), []);
|
||||||
|
const handleClose = useCallback(() => setIsModalOpen(false), []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<View style={settingsStyles.card}>
|
||||||
|
<Pressable
|
||||||
|
style={settingsStyles.row}
|
||||||
|
onPress={handleOpen}
|
||||||
|
accessibilityRole="button"
|
||||||
|
testID="host-page-pair-device-row"
|
||||||
|
>
|
||||||
|
<View style={settingsStyles.rowContent}>
|
||||||
|
<Text style={settingsStyles.rowTitle}>{t("settings.host.pairDevices.rowTitle")}</Text>
|
||||||
|
<Text style={settingsStyles.rowHint}>{t("settings.host.pairDevices.rowHint")}</Text>
|
||||||
|
</View>
|
||||||
|
<ChevronRight size={theme.iconSize.sm} color={theme.colors.foregroundMuted} />
|
||||||
|
</Pressable>
|
||||||
|
|
||||||
|
<PairDeviceModal
|
||||||
|
serverId={serverId}
|
||||||
|
visible={isModalOpen}
|
||||||
|
onClose={handleClose}
|
||||||
|
testID="host-page-pair-device-card"
|
||||||
|
/>
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function RemoveHostSection({
|
function RemoveHostSection({
|
||||||
host,
|
host,
|
||||||
isLocalDaemon,
|
isLocalDaemon,
|
||||||
|
|||||||
@@ -2188,11 +2188,10 @@ function WorkspaceScreenContent({
|
|||||||
|
|
||||||
toast.show(t("workspace.tabs.toasts.reloadingAgent"), { durationMs: null });
|
toast.show(t("workspace.tabs.toasts.reloadingAgent"), { durationMs: null });
|
||||||
try {
|
try {
|
||||||
await client.refreshAgent(agentId);
|
const refreshed = await client.refreshAgent(agentId);
|
||||||
// Send the existing cursor so the server detects the new epoch and
|
// Send the existing cursor: Reload agent keeps the history, so the server
|
||||||
// returns reset:true. Without a cursor, the server returns reset:false
|
// returns only the rows it added. When the history was imported again
|
||||||
// and the client takes the incremental path, where new-epoch rows are
|
// under a new epoch, the cursor reads as stale and the server resets.
|
||||||
// dropped against the stale cursor.
|
|
||||||
const sessionState = useSessionStore.getState().sessions[normalizedServerId];
|
const sessionState = useSessionStore.getState().sessions[normalizedServerId];
|
||||||
const currentCursor = sessionState?.agentTimelineCursor.get(agentId);
|
const currentCursor = sessionState?.agentTimelineCursor.get(agentId);
|
||||||
await getHostRuntimeStore().fetchAgentTimeline(normalizedServerId, agentId, {
|
await getHostRuntimeStore().fetchAgentTimeline(normalizedServerId, agentId, {
|
||||||
@@ -2201,7 +2200,13 @@ function WorkspaceScreenContent({
|
|||||||
? { cursor: { epoch: currentCursor.epoch, seq: currentCursor.endSeq } }
|
? { 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) {
|
} catch (error) {
|
||||||
toast.error(
|
toast.error(
|
||||||
error instanceof Error ? error.message : t("workspace.tabs.toasts.failedToReloadAgent"),
|
error instanceof Error ? error.message : t("workspace.tabs.toasts.failedToReloadAgent"),
|
||||||
|
|||||||
@@ -324,6 +324,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 =
|
export type AgentTimelineState =
|
||||||
| { status: "cold" }
|
| { status: "cold" }
|
||||||
| { status: "painted"; items: StreamItem[] }
|
| { status: "painted"; items: StreamItem[] }
|
||||||
@@ -498,6 +504,7 @@ export interface SessionState {
|
|||||||
agentTimelineUnsettledTurn: Map<string, UnsettledTurn>;
|
agentTimelineUnsettledTurn: Map<string, UnsettledTurn>;
|
||||||
agentTimelineHasOlder: Map<string, boolean>;
|
agentTimelineHasOlder: Map<string, boolean>;
|
||||||
agentTimelineHasNewer: Map<string, boolean>;
|
agentTimelineHasNewer: Map<string, boolean>;
|
||||||
|
agentTimelineLatestRewind: Map<string, AgentTimelineRewind>;
|
||||||
agentTimelineOlderFetchInFlight: Map<string, boolean>;
|
agentTimelineOlderFetchInFlight: Map<string, boolean>;
|
||||||
historySyncGeneration: number;
|
historySyncGeneration: number;
|
||||||
agentHistorySyncGeneration: Map<string, number>;
|
agentHistorySyncGeneration: Map<string, number>;
|
||||||
@@ -617,6 +624,12 @@ interface SessionStoreActions {
|
|||||||
serverId: string,
|
serverId: string,
|
||||||
state: Map<string, boolean> | ((prev: Map<string, boolean>) => Map<string, boolean>),
|
state: Map<string, boolean> | ((prev: Map<string, boolean>) => Map<string, boolean>),
|
||||||
) => void;
|
) => 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: (
|
setAgentTimelineOlderFetchInFlight: (
|
||||||
serverId: string,
|
serverId: string,
|
||||||
state: Map<string, boolean> | ((prev: Map<string, boolean>) => Map<string, boolean>),
|
state: Map<string, boolean> | ((prev: Map<string, boolean>) => Map<string, boolean>),
|
||||||
@@ -753,6 +766,7 @@ function createInitialSessionState(
|
|||||||
agentTimelineUnsettledTurn: new Map(),
|
agentTimelineUnsettledTurn: new Map(),
|
||||||
agentTimelineHasOlder: new Map(),
|
agentTimelineHasOlder: new Map(),
|
||||||
agentTimelineHasNewer: new Map(),
|
agentTimelineHasNewer: new Map(),
|
||||||
|
agentTimelineLatestRewind: new Map(),
|
||||||
agentTimelineOlderFetchInFlight: new Map(),
|
agentTimelineOlderFetchInFlight: new Map(),
|
||||||
historySyncGeneration: 0,
|
historySyncGeneration: 0,
|
||||||
agentHistorySyncGeneration: new Map(),
|
agentHistorySyncGeneration: new Map(),
|
||||||
@@ -1401,6 +1415,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) => {
|
setAgentTimelineOlderFetchInFlight: (serverId, state) => {
|
||||||
set((prev) => {
|
set((prev) => {
|
||||||
const session = prev.sessions[serverId];
|
const session = prev.sessions[serverId];
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ function item(id: string, text: string, seq: number): StreamItem {
|
|||||||
id,
|
id,
|
||||||
text,
|
text,
|
||||||
timestamp: new Date("2026-08-26T10:00:00.000Z"),
|
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", () => {
|
describe("turn boundaries", () => {
|
||||||
it("commits a turn's final reply before the turn stops running", () => {
|
it("commits a turn's final reply before the turn stops running", () => {
|
||||||
useSessionStore.getState().initializeSession(SERVER_ID, null);
|
useSessionStore.getState().initializeSession(SERVER_ID, null);
|
||||||
|
|||||||
@@ -398,7 +398,7 @@ describe("processTimelineResponse", () => {
|
|||||||
messageId: "provider-message",
|
messageId: "provider-message",
|
||||||
text: "local prompt",
|
text: "local prompt",
|
||||||
timestamp: new Date(1000),
|
timestamp: new Date(1000),
|
||||||
timelineCursor: { epoch: "epoch-1", seq: 1 },
|
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
|
||||||
turnId: "turn-1",
|
turnId: "turn-1",
|
||||||
});
|
});
|
||||||
const hello = createUserMessage({
|
const hello = createUserMessage({
|
||||||
@@ -406,7 +406,7 @@ describe("processTimelineResponse", () => {
|
|||||||
clientMessageId: "hello-client",
|
clientMessageId: "hello-client",
|
||||||
text: "hello",
|
text: "hello",
|
||||||
timestamp: new Date(1500),
|
timestamp: new Date(1500),
|
||||||
timelineCursor: { epoch: "epoch-1", seq: 2 },
|
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
|
||||||
turnId: "turn-1",
|
turnId: "turn-1",
|
||||||
});
|
});
|
||||||
const currentTail = [canonical, makeAssistantItem("existing tail", "existing-tail"), hello];
|
const currentTail = [canonical, makeAssistantItem("existing tail", "existing-tail"), hello];
|
||||||
@@ -456,7 +456,7 @@ describe("processTimelineResponse", () => {
|
|||||||
id: "stale-history",
|
id: "stale-history",
|
||||||
text: "stale history",
|
text: "stale history",
|
||||||
timestamp: new Date(1040),
|
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 },
|
currentCursor: { epoch: "epoch-1", startSeq: 1, endSeq: 40 },
|
||||||
@@ -484,11 +484,11 @@ describe("processTimelineResponse", () => {
|
|||||||
const unresolved = makeSubmittedUserMessage("unresolved prompt", "client-unresolved");
|
const unresolved = makeSubmittedUserMessage("unresolved prompt", "client-unresolved");
|
||||||
const coveredLive: StreamItem = {
|
const coveredLive: StreamItem = {
|
||||||
...makeAssistantItem("covered live", "covered-live"),
|
...makeAssistantItem("covered live", "covered-live"),
|
||||||
timelineCursor: { epoch: "epoch-1", seq: 235 },
|
timelineCursor: { epoch: "epoch-1", seq: 235, anchorSeq: 235 },
|
||||||
};
|
};
|
||||||
const newerLive: StreamItem = {
|
const newerLive: StreamItem = {
|
||||||
...makeAssistantItem("newer live", "newer-live"),
|
...makeAssistantItem("newer live", "newer-live"),
|
||||||
timelineCursor: { epoch: "epoch-1", seq: 245 },
|
timelineCursor: { epoch: "epoch-1", seq: 245, anchorSeq: 245 },
|
||||||
};
|
};
|
||||||
|
|
||||||
const result = processTimelineResponse({
|
const result = processTimelineResponse({
|
||||||
@@ -573,7 +573,7 @@ describe("processTimelineResponse", () => {
|
|||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
kind: "assistant_message",
|
kind: "assistant_message",
|
||||||
text: "[System Error] failed",
|
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,
|
}).item,
|
||||||
} as AgentStreamEventPayload,
|
} as AgentStreamEventPayload,
|
||||||
timestamp: new Date(2000),
|
timestamp: new Date(2000),
|
||||||
timelineCursor: { epoch: "epoch-1", seq: 2 },
|
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
{ source: "canonical" },
|
{ source: "canonical" },
|
||||||
@@ -775,7 +775,7 @@ describe("processTimelineResponse", () => {
|
|||||||
|
|
||||||
expect(getAgentToolCalls([...result.tail, ...result.head])).toEqual([
|
expect(getAgentToolCalls([...result.tail, ...result.head])).toEqual([
|
||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
timelineCursor: { epoch: "epoch-1", seq: 2 },
|
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 1 },
|
||||||
payload: expect.objectContaining({
|
payload: expect.objectContaining({
|
||||||
data: expect.objectContaining({ callId, status: "completed" }),
|
data: expect.objectContaining({ callId, status: "completed" }),
|
||||||
}),
|
}),
|
||||||
@@ -796,7 +796,7 @@ describe("processTimelineResponse", () => {
|
|||||||
},
|
},
|
||||||
} as AgentStreamEventPayload,
|
} as AgentStreamEventPayload,
|
||||||
timestamp: new Date(2000),
|
timestamp: new Date(2000),
|
||||||
timelineCursor: { epoch: "epoch-1", seq: 2 },
|
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
{ source: "canonical" },
|
{ source: "canonical" },
|
||||||
@@ -831,7 +831,7 @@ describe("processTimelineResponse", () => {
|
|||||||
|
|
||||||
expect([...result.tail, ...result.head].filter((item) => item.kind === "todo_list")).toEqual([
|
expect([...result.tail, ...result.head].filter((item) => item.kind === "todo_list")).toEqual([
|
||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
timelineCursor: { epoch: "epoch-1", seq: 2 },
|
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 1 },
|
||||||
items: [{ text: "Verify hydration", completed: true }],
|
items: [{ text: "Verify hydration", completed: true }],
|
||||||
}),
|
}),
|
||||||
]);
|
]);
|
||||||
@@ -847,7 +847,7 @@ describe("processTimelineResponse", () => {
|
|||||||
item: { type: "compaction", status: "completed", trigger: "auto", preTokens: 1200 },
|
item: { type: "compaction", status: "completed", trigger: "auto", preTokens: 1200 },
|
||||||
} as AgentStreamEventPayload,
|
} as AgentStreamEventPayload,
|
||||||
timestamp: new Date(2000),
|
timestamp: new Date(2000),
|
||||||
timelineCursor: { epoch: "epoch-1", seq: 2 },
|
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
{ source: "canonical" },
|
{ source: "canonical" },
|
||||||
@@ -879,7 +879,7 @@ describe("processTimelineResponse", () => {
|
|||||||
|
|
||||||
expect([...result.tail, ...result.head].filter((item) => item.kind === "compaction")).toEqual([
|
expect([...result.tail, ...result.head].filter((item) => item.kind === "compaction")).toEqual([
|
||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
timelineCursor: { epoch: "epoch-1", seq: 2 },
|
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 1 },
|
||||||
status: "completed",
|
status: "completed",
|
||||||
trigger: "auto",
|
trigger: "auto",
|
||||||
preTokens: 1200,
|
preTokens: 1200,
|
||||||
@@ -918,7 +918,7 @@ describe("processTimelineResponse", () => {
|
|||||||
messageId: "assistant-live",
|
messageId: "assistant-live",
|
||||||
text: " continuation",
|
text: " continuation",
|
||||||
timestamp: new Date(2001),
|
timestamp: new Date(2001),
|
||||||
timelineCursor: { epoch: "epoch-1", seq: 101 },
|
timelineCursor: { epoch: "epoch-1", seq: 101, anchorSeq: 101 },
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
isInitializing: true,
|
isInitializing: true,
|
||||||
@@ -946,7 +946,7 @@ describe("processTimelineResponse", () => {
|
|||||||
);
|
);
|
||||||
expect(assistants).toHaveLength(1);
|
expect(assistants).toHaveLength(1);
|
||||||
expect(assistants[0]?.text).toBe("canonical prefix continuation");
|
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", () => {
|
it("keeps assistant segments separate when a live tool sits between them", () => {
|
||||||
@@ -963,12 +963,12 @@ describe("processTimelineResponse", () => {
|
|||||||
}).item,
|
}).item,
|
||||||
} as AgentStreamEventPayload,
|
} as AgentStreamEventPayload,
|
||||||
timestamp: new Date(2101),
|
timestamp: new Date(2101),
|
||||||
timelineCursor: { epoch: "epoch-1", seq: 101 },
|
timelineCursor: { epoch: "epoch-1", seq: 101, anchorSeq: 101 },
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
event: makeAssistantTimelineEvent("after tool", messageId),
|
event: makeAssistantTimelineEvent("after tool", messageId),
|
||||||
timestamp: new Date(2102),
|
timestamp: new Date(2102),
|
||||||
timelineCursor: { epoch: "epoch-1", seq: 102 },
|
timelineCursor: { epoch: "epoch-1", seq: 102, anchorSeq: 102 },
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
{ source: "canonical" },
|
{ source: "canonical" },
|
||||||
@@ -1019,7 +1019,7 @@ describe("processTimelineResponse", () => {
|
|||||||
id: "assistant-live",
|
id: "assistant-live",
|
||||||
text: "canonical prefix continuation",
|
text: "canonical prefix continuation",
|
||||||
timestamp: new Date(2001),
|
timestamp: new Date(2001),
|
||||||
timelineCursor: { epoch: "epoch-1", seq: 101 },
|
timelineCursor: { epoch: "epoch-1", seq: 101, anchorSeq: 101 },
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
isInitializing: true,
|
isInitializing: true,
|
||||||
@@ -1038,7 +1038,7 @@ describe("processTimelineResponse", () => {
|
|||||||
);
|
);
|
||||||
expect(assistants).toHaveLength(1);
|
expect(assistants).toHaveLength(1);
|
||||||
expect(assistants[0]?.text).toBe("canonical prefix continuation");
|
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", () => {
|
it("keeps a canonical live user row newer than the bootstrap page", () => {
|
||||||
@@ -1060,7 +1060,7 @@ describe("processTimelineResponse", () => {
|
|||||||
});
|
});
|
||||||
expect(live.head[0]).toMatchObject({
|
expect(live.head[0]).toMatchObject({
|
||||||
kind: "user_message",
|
kind: "user_message",
|
||||||
timelineCursor: { epoch: "epoch-1", seq: 101 },
|
timelineCursor: { epoch: "epoch-1", seq: 101, anchorSeq: 101 },
|
||||||
});
|
});
|
||||||
|
|
||||||
const result = processTimelineResponse({
|
const result = processTimelineResponse({
|
||||||
@@ -1123,7 +1123,7 @@ describe("processTimelineResponse", () => {
|
|||||||
kind: "user_message",
|
kind: "user_message",
|
||||||
clientMessageId: "client-message-1",
|
clientMessageId: "client-message-1",
|
||||||
messageId: "provider-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",
|
id: "newest",
|
||||||
text: "newest",
|
text: "newest",
|
||||||
timestamp: new Date(1000),
|
timestamp: new Date(1000),
|
||||||
timelineCursor: { epoch: "epoch-1", seq: 100 },
|
timelineCursor: { epoch: "epoch-1", seq: 100, anchorSeq: 100 },
|
||||||
},
|
},
|
||||||
makeSubmittedUserMessage("pending submission", "pending-submission"),
|
makeSubmittedUserMessage("pending submission", "pending-submission"),
|
||||||
],
|
],
|
||||||
@@ -2886,14 +2886,14 @@ describe("processTimelineResponse", () => {
|
|||||||
id: "oldest",
|
id: "oldest",
|
||||||
text: "oldest",
|
text: "oldest",
|
||||||
timestamp: new Date(1000),
|
timestamp: new Date(1000),
|
||||||
timelineCursor: { epoch: "epoch-1", seq: 1 },
|
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
kind: "user_message",
|
kind: "user_message",
|
||||||
id: "newest",
|
id: "newest",
|
||||||
text: "newest",
|
text: "newest",
|
||||||
timestamp: new Date(100_000),
|
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",
|
id: "newest",
|
||||||
text: "newest",
|
text: "newest",
|
||||||
timestamp: new Date(100_000),
|
timestamp: new Date(100_000),
|
||||||
timelineCursor: { epoch: "epoch-1", seq: 100 },
|
timelineCursor: { epoch: "epoch-1", seq: 100, anchorSeq: 100 },
|
||||||
},
|
},
|
||||||
...(lane === "tail" ? [pending] : []),
|
...(lane === "tail" ? [pending] : []),
|
||||||
],
|
],
|
||||||
@@ -2976,9 +2976,13 @@ describe("processTimelineResponse", () => {
|
|||||||
{
|
{
|
||||||
text: "local pending prompt",
|
text: "local pending prompt",
|
||||||
messageId: "canonical-message",
|
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: [],
|
head: [],
|
||||||
acknowledgedClientMessageIds: [clientMessageId],
|
acknowledgedClientMessageIds: [clientMessageId],
|
||||||
@@ -2992,7 +2996,7 @@ describe("processTimelineResponse", () => {
|
|||||||
{
|
{
|
||||||
event: makeToolCallTimelineEvent("call-1"),
|
event: makeToolCallTimelineEvent("call-1"),
|
||||||
timestamp: new Date(500),
|
timestamp: new Date(500),
|
||||||
timelineCursor: { epoch: "epoch-1", seq: 500 },
|
timelineCursor: { epoch: "epoch-1", seq: 500, anchorSeq: 500 },
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
{ source: "canonical" },
|
{ source: "canonical" },
|
||||||
@@ -3038,7 +3042,7 @@ describe("processTimelineResponse", () => {
|
|||||||
{
|
{
|
||||||
callId: "call-1",
|
callId: "call-1",
|
||||||
status: "completed",
|
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"),
|
...makeAssistantItem("projected response", "loaded-assistant"),
|
||||||
messageId: "assistant-message",
|
messageId: "assistant-message",
|
||||||
timestamp,
|
timestamp,
|
||||||
timelineCursor: { epoch: "epoch-1", seq: 500 },
|
timelineCursor: { epoch: "epoch-1", seq: 500, anchorSeq: 500 },
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
const result = processTimelineResponse({
|
const result = processTimelineResponse({
|
||||||
@@ -3100,7 +3104,7 @@ describe("processTimelineResponse", () => {
|
|||||||
id: "loaded-assistant",
|
id: "loaded-assistant",
|
||||||
text: "projected response",
|
text: "projected response",
|
||||||
messageId: "assistant-message",
|
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",
|
id: "current-200",
|
||||||
text: "current-200",
|
text: "current-200",
|
||||||
timestamp: new Date(3200),
|
timestamp: new Date(3200),
|
||||||
timelineCursor: { epoch: "epoch-1", seq: 200 },
|
timelineCursor: { epoch: "epoch-1", seq: 200, anchorSeq: 200 },
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
const existingCursor: TimelineCursor = {
|
const existingCursor: TimelineCursor = {
|
||||||
@@ -3219,7 +3223,7 @@ describe("processTimelineResponse", () => {
|
|||||||
const currentTail = [
|
const currentTail = [
|
||||||
{
|
{
|
||||||
...makeAssistantItem("newer chunk", "assistant-newer"),
|
...makeAssistantItem("newer chunk", "assistant-newer"),
|
||||||
timelineCursor: { epoch: "epoch-1", seq: 3 },
|
timelineCursor: { epoch: "epoch-1", seq: 3, anchorSeq: 3 },
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
const existingCursor: TimelineCursor = {
|
const existingCursor: TimelineCursor = {
|
||||||
@@ -3246,7 +3250,7 @@ describe("processTimelineResponse", () => {
|
|||||||
expect(result.tail[0]).toEqual(
|
expect(result.tail[0]).toEqual(
|
||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
id: "assistant-newer",
|
id: "assistant-newer",
|
||||||
timelineCursor: { epoch: "epoch-1", seq: 3 },
|
timelineCursor: { epoch: "epoch-1", seq: 3, anchorSeq: 3 },
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
expect(result.cursor).toEqual({
|
expect(result.cursor).toEqual({
|
||||||
@@ -3686,7 +3690,7 @@ describe("processAgentStreamEvent", () => {
|
|||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
kind: "assistant_message",
|
kind: "assistant_message",
|
||||||
text: "[System Error] failed",
|
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(getUserTexts(result.head)).toEqual(["live before bootstrap"]);
|
||||||
expect(result.head[0]).toMatchObject({
|
expect(result.head[0]).toMatchObject({
|
||||||
kind: "user_message",
|
kind: "user_message",
|
||||||
timelineCursor: { epoch: "epoch-1", seq: 51 },
|
timelineCursor: { epoch: "epoch-1", seq: 51, anchorSeq: 51 },
|
||||||
});
|
});
|
||||||
expect(result.cursorChanged).toBe(false);
|
expect(result.cursorChanged).toBe(false);
|
||||||
expect(result.cursor).toBeNull();
|
expect(result.cursor).toBeNull();
|
||||||
@@ -3968,7 +3972,7 @@ describe("processAgentStreamEvent", () => {
|
|||||||
clientMessageId: "client-message-1",
|
clientMessageId: "client-message-1",
|
||||||
messageId: "provider-message-1",
|
messageId: "provider-message-1",
|
||||||
text: "submitted before bootstrap",
|
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", () => {
|
describe("turn metrics", () => {
|
||||||
const metrics = [
|
const metrics = [
|
||||||
{ label: "Model", value: "opus" },
|
{ label: "Model", value: "opus" },
|
||||||
@@ -4816,4 +5093,30 @@ describe("turn metrics", () => {
|
|||||||
|
|
||||||
expect(repeated.tail).toBe(first.tail);
|
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 { AgentMetric, AgentTimelineItem } from "@getpaseo/protocol/agent-types";
|
||||||
import type { AgentStreamEventPayload } from "@getpaseo/protocol/messages";
|
import type { AgentStreamEventPayload } from "@getpaseo/protocol/messages";
|
||||||
import { selectAgentTimelineState, useSessionStore } from "@/stores/session-store";
|
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 type { TurnLivenessTransition } from "@/timeline/turn-liveness";
|
||||||
import { stampTimelineTurnMetrics } from "@/timeline/turn-metrics";
|
import { stampTimelineTurnMetrics } from "@/timeline/turn-metrics";
|
||||||
import {
|
import {
|
||||||
@@ -72,6 +78,64 @@ interface TimelineSeqRange {
|
|||||||
endSeq: number;
|
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(
|
function mergeTimelineCoverage(
|
||||||
current: TimelineCursor,
|
current: TimelineCursor,
|
||||||
added: TimelineLoadedRange,
|
added: TimelineLoadedRange,
|
||||||
@@ -152,6 +216,7 @@ export interface ProcessTimelineResponseInput {
|
|||||||
hasNewer: boolean;
|
hasNewer: boolean;
|
||||||
hasOlder: boolean;
|
hasOlder: boolean;
|
||||||
mergeWindow?: boolean;
|
mergeWindow?: boolean;
|
||||||
|
retirements?: TimelineRetirement[];
|
||||||
};
|
};
|
||||||
currentTail: StreamItem[];
|
currentTail: StreamItem[];
|
||||||
currentHead: StreamItem[];
|
currentHead: StreamItem[];
|
||||||
@@ -396,7 +461,7 @@ function mergeTimelineWindow(args: {
|
|||||||
toHydratedEvents: (units: TimelineUnit[]) => Array<{
|
toHydratedEvents: (units: TimelineUnit[]) => Array<{
|
||||||
event: AgentStreamEventPayload;
|
event: AgentStreamEventPayload;
|
||||||
timestamp: Date;
|
timestamp: Date;
|
||||||
timelineCursor: { epoch: string; seq: number };
|
timelineCursor: TimelinePosition;
|
||||||
}>;
|
}>;
|
||||||
}): TimelinePathResult {
|
}): TimelinePathResult {
|
||||||
const { timelineUnits, payload, currentTail, currentHead, currentCursor, toHydratedEvents } =
|
const { timelineUnits, payload, currentTail, currentHead, currentCursor, toHydratedEvents } =
|
||||||
@@ -760,7 +825,7 @@ function replaceLiveAssistantWithProjectedText(params: {
|
|||||||
head: StreamItem[];
|
head: StreamItem[];
|
||||||
event: AgentStreamEventPayload;
|
event: AgentStreamEventPayload;
|
||||||
timestamp: Date;
|
timestamp: Date;
|
||||||
timelineCursor: { epoch: string; seq: number };
|
timelineCursor: TimelinePosition;
|
||||||
}): StreamItem[] | null {
|
}): StreamItem[] | null {
|
||||||
const { head, event, timestamp, timelineCursor } = params;
|
const { head, event, timestamp, timelineCursor } = params;
|
||||||
if (event.type !== "timeline" || event.item.type !== "assistant_message") {
|
if (event.type !== "timeline" || event.item.type !== "assistant_message") {
|
||||||
@@ -779,7 +844,7 @@ function replaceLiveAssistantWithProjectedText(params: {
|
|||||||
...current,
|
...current,
|
||||||
text: event.item.text,
|
text: event.item.text,
|
||||||
timestamp,
|
timestamp,
|
||||||
timelineCursor,
|
...advanceTimelinePosition(current.timelineCursor, timelineCursor),
|
||||||
};
|
};
|
||||||
return next;
|
return next;
|
||||||
}
|
}
|
||||||
@@ -829,7 +894,7 @@ function reconcileOverlappingProjectedAssistant(params: {
|
|||||||
...(messageId !== undefined ? { messageId } : {}),
|
...(messageId !== undefined ? { messageId } : {}),
|
||||||
text: projectedText,
|
text: projectedText,
|
||||||
timestamp: unit.timestamp,
|
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 replaceMatch = (items: StreamItem[], index: number) => {
|
||||||
const next = [...items];
|
const next = [...items];
|
||||||
@@ -946,8 +1011,8 @@ function applyCanonicalForwardUnit(params: {
|
|||||||
unit: TimelineUnit;
|
unit: TimelineUnit;
|
||||||
epoch: string;
|
epoch: string;
|
||||||
}): { tail: StreamItem[]; head: StreamItem[]; acknowledgedClientMessageIds: string[] } {
|
}): { tail: StreamItem[]; head: StreamItem[]; acknowledgedClientMessageIds: string[] } {
|
||||||
const { event, timestamp, seqEnd } = params.unit;
|
const { event, timestamp, seq, seqEnd } = params.unit;
|
||||||
const timelineCursor = { epoch: params.epoch, seq: seqEnd };
|
const timelineCursor: TimelinePosition = { epoch: params.epoch, seq: seqEnd, anchorSeq: seq };
|
||||||
if (event.type === "timeline" && event.item.type === "user_message") {
|
if (event.type === "timeline" && event.item.type === "user_message") {
|
||||||
const applied = applyStreamEvent({
|
const applied = applyStreamEvent({
|
||||||
tail: params.tail,
|
tail: params.tail,
|
||||||
@@ -1146,10 +1211,10 @@ function applyAcceptedTimelinePage(input: {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
const olderTail = hydrateStreamState(
|
const olderTail = hydrateStreamState(
|
||||||
acceptedUnits.map(({ event, timestamp, seqEnd }) => ({
|
acceptedUnits.map(({ event, timestamp, seq, seqEnd }) => ({
|
||||||
event,
|
event,
|
||||||
timestamp,
|
timestamp,
|
||||||
timelineCursor: { epoch: payload.epoch, seq: seqEnd },
|
timelineCursor: { epoch: payload.epoch, seq: seqEnd, anchorSeq: seq },
|
||||||
})),
|
})),
|
||||||
{
|
{
|
||||||
source: "canonical",
|
source: "canonical",
|
||||||
@@ -1181,7 +1246,12 @@ function applyTimelineIncrementalPath(args: {
|
|||||||
let cursorChanged = false;
|
let cursorChanged = false;
|
||||||
const sideEffects: TimelineReducerSideEffect[] = [];
|
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 {
|
return {
|
||||||
tail: currentTail,
|
tail: currentTail,
|
||||||
head: currentHead,
|
head: currentHead,
|
||||||
@@ -1239,8 +1309,6 @@ export function processTimelineResponse(
|
|||||||
): ProcessTimelineResponseOutput {
|
): ProcessTimelineResponseOutput {
|
||||||
const {
|
const {
|
||||||
payload,
|
payload,
|
||||||
currentTail,
|
|
||||||
currentHead,
|
|
||||||
currentCursor,
|
currentCursor,
|
||||||
isInitializing,
|
isInitializing,
|
||||||
hasActiveInitDeferred,
|
hasActiveInitDeferred,
|
||||||
@@ -1254,8 +1322,8 @@ export function processTimelineResponse(
|
|||||||
if (payload.error) {
|
if (payload.error) {
|
||||||
return {
|
return {
|
||||||
commit: "apply",
|
commit: "apply",
|
||||||
tail: currentTail,
|
tail: input.currentTail,
|
||||||
head: currentHead,
|
head: input.currentHead,
|
||||||
cursor: currentCursor,
|
cursor: currentCursor,
|
||||||
cursorChanged: false,
|
cursorChanged: false,
|
||||||
older: "unchanged",
|
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
|
// Convert entries to timeline units
|
||||||
// ------------------------------------------------------------------
|
// ------------------------------------------------------------------
|
||||||
@@ -1292,12 +1367,12 @@ export function processTimelineResponse(
|
|||||||
): Array<{
|
): Array<{
|
||||||
event: AgentStreamEventPayload;
|
event: AgentStreamEventPayload;
|
||||||
timestamp: Date;
|
timestamp: Date;
|
||||||
timelineCursor: { epoch: string; seq: number };
|
timelineCursor: TimelinePosition;
|
||||||
}> =>
|
}> =>
|
||||||
units.map(({ event, timestamp, seqEnd }) => ({
|
units.map(({ event, timestamp, seq, seqEnd }) => ({
|
||||||
event,
|
event,
|
||||||
timestamp,
|
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 {
|
export interface ProcessAgentStreamEventInput {
|
||||||
event: AgentStreamEventPayload;
|
event: AgentStreamEventPayload | TimelineRewindEvent;
|
||||||
seq: number | undefined;
|
seq: number | undefined;
|
||||||
epoch: string | undefined;
|
epoch: string | undefined;
|
||||||
currentTail: StreamItem[];
|
currentTail: StreamItem[];
|
||||||
@@ -1455,7 +1530,7 @@ export interface ProcessAgentStreamEventOutput {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface AgentStreamReducerEvent {
|
export interface AgentStreamReducerEvent {
|
||||||
event: AgentStreamEventPayload;
|
event: AgentStreamEventPayload | TimelineRewindEvent;
|
||||||
seq: number | undefined;
|
seq: number | undefined;
|
||||||
epoch: string | undefined;
|
epoch: string | undefined;
|
||||||
timestamp: Date;
|
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(
|
export function processAgentStreamEvent(
|
||||||
input: ProcessAgentStreamEventInput,
|
input: ProcessAgentStreamEventInput,
|
||||||
): ProcessAgentStreamEventOutput {
|
): ProcessAgentStreamEventOutput {
|
||||||
|
const event = input.event;
|
||||||
|
if (event.type === "rewind") return processTimelineRewind({ ...input, event });
|
||||||
const {
|
const {
|
||||||
event,
|
|
||||||
seq,
|
seq,
|
||||||
epoch,
|
epoch,
|
||||||
currentTail,
|
currentTail,
|
||||||
@@ -1596,7 +1730,7 @@ export function processAgentStreamEvent(
|
|||||||
});
|
});
|
||||||
const timelineCursor =
|
const timelineCursor =
|
||||||
event.type === "timeline" && seq !== undefined && epoch !== undefined
|
event.type === "timeline" && seq !== undefined && epoch !== undefined
|
||||||
? { epoch, seq }
|
? { epoch, seq, anchorSeq: seq }
|
||||||
: undefined;
|
: undefined;
|
||||||
// ------------------------------------------------------------------
|
// ------------------------------------------------------------------
|
||||||
// Apply stream event to tail/head
|
// Apply stream event to tail/head
|
||||||
@@ -1910,6 +2044,10 @@ export function createSessionAgentStreamReducerQueue(
|
|||||||
};
|
};
|
||||||
},
|
},
|
||||||
commit: (agentId, result, events) => {
|
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 (
|
if (
|
||||||
result.changedTail ||
|
result.changedTail ||
|
||||||
result.changedHead ||
|
result.changedHead ||
|
||||||
|
|||||||
@@ -237,6 +237,13 @@ function commitProcessedTimeline(input: {
|
|||||||
const agentId = payload.agentId;
|
const agentId = payload.agentId;
|
||||||
const store = useSessionStore.getState();
|
const store = useSessionStore.getState();
|
||||||
if (result.commit !== "discard") {
|
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, {
|
store.applyAgentTimelineResponseState(serverId, agentId, {
|
||||||
items: result.tail,
|
items: result.tail,
|
||||||
head: result.head,
|
head: result.head,
|
||||||
@@ -457,8 +464,14 @@ export type ViewedTimelineOwnerPorts = Omit<
|
|||||||
| "applyCurrentTimeline"
|
| "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 {
|
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
|
* 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
|
* 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;
|
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: {
|
export function createViewedTimelineOwner(input: {
|
||||||
serverId: string;
|
serverId: string;
|
||||||
replica: TimelineReplica;
|
replica: TimelineReplica;
|
||||||
@@ -477,6 +521,7 @@ export function createViewedTimelineOwner(input: {
|
|||||||
ports: ViewedTimelineOwnerPorts;
|
ports: ViewedTimelineOwnerPorts;
|
||||||
}): ViewedTimelineOwner {
|
}): ViewedTimelineOwner {
|
||||||
const forcedTailReplacements = new Set<string>();
|
const forcedTailReplacements = new Set<string>();
|
||||||
|
const retirements = createRetirementHighWater();
|
||||||
const sync = createViewedTimelineSync({
|
const sync = createViewedTimelineSync({
|
||||||
...input.ports,
|
...input.ports,
|
||||||
fetchLatestTail: async (agentId) => {
|
fetchLatestTail: async (agentId) => {
|
||||||
@@ -517,6 +562,8 @@ export function createViewedTimelineOwner(input: {
|
|||||||
return {
|
return {
|
||||||
...sync,
|
...sync,
|
||||||
applyTimelineResponse(receivedPayload) {
|
applyTimelineResponse(receivedPayload) {
|
||||||
|
if (retirements.servedBefore(receivedPayload)) return "stale";
|
||||||
|
retirements.notePage(receivedPayload);
|
||||||
const payload = consumeForcedTimelineTailReplacement(receivedPayload, forcedTailReplacements);
|
const payload = consumeForcedTimelineTailReplacement(receivedPayload, forcedTailReplacements);
|
||||||
const accepted = applyAuthoritativeTimelineResponse({
|
const accepted = applyAuthoritativeTimelineResponse({
|
||||||
serverId: input.serverId,
|
serverId: input.serverId,
|
||||||
@@ -526,8 +573,12 @@ export function createViewedTimelineOwner(input: {
|
|||||||
drainQueuedAgentMessage: input.drainQueuedAgentMessage,
|
drainQueuedAgentMessage: input.drainQueuedAgentMessage,
|
||||||
});
|
});
|
||||||
if (accepted) input.replica.timelineUpdated(payload.agentId);
|
if (accepted) input.replica.timelineUpdated(payload.agentId);
|
||||||
|
return "applied";
|
||||||
},
|
},
|
||||||
applyStreamEvent(agentId, event) {
|
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);
|
streamQueue.enqueue(agentId, event);
|
||||||
const turnLiveness = deriveAgentStreamTurnLiveness([event]);
|
const turnLiveness = deriveAgentStreamTurnLiveness([event]);
|
||||||
if (turnLiveness.length === 0) return;
|
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", () => {
|
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({
|
const result = applyStreamEvent({
|
||||||
tail: [],
|
tail: [],
|
||||||
head: [],
|
head: [],
|
||||||
@@ -1890,7 +1890,7 @@ describe("turn lifecycle events", () => {
|
|||||||
new Date("2025-01-01T15:03:11Z"),
|
new Date("2025-01-01T15:03:11Z"),
|
||||||
{
|
{
|
||||||
source: "canonical",
|
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.messageId, "provider-owned-canonical");
|
||||||
assert.strictEqual(userMessage.text, "Analyze this");
|
assert.strictEqual(userMessage.text, "Analyze this");
|
||||||
assert.strictEqual(userMessage.timestamp.getTime(), submittedTimestamp.getTime());
|
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.images, [image]);
|
||||||
assert.deepStrictEqual(userMessage.attachments, [attachment]);
|
assert.deepStrictEqual(userMessage.attachments, [attachment]);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -266,7 +266,7 @@ function produceUserMessage(
|
|||||||
...presentation,
|
...presentation,
|
||||||
clientMessageId: incoming.clientMessageId ?? existing.clientMessageId,
|
clientMessageId: incoming.clientMessageId ?? existing.clientMessageId,
|
||||||
messageId: incoming.messageId ?? existing.messageId,
|
messageId: incoming.messageId ?? existing.messageId,
|
||||||
timelineCursor: incoming.timelineCursor ?? existing.timelineCursor,
|
...advanceTimelinePosition(existing.timelineCursor, incoming.timelineCursor),
|
||||||
});
|
});
|
||||||
if (
|
if (
|
||||||
existing.id === merged.id &&
|
existing.id === merged.id &&
|
||||||
@@ -482,7 +482,7 @@ function mergeRetainedLifecycleItem(tail: StreamItem[], retained: StreamItem): S
|
|||||||
const next = [...tail];
|
const next = [...tail];
|
||||||
next[tailIndex] = {
|
next[tailIndex] = {
|
||||||
...existing,
|
...existing,
|
||||||
timelineCursor: retained.timelineCursor,
|
...advanceTimelinePosition(existing.timelineCursor, retained.timelineCursor),
|
||||||
timestamp: retained.timestamp,
|
timestamp: retained.timestamp,
|
||||||
items: retained.items,
|
items: retained.items,
|
||||||
};
|
};
|
||||||
@@ -499,7 +499,7 @@ function mergeRetainedLifecycleItem(tail: StreamItem[], retained: StreamItem): S
|
|||||||
const next = [...tail];
|
const next = [...tail];
|
||||||
next[tailIndex] = {
|
next[tailIndex] = {
|
||||||
...existing,
|
...existing,
|
||||||
timelineCursor: retained.timelineCursor,
|
...advanceTimelinePosition(existing.timelineCursor, retained.timelineCursor),
|
||||||
status: "completed",
|
status: "completed",
|
||||||
trigger: retained.trigger ?? existing.trigger,
|
trigger: retained.trigger ?? existing.trigger,
|
||||||
preTokens: retained.preTokens ?? existing.preTokens,
|
preTokens: retained.preTokens ?? existing.preTokens,
|
||||||
@@ -519,7 +519,10 @@ function replaceTimelineIdentityItem(
|
|||||||
const existing = items[index];
|
const existing = items[index];
|
||||||
if (index < 0 || !existing || existing.kind !== "plugin") return null;
|
if (index < 0 || !existing || existing.kind !== "plugin") return null;
|
||||||
const next = [...items];
|
const next = [...items];
|
||||||
next[index] = retained;
|
next[index] = {
|
||||||
|
...retained,
|
||||||
|
...advanceTimelinePosition(existing.timelineCursor, retained.timelineCursor),
|
||||||
|
};
|
||||||
return next;
|
return next;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -610,7 +613,11 @@ function preserveReplacementHead(
|
|||||||
: `${tailAssistant.text}${liveAssistant.text}`;
|
: `${tailAssistant.text}${liveAssistant.text}`;
|
||||||
const head = [
|
const head = [
|
||||||
...unreconciledHead.slice(0, liveAssistantIndex),
|
...unreconciledHead.slice(0, liveAssistantIndex),
|
||||||
{ ...liveAssistant, text },
|
{
|
||||||
|
...liveAssistant,
|
||||||
|
text,
|
||||||
|
...advanceTimelinePosition(tailAssistant.timelineCursor, liveAssistant.timelineCursor),
|
||||||
|
},
|
||||||
...unreconciledHead.slice(liveAssistantIndex + 1),
|
...unreconciledHead.slice(liveAssistantIndex + 1),
|
||||||
];
|
];
|
||||||
return {
|
return {
|
||||||
@@ -625,7 +632,13 @@ function preserveReplacementHead(
|
|||||||
|
|
||||||
const head = [
|
const head = [
|
||||||
...unreconciledHead.slice(0, liveAssistantIndex),
|
...unreconciledHead.slice(0, liveAssistantIndex),
|
||||||
{ ...liveAssistant, text: tailAssistant.text },
|
{
|
||||||
|
...liveAssistant,
|
||||||
|
text: tailAssistant.text,
|
||||||
|
...(liveAssistant.timelineCursor
|
||||||
|
? advanceTimelinePosition(tailAssistant.timelineCursor, liveAssistant.timelineCursor)
|
||||||
|
: {}),
|
||||||
|
},
|
||||||
...unreconciledHead.slice(liveAssistantIndex + 1),
|
...unreconciledHead.slice(liveAssistantIndex + 1),
|
||||||
];
|
];
|
||||||
return {
|
return {
|
||||||
@@ -724,7 +737,27 @@ export interface AssistantMessageItem {
|
|||||||
|
|
||||||
export interface TimelinePosition {
|
export interface TimelinePosition {
|
||||||
epoch: string;
|
epoch: string;
|
||||||
|
/** The latest seq that changed this row. */
|
||||||
seq: number;
|
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";
|
export type ThoughtStatus = "loading" | "ready";
|
||||||
@@ -983,7 +1016,7 @@ function appendAssistantMessage(
|
|||||||
...last,
|
...last,
|
||||||
text: `${last.text}${chunk}`,
|
text: `${last.text}${chunk}`,
|
||||||
timestamp,
|
timestamp,
|
||||||
...(timelineCursor ? { timelineCursor } : {}),
|
...advanceTimelinePosition(last.timelineCursor, timelineCursor),
|
||||||
};
|
};
|
||||||
return [...state.slice(0, -1), updated];
|
return [...state.slice(0, -1), updated];
|
||||||
}
|
}
|
||||||
@@ -1001,7 +1034,7 @@ function appendAssistantMessage(
|
|||||||
...secondLast,
|
...secondLast,
|
||||||
text: `${secondLast.text}${chunk}`,
|
text: `${secondLast.text}${chunk}`,
|
||||||
timestamp,
|
timestamp,
|
||||||
...(timelineCursor ? { timelineCursor } : {}),
|
...advanceTimelinePosition(secondLast.timelineCursor, timelineCursor),
|
||||||
};
|
};
|
||||||
return [...state.slice(0, -2), updated, last];
|
return [...state.slice(0, -2), updated, last];
|
||||||
}
|
}
|
||||||
@@ -1039,7 +1072,7 @@ function appendThought(
|
|||||||
if (last && last.kind === "thought" && last.turnId === turnId) {
|
if (last && last.kind === "thought" && last.turnId === turnId) {
|
||||||
const updated: ThoughtItem = {
|
const updated: ThoughtItem = {
|
||||||
...last,
|
...last,
|
||||||
...(timelineCursor ? { timelineCursor } : {}),
|
...advanceTimelinePosition(last.timelineCursor, timelineCursor),
|
||||||
text: `${last.text}${chunk}`,
|
text: `${last.text}${chunk}`,
|
||||||
timestamp,
|
timestamp,
|
||||||
status: "loading",
|
status: "loading",
|
||||||
@@ -1219,7 +1252,7 @@ export function mergeAgentToolCallItem(
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
...existing,
|
...existing,
|
||||||
...(timelineCursor ? { timelineCursor } : {}),
|
...advanceTimelinePosition(existing.timelineCursor, timelineCursor),
|
||||||
timestamp,
|
timestamp,
|
||||||
payload: {
|
payload: {
|
||||||
source: "agent",
|
source: "agent",
|
||||||
@@ -1325,7 +1358,11 @@ function appendPluginTimelineItem(
|
|||||||
const existing = state[existingIndex];
|
const existing = state[existingIndex];
|
||||||
if (!existing || existing.kind !== "plugin") return state;
|
if (!existing || existing.kind !== "plugin") return state;
|
||||||
const next = [...state];
|
const next = [...state];
|
||||||
next[existingIndex] = { ...nextItem, id: existing.id };
|
next[existingIndex] = {
|
||||||
|
...nextItem,
|
||||||
|
id: existing.id,
|
||||||
|
...advanceTimelinePosition(existing.timelineCursor, timelineCursor),
|
||||||
|
};
|
||||||
return next;
|
return next;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1356,7 +1393,7 @@ function appendTodoList(
|
|||||||
const next = [...state];
|
const next = [...state];
|
||||||
next[previousIndex] = {
|
next[previousIndex] = {
|
||||||
...previous,
|
...previous,
|
||||||
...(timelineCursor ? { timelineCursor } : {}),
|
...advanceTimelinePosition(previous.timelineCursor, timelineCursor),
|
||||||
items: normalizedItems,
|
items: normalizedItems,
|
||||||
timestamp,
|
timestamp,
|
||||||
};
|
};
|
||||||
@@ -1375,7 +1412,7 @@ function appendTodoList(
|
|||||||
const next = [...state];
|
const next = [...state];
|
||||||
next[next.length - 1] = {
|
next[next.length - 1] = {
|
||||||
...lastItem,
|
...lastItem,
|
||||||
...(timelineCursor ? { timelineCursor } : {}),
|
...advanceTimelinePosition(lastItem.timelineCursor, timelineCursor),
|
||||||
items: normalizedItems,
|
items: normalizedItems,
|
||||||
activity: { type: "created", count: normalizedItems.length },
|
activity: { type: "created", count: normalizedItems.length },
|
||||||
timestamp,
|
timestamp,
|
||||||
@@ -1520,7 +1557,7 @@ function reduceTimelineCompaction(
|
|||||||
if (loadingIdx >= 0 && existing && existing.kind === "compaction") {
|
if (loadingIdx >= 0 && existing && existing.kind === "compaction") {
|
||||||
const updated: CompactionItem = {
|
const updated: CompactionItem = {
|
||||||
...existing,
|
...existing,
|
||||||
...(timelineCursor ? { timelineCursor } : {}),
|
...advanceTimelinePosition(existing.timelineCursor, timelineCursor),
|
||||||
status: "completed",
|
status: "completed",
|
||||||
trigger: item.trigger ?? existing.trigger,
|
trigger: item.trigger ?? existing.trigger,
|
||||||
preTokens: item.preTokens ?? existing.preTokens,
|
preTokens: item.preTokens ?? existing.preTokens,
|
||||||
@@ -1645,7 +1682,10 @@ export function reduceStreamUpdate(
|
|||||||
),
|
),
|
||||||
event,
|
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":
|
case "turn_completed":
|
||||||
return stampCompletedTurnMetrics(finalizeActiveThoughts(state), event.metrics, event.turnId);
|
return stampCompletedTurnMetrics(finalizeActiveThoughts(state), event.metrics, event.turnId);
|
||||||
|
|||||||
@@ -246,8 +246,7 @@ describe("global routes", () => {
|
|||||||
describe("host settings section slugs", () => {
|
describe("host settings section slugs", () => {
|
||||||
it("keeps current host settings sections", () => {
|
it("keeps current host settings sections", () => {
|
||||||
expect(normalizeHostSectionSlug("connections")).toBe("connections");
|
expect(normalizeHostSectionSlug("connections")).toBe("connections");
|
||||||
expect(normalizeHostSectionSlug("devices")).toBe("devices");
|
expect(normalizeHostSectionSlug("pair-device")).toBe("pair-device");
|
||||||
expect(normalizeHostSectionSlug("pair-device")).toBe("devices");
|
|
||||||
expect(normalizeHostSectionSlug("agents")).toBe("agents");
|
expect(normalizeHostSectionSlug("agents")).toBe("agents");
|
||||||
expect(normalizeHostSectionSlug("metadata")).toBe("metadata");
|
expect(normalizeHostSectionSlug("metadata")).toBe("metadata");
|
||||||
expect(normalizeHostSectionSlug("workspaces")).toBe("workspaces");
|
expect(normalizeHostSectionSlug("workspaces")).toBe("workspaces");
|
||||||
|
|||||||
@@ -515,7 +515,7 @@ export function isSettingsSectionSlug(value: string): value is SettingsSectionSl
|
|||||||
export const HOST_SECTION_SLUGS = [
|
export const HOST_SECTION_SLUGS = [
|
||||||
"projects",
|
"projects",
|
||||||
"connections",
|
"connections",
|
||||||
"devices",
|
"pair-device",
|
||||||
"agents",
|
"agents",
|
||||||
"agent-profiles",
|
"agent-profiles",
|
||||||
"metadata",
|
"metadata",
|
||||||
@@ -531,7 +531,6 @@ export const HOST_SECTION_SLUGS = [
|
|||||||
export type HostSectionSlug = (typeof HOST_SECTION_SLUGS)[number];
|
export type HostSectionSlug = (typeof HOST_SECTION_SLUGS)[number];
|
||||||
|
|
||||||
const LEGACY_HOST_SECTION_SLUGS: Record<string, HostSectionSlug> = {
|
const LEGACY_HOST_SECTION_SLUGS: Record<string, HostSectionSlug> = {
|
||||||
"pair-device": "devices",
|
|
||||||
orchestration: "agents",
|
orchestration: "agents",
|
||||||
daemon: "host",
|
daemon: "host",
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -47,5 +47,8 @@
|
|||||||
"typescript": "^5.2.2",
|
"typescript": "^5.2.2",
|
||||||
"vitest": "^4.1.6",
|
"vitest": "^4.1.6",
|
||||||
"zx": "^8.8.5"
|
"zx": "^8.8.5"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=22.16.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -146,6 +146,10 @@ export async function runAttachCommand(
|
|||||||
const unsubscribe = client.subscribeAgentTimeline(resolvedId, (message) => {
|
const unsubscribe = client.subscribeAgentTimeline(resolvedId, (message) => {
|
||||||
if (message.type === "agent.timeline.replacement") {
|
if (message.type === "agent.timeline.replacement") {
|
||||||
console.log("\n[Timeline replaced; earlier output is no longer current]");
|
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") {
|
} else if (message.type === "agent.timeline.subscription_restored") {
|
||||||
console.log("\n[Reconnected; live output resumed. Events may have been missed.]");
|
console.log("\n[Reconnected; live output resumed. Events may have been missed.]");
|
||||||
} else if (message.type === "agent.timeline.error") {
|
} else if (message.type === "agent.timeline.error") {
|
||||||
|
|||||||
@@ -408,7 +408,6 @@ async function runFollowMode({
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.warn("Warning: failed to fetch existing timeline", error);
|
console.warn("Warning: failed to fetch existing timeline", error);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Apply filter to existing items
|
// Apply filter to existing items
|
||||||
if (options.filter) {
|
if (options.filter) {
|
||||||
existingItems = existingItems.filter((item) => matchesFilter(item, 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]");
|
notice("\n[Timeline replaced; earlier output is no longer current]");
|
||||||
return;
|
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") {
|
if (message.type === "agent.timeline.error") {
|
||||||
writer.end();
|
writer.end();
|
||||||
|
|||||||
@@ -6,11 +6,7 @@ import {
|
|||||||
isSameDaemonInstance,
|
isSameDaemonInstance,
|
||||||
DaemonInstanceError,
|
DaemonInstanceError,
|
||||||
} from "@getpaseo/server/daemon-control";
|
} from "@getpaseo/server/daemon-control";
|
||||||
import {
|
import { readPersistedConfig, resolveConfigFromPersisted } from "@getpaseo/server/configuration";
|
||||||
readPersistedConfig,
|
|
||||||
resolveConfigFromPersisted,
|
|
||||||
getMainListenAddress,
|
|
||||||
} from "@getpaseo/server/configuration";
|
|
||||||
import { connectToDaemon, buildDaemonConnectionCommandError } from "../../utils/client.js";
|
import { connectToDaemon, buildDaemonConnectionCommandError } from "../../utils/client.js";
|
||||||
import { withOutput, toCommandError, type CommandOptions } from "../../output/index.js";
|
import { withOutput, toCommandError, type CommandOptions } from "../../output/index.js";
|
||||||
import { addJsonAndDaemonHostOptions } from "../../utils/command-options.js";
|
import { addJsonAndDaemonHostOptions } from "../../utils/command-options.js";
|
||||||
@@ -107,8 +103,6 @@ async function probeDaemonStatus(
|
|||||||
daemonNode: status.nodePath,
|
daemonNode: status.nodePath,
|
||||||
providers: status.providers,
|
providers: status.providers,
|
||||||
relay: status.relay,
|
relay: status.relay,
|
||||||
tailscale: status.tailscale,
|
|
||||||
extraListeners: status.extraListeners,
|
|
||||||
...(status.terminalsUnavailable ? { terminals: status.terminalsUnavailable } : {}),
|
...(status.terminalsUnavailable ? { terminals: status.terminalsUnavailable } : {}),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -133,7 +127,7 @@ function localStatus(home: string, instance: Awaited<ReturnType<typeof readDaemo
|
|||||||
listen: instance?.listen ?? null,
|
listen: instance?.listen ?? null,
|
||||||
serverId: instance?.serverId ?? undefined,
|
serverId: instance?.serverId ?? undefined,
|
||||||
hostname: instance?.hostname ?? null,
|
hostname: instance?.hostname ?? null,
|
||||||
configuredListen: getMainListenAddress(config.listen),
|
configuredListen: config.listen,
|
||||||
localDaemon,
|
localDaemon,
|
||||||
desktopManaged: instance?.desktopManaged === true,
|
desktopManaged: instance?.desktopManaged === true,
|
||||||
logPath: daemonLogPath(home),
|
logPath: daemonLogPath(home),
|
||||||
|
|||||||
@@ -210,7 +210,12 @@ try {
|
|||||||
console.log("Foreground SIGINT reached the supervisor. The worker and ACP processes exited.");
|
console.log("Foreground SIGINT reached the supervisor. The worker and ACP processes exited.");
|
||||||
|
|
||||||
daemon = await startSupervisor();
|
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?.status, "idle");
|
||||||
assert.equal(restoredIdle?.requiresAttention, false);
|
assert.equal(restoredIdle?.requiresAttention, false);
|
||||||
await waitFor(async () => {
|
await waitFor(async () => {
|
||||||
|
|||||||
@@ -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 () => {
|
test("local listeners create no demand before or after reconnect", async () => {
|
||||||
const h = connection();
|
const h = connection();
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -141,6 +141,7 @@ export const DEFAULT_CLIENT_CAPABILITIES = {
|
|||||||
[CLIENT_CAPS.compactProviderSnapshots]: true,
|
[CLIENT_CAPS.compactProviderSnapshots]: true,
|
||||||
[CLIENT_CAPS.providerSnapshotReferences]: true,
|
[CLIENT_CAPS.providerSnapshotReferences]: true,
|
||||||
[CLIENT_CAPS.timelineReplacementInvalidation]: true,
|
[CLIENT_CAPS.timelineReplacementInvalidation]: true,
|
||||||
|
[CLIENT_CAPS.timelineRewindOperations]: true,
|
||||||
[CLIENT_CAPS.timelineNotifications]: true,
|
[CLIENT_CAPS.timelineNotifications]: true,
|
||||||
[CLIENT_CAPS.pluginTimelineItems]: true,
|
[CLIENT_CAPS.pluginTimelineItems]: true,
|
||||||
[CLIENT_CAPS.workspaceSetupBlocked]: true,
|
[CLIENT_CAPS.workspaceSetupBlocked]: true,
|
||||||
|
|||||||
@@ -246,7 +246,9 @@ export class LegacySubscriptions {
|
|||||||
);
|
);
|
||||||
case "agent.timeline.set_subscription.request":
|
case "agent.timeline.set_subscription.request":
|
||||||
return (
|
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)
|
(query.agentIds as string[]).includes(message.payload.agentId)
|
||||||
);
|
);
|
||||||
case "session.events.set_subscription.request":
|
case "session.events.set_subscription.request":
|
||||||
|
|||||||
@@ -1132,6 +1132,7 @@ test("advertises client capabilities in hello", async () => {
|
|||||||
all_providers: true,
|
all_providers: true,
|
||||||
selective_agent_timeline: true,
|
selective_agent_timeline: true,
|
||||||
timeline_replacement_invalidation: true,
|
timeline_replacement_invalidation: true,
|
||||||
|
timeline_rewind_operations: true,
|
||||||
provider_snapshot_references: true,
|
provider_snapshot_references: true,
|
||||||
explicit_event_subscriptions: true,
|
explicit_event_subscriptions: true,
|
||||||
owned_subscriptions: true,
|
owned_subscriptions: true,
|
||||||
|
|||||||
@@ -123,7 +123,6 @@ import type {
|
|||||||
ProviderInstallationCheckUpdatesResponseMessage,
|
ProviderInstallationCheckUpdatesResponseMessage,
|
||||||
UsageReportEntry,
|
UsageReportEntry,
|
||||||
DaemonGetStatusResponse,
|
DaemonGetStatusResponse,
|
||||||
DaemonTailscaleSetResponse,
|
|
||||||
DaemonGetPairingOfferResponse,
|
DaemonGetPairingOfferResponse,
|
||||||
DaemonConfigReloadResponse,
|
DaemonConfigReloadResponse,
|
||||||
DiagnosticsResponse,
|
DiagnosticsResponse,
|
||||||
@@ -843,7 +842,6 @@ export interface ShutdownServerOptions {
|
|||||||
keepTerminals?: boolean;
|
keepTerminals?: boolean;
|
||||||
}
|
}
|
||||||
export interface DaemonStatusOptions {
|
export interface DaemonStatusOptions {
|
||||||
includeProviders?: boolean;
|
|
||||||
requestId?: string;
|
requestId?: string;
|
||||||
timeout?: number;
|
timeout?: number;
|
||||||
}
|
}
|
||||||
@@ -6126,17 +6124,6 @@ export class DaemonClient {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async setTailscaleEnabled(
|
|
||||||
enabled: boolean,
|
|
||||||
confirmed = false,
|
|
||||||
): Promise<DaemonTailscaleSetResponse["payload"]> {
|
|
||||||
return this.sendCorrelatedSessionRequest({
|
|
||||||
message: { type: "daemon.tailscale.set.request", enabled, confirmed },
|
|
||||||
responseType: "daemon.tailscale.set.response",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The Tailscale disconnect flag describes the connection used for this request. */
|
|
||||||
async getDaemonStatus(options?: DaemonStatusOptions): Promise<DaemonStatusPayload> {
|
async getDaemonStatus(options?: DaemonStatusOptions): Promise<DaemonStatusPayload> {
|
||||||
if (!this.lastServerInfoMessage) throw new DaemonConnectionError("Transport not connected");
|
if (!this.lastServerInfoMessage) throw new DaemonConnectionError("Transport not connected");
|
||||||
if (this.lastServerInfoMessage?.features?.daemonStatusRpc !== true) {
|
if (this.lastServerInfoMessage?.features?.daemonStatusRpc !== true) {
|
||||||
@@ -6146,7 +6133,6 @@ export class DaemonClient {
|
|||||||
requestId: options?.requestId,
|
requestId: options?.requestId,
|
||||||
message: {
|
message: {
|
||||||
type: "daemon.get_status.request",
|
type: "daemon.get_status.request",
|
||||||
includeProviders: options?.includeProviders,
|
|
||||||
},
|
},
|
||||||
responseType: "daemon.get_status.response",
|
responseType: "daemon.get_status.response",
|
||||||
timeout: options?.timeout,
|
timeout: options?.timeout,
|
||||||
|
|||||||
@@ -346,6 +346,14 @@ export type PaseoAgentTimelineEvent =
|
|||||||
agentId: string;
|
agentId: string;
|
||||||
event: { type: "replacement"; epoch: 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;
|
agentId: string;
|
||||||
subscriptionId: string;
|
subscriptionId: string;
|
||||||
@@ -367,7 +375,9 @@ export interface PaseoAgentTimelineHandle {
|
|||||||
* Delivers live events only. After reconnect, subscription_restored precedes
|
* Delivers live events only. After reconnect, subscription_restored precedes
|
||||||
* subsequent updates. History may have been missed; use refetch() to request
|
* subsequent updates. History may have been missed; use refetch() to request
|
||||||
* the range you need. No history is fetched automatically. A replacement event
|
* 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
|
* Await the returned unsubscribe function's `ready` promise before starting
|
||||||
* work that must be observed. It rejects if establishment fails.
|
* work that must be observed. It rejects if establishment fails.
|
||||||
*/
|
*/
|
||||||
@@ -1047,6 +1057,16 @@ function createAgentHandleFactory(
|
|||||||
agentId: id,
|
agentId: id,
|
||||||
event: { type: "replacement", epoch: message.payload.epoch },
|
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<
|
type TimelineUpdate = Extract<
|
||||||
SessionOutboundMessage,
|
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. */
|
/** Local SDK lifecycle messages; these are not additional wire RPCs. */
|
||||||
@@ -59,7 +59,11 @@ export function subscribeTimeline(
|
|||||||
});
|
});
|
||||||
},
|
},
|
||||||
update: (message) => {
|
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);
|
notify(message);
|
||||||
},
|
},
|
||||||
error: fail,
|
error: fail,
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ const SETTINGS_DESTINATIONS = [
|
|||||||
"Overview",
|
"Overview",
|
||||||
"Projects",
|
"Projects",
|
||||||
"Connections",
|
"Connections",
|
||||||
"Devices",
|
"Pair device",
|
||||||
"Agents",
|
"Agents",
|
||||||
"Metadata",
|
"Metadata",
|
||||||
"Workspaces",
|
"Workspaces",
|
||||||
|
|||||||
@@ -377,6 +377,11 @@ export type ProviderInput =
|
|||||||
sessionId: string;
|
sessionId: string;
|
||||||
changes: ProviderConfigChanges;
|
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";
|
type: "session.revert";
|
||||||
requestId: string;
|
requestId: string;
|
||||||
|
|||||||
@@ -39,6 +39,9 @@ export const CLIENT_CAPS = {
|
|||||||
// COMPAT(timelineReplacementInvalidation): added in v0.5.0, remove legacy
|
// COMPAT(timelineReplacementInvalidation): added in v0.5.0, remove legacy
|
||||||
// reconstructed timeline replay after 2027-02-21 once the client floor supports invalidation.
|
// reconstructed timeline replay after 2027-02-21 once the client floor supports invalidation.
|
||||||
timelineReplacementInvalidation: "timeline_replacement_invalidation",
|
timelineReplacementInvalidation: "timeline_replacement_invalidation",
|
||||||
|
// COMPAT(timelineRewindOperations): added in v0.14.1, remove after 2027-05-10 once the client
|
||||||
|
// floor applies rewinds. Clients without it see a rewound history under a derived epoch.
|
||||||
|
timelineRewindOperations: "timeline_rewind_operations",
|
||||||
// COMPAT(timelineNotifications): added in v0.7.2. The daemon omits notification
|
// COMPAT(timelineNotifications): added in v0.7.2. The daemon omits notification
|
||||||
// timeline items for older clients whose strict timeline union rejects them.
|
// timeline items for older clients whose strict timeline union rejects them.
|
||||||
// Remove after 2027-03-03 once the supported client floor is >= v0.7.2.
|
// Remove after 2027-03-03 once the supported client floor is >= v0.7.2.
|
||||||
|
|||||||
@@ -857,6 +857,7 @@ export const AgentStreamEventPayloadSchema = z.discriminatedUnion("type", [
|
|||||||
provider: AgentProviderSchema,
|
provider: AgentProviderSchema,
|
||||||
item: AgentTimelineItemPayloadSchema,
|
item: AgentTimelineItemPayloadSchema,
|
||||||
turnId: z.string().optional(),
|
turnId: z.string().optional(),
|
||||||
|
turnMetrics: z.array(AgentMetricSchema).optional(),
|
||||||
}),
|
}),
|
||||||
z.object({
|
z.object({
|
||||||
type: z.literal("permission_requested"),
|
type: z.literal("permission_requested"),
|
||||||
@@ -1552,17 +1553,9 @@ export const WaitForFinishRequestSchema = z.object({
|
|||||||
timeoutMs: z.number().int().positive().optional(),
|
timeoutMs: z.number().int().positive().optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
export const DaemonTailscaleSetRequestSchema = z.object({
|
|
||||||
type: z.literal("daemon.tailscale.set.request"),
|
|
||||||
requestId: z.string(),
|
|
||||||
enabled: z.boolean(),
|
|
||||||
confirmed: z.boolean().optional(),
|
|
||||||
});
|
|
||||||
|
|
||||||
export const DaemonGetStatusRequestSchema = z.object({
|
export const DaemonGetStatusRequestSchema = z.object({
|
||||||
type: z.literal("daemon.get_status.request"),
|
type: z.literal("daemon.get_status.request"),
|
||||||
requestId: z.string(),
|
requestId: z.string(),
|
||||||
includeProviders: z.boolean().optional(),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
export const DaemonGetPairingOfferRequestSchema = z.object({
|
export const DaemonGetPairingOfferRequestSchema = z.object({
|
||||||
@@ -3630,7 +3623,6 @@ export const SessionInboundMessageSchema = z.discriminatedUnion("type", [
|
|||||||
SendAgentMessageRequestSchema,
|
SendAgentMessageRequestSchema,
|
||||||
WaitForFinishRequestSchema,
|
WaitForFinishRequestSchema,
|
||||||
DaemonGetStatusRequestSchema,
|
DaemonGetStatusRequestSchema,
|
||||||
DaemonTailscaleSetRequestSchema,
|
|
||||||
DaemonGetPairingOfferRequestSchema,
|
DaemonGetPairingOfferRequestSchema,
|
||||||
DaemonConfigReloadRequestSchema,
|
DaemonConfigReloadRequestSchema,
|
||||||
HubManagementDaemonConnectRequestSchema,
|
HubManagementDaemonConnectRequestSchema,
|
||||||
@@ -4055,7 +4047,6 @@ export const ServerInfoStatusPayloadSchema = z
|
|||||||
forgeSearch: z.boolean().optional(),
|
forgeSearch: z.boolean().optional(),
|
||||||
// COMPAT(daemonStatusRpc): added in v0.1.76, remove gate after 2026-11-18.
|
// COMPAT(daemonStatusRpc): added in v0.1.76, remove gate after 2026-11-18.
|
||||||
daemonStatusRpc: z.boolean().optional(),
|
daemonStatusRpc: z.boolean().optional(),
|
||||||
tailscale: z.boolean().optional(),
|
|
||||||
// COMPAT(daemonConfigReload): added in v0.4.0, remove gate after 2027-02-14.
|
// COMPAT(daemonConfigReload): added in v0.4.0, remove gate after 2027-02-14.
|
||||||
daemonConfigReload: z.boolean().optional(),
|
daemonConfigReload: z.boolean().optional(),
|
||||||
// COMPAT(speechSettings): added in v0.12.0, remove gate after 2027-04-18.
|
// COMPAT(speechSettings): added in v0.12.0, remove gate after 2027-04-18.
|
||||||
@@ -4102,6 +4093,9 @@ export const ServerInfoStatusPayloadSchema = z
|
|||||||
"terminal-grapheme-widths": z.boolean().optional(),
|
"terminal-grapheme-widths": z.boolean().optional(),
|
||||||
// COMPAT(rewind): added in v0.1.X, drop the gate when floor >= v0.1.X.
|
// COMPAT(rewind): added in v0.1.X, drop the gate when floor >= v0.1.X.
|
||||||
rewind: z.boolean().optional(),
|
rewind: z.boolean().optional(),
|
||||||
|
// COMPAT(timelineRewindOperations): added in v0.14.1, remove gate after 2027-05-10.
|
||||||
|
// A conversation rewind arrives as `agent.timeline.rewind`, not a replacement.
|
||||||
|
timelineRewindOperations: z.boolean().optional(),
|
||||||
// COMPAT(agentTimelinePromptIndex): added in v0.2.X, drop the gate when floor >= v0.2.X.
|
// COMPAT(agentTimelinePromptIndex): added in v0.2.X, drop the gate when floor >= v0.2.X.
|
||||||
agentTimelinePromptIndex: z.boolean().optional(),
|
agentTimelinePromptIndex: z.boolean().optional(),
|
||||||
// COMPAT(agentHistorySearch): added in v0.3.0, remove gate after 2027-02-07.
|
// COMPAT(agentHistorySearch): added in v0.3.0, remove gate after 2027-02-07.
|
||||||
@@ -4305,6 +4299,8 @@ export const AgentResumedStatusPayloadSchema = z
|
|||||||
export const AgentRefreshedStatusPayloadSchema = z
|
export const AgentRefreshedStatusPayloadSchema = z
|
||||||
.object({
|
.object({
|
||||||
status: z.literal("agent_refreshed"),
|
status: z.literal("agent_refreshed"),
|
||||||
|
/** The provider's history differs from the kept history, which Reload agent did not change. */
|
||||||
|
historyDiverged: z.boolean().optional(),
|
||||||
})
|
})
|
||||||
.extend(AgentStatusWithTimelineSchema.shape);
|
.extend(AgentStatusWithTimelineSchema.shape);
|
||||||
|
|
||||||
@@ -5165,6 +5161,12 @@ export const AgentTimelineEntryPayloadSchema = z.object({
|
|||||||
turnMetrics: z.array(AgentMetricSchema).optional(),
|
turnMetrics: z.array(AgentMetricSchema).optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/** Active rows anchored in `[retireFromSeq, seq)` left the conversation. `seq` is the retirement's own. */
|
||||||
|
export const AgentTimelineRetirementSchema = z.object({
|
||||||
|
seq: z.number().int().nonnegative(),
|
||||||
|
retireFromSeq: z.number().int().nonnegative(),
|
||||||
|
});
|
||||||
|
|
||||||
export const FetchAgentTimelineResponseMessageSchema = z.object({
|
export const FetchAgentTimelineResponseMessageSchema = z.object({
|
||||||
type: z.literal("fetch_agent_timeline_response"),
|
type: z.literal("fetch_agent_timeline_response"),
|
||||||
payload: z.object({
|
payload: z.object({
|
||||||
@@ -5188,6 +5190,9 @@ export const FetchAgentTimelineResponseMessageSchema = z.object({
|
|||||||
hasNewer: z.boolean(),
|
hasNewer: z.boolean(),
|
||||||
mergeWindow: z.boolean().optional(),
|
mergeWindow: z.boolean().optional(),
|
||||||
entries: z.array(AgentTimelineEntryPayloadSchema),
|
entries: z.array(AgentTimelineEntryPayloadSchema),
|
||||||
|
// COMPAT(timelineRewindOperations): added in v0.14.1. Retirements whose seq lies in the page's
|
||||||
|
// span; apply them before the entries. Sent only to clients with the capability.
|
||||||
|
retirements: z.array(AgentTimelineRetirementSchema).optional(),
|
||||||
error: z.string().nullable(),
|
error: z.string().nullable(),
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
@@ -5201,6 +5206,18 @@ export const AgentTimelineReplacementMessageSchema = z.object({
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/** A conversation rewind retired active rows. Apply it when `seq` follows the loaded end. */
|
||||||
|
export const AgentTimelineRewindMessageSchema = z.object({
|
||||||
|
type: z.literal("agent.timeline.rewind"),
|
||||||
|
payload: z.object({
|
||||||
|
subscriptionId: z.string().optional(),
|
||||||
|
agentId: z.string(),
|
||||||
|
epoch: z.string(),
|
||||||
|
seq: z.number().int().nonnegative(),
|
||||||
|
retireFromSeq: z.number().int().nonnegative(),
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
export const AgentTimelineSearchResponseMessageSchema = z.object({
|
export const AgentTimelineSearchResponseMessageSchema = z.object({
|
||||||
type: z.literal("agent.timeline.search.response"),
|
type: z.literal("agent.timeline.search.response"),
|
||||||
payload: z.object({
|
payload: z.object({
|
||||||
@@ -5587,32 +5604,6 @@ export const GetDaemonConfigResponseMessageSchema = z.object({
|
|||||||
.passthrough(),
|
.passthrough(),
|
||||||
});
|
});
|
||||||
|
|
||||||
const TailscaleStatusSchema = z.object({
|
|
||||||
ip: z.string().nullable(),
|
|
||||||
address: z.string().nullable(),
|
|
||||||
state: z.enum(["unavailable", "off", "waiting", "on"]),
|
|
||||||
lockedBy: z.enum(["main", "launch"]).optional(),
|
|
||||||
// COMPAT(tailscale): keep lockedBy "main" for older clients when the main listener is a socket.
|
|
||||||
mainIsSocket: z.literal(true).optional(),
|
|
||||||
// Whether turning off Tailscale would disconnect the source of this request.
|
|
||||||
disconnectsCurrentConnection: z.boolean().optional(),
|
|
||||||
});
|
|
||||||
|
|
||||||
const ExtraListenerStatusSchema = z.object({
|
|
||||||
address: z.string(),
|
|
||||||
state: z.enum(["waiting", "listening"]),
|
|
||||||
});
|
|
||||||
|
|
||||||
export const DaemonTailscaleSetResponseSchema = z.object({
|
|
||||||
type: z.literal("daemon.tailscale.set.response"),
|
|
||||||
payload: z.object({
|
|
||||||
requestId: z.string(),
|
|
||||||
confirmationRequired: z.boolean(),
|
|
||||||
tailscale: TailscaleStatusSchema,
|
|
||||||
extraListeners: z.array(ExtraListenerStatusSchema),
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
export const DaemonGetStatusResponseSchema = z.object({
|
export const DaemonGetStatusResponseSchema = z.object({
|
||||||
type: z.literal("daemon.get_status.response"),
|
type: z.literal("daemon.get_status.response"),
|
||||||
payload: z
|
payload: z
|
||||||
@@ -5624,8 +5615,6 @@ export const DaemonGetStatusResponseSchema = z.object({
|
|||||||
nodePath: z.string(),
|
nodePath: z.string(),
|
||||||
startedAt: z.string().nullable().optional(),
|
startedAt: z.string().nullable().optional(),
|
||||||
listen: z.string().nullable(),
|
listen: z.string().nullable(),
|
||||||
tailscale: TailscaleStatusSchema.optional(),
|
|
||||||
extraListeners: z.array(ExtraListenerStatusSchema).optional(),
|
|
||||||
relay: z
|
relay: z
|
||||||
.object({
|
.object({
|
||||||
enabled: z.boolean(),
|
enabled: z.boolean(),
|
||||||
@@ -7817,6 +7806,7 @@ export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [
|
|||||||
FetchAgentResponseMessageSchema,
|
FetchAgentResponseMessageSchema,
|
||||||
FetchAgentTimelineResponseMessageSchema,
|
FetchAgentTimelineResponseMessageSchema,
|
||||||
AgentTimelineReplacementMessageSchema,
|
AgentTimelineReplacementMessageSchema,
|
||||||
|
AgentTimelineRewindMessageSchema,
|
||||||
AgentTimelineSearchResponseMessageSchema,
|
AgentTimelineSearchResponseMessageSchema,
|
||||||
AgentTimelineListPromptsResponseMessageSchema,
|
AgentTimelineListPromptsResponseMessageSchema,
|
||||||
ProviderSubagentListResponseMessageSchema,
|
ProviderSubagentListResponseMessageSchema,
|
||||||
@@ -7840,7 +7830,6 @@ export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [
|
|||||||
SendAgentMessageResponseMessageSchema,
|
SendAgentMessageResponseMessageSchema,
|
||||||
SetVoiceModeResponseMessageSchema,
|
SetVoiceModeResponseMessageSchema,
|
||||||
DaemonGetStatusResponseSchema,
|
DaemonGetStatusResponseSchema,
|
||||||
DaemonTailscaleSetResponseSchema,
|
|
||||||
DaemonGetPairingOfferResponseSchema,
|
DaemonGetPairingOfferResponseSchema,
|
||||||
DaemonConfigReloadResponseSchema,
|
DaemonConfigReloadResponseSchema,
|
||||||
HubManagementDaemonConnectResponseSchema,
|
HubManagementDaemonConnectResponseSchema,
|
||||||
@@ -8522,6 +8511,7 @@ export const WSHelloMessageSchema = z.object({
|
|||||||
[CLIENT_CAPS.compactProviderSnapshots]: z.boolean().optional(),
|
[CLIENT_CAPS.compactProviderSnapshots]: z.boolean().optional(),
|
||||||
[CLIENT_CAPS.providerSnapshotReferences]: z.boolean().optional(),
|
[CLIENT_CAPS.providerSnapshotReferences]: z.boolean().optional(),
|
||||||
[CLIENT_CAPS.timelineReplacementInvalidation]: z.boolean().optional(),
|
[CLIENT_CAPS.timelineReplacementInvalidation]: z.boolean().optional(),
|
||||||
|
[CLIENT_CAPS.timelineRewindOperations]: z.boolean().optional(),
|
||||||
[CLIENT_CAPS.timelineNotifications]: z.boolean().optional(),
|
[CLIENT_CAPS.timelineNotifications]: z.boolean().optional(),
|
||||||
[CLIENT_CAPS.backgroundAgents]: z.boolean().optional(),
|
[CLIENT_CAPS.backgroundAgents]: z.boolean().optional(),
|
||||||
[CLIENT_CAPS.browserHost]: BrowserAutomationHostCapabilitySchema.optional(),
|
[CLIENT_CAPS.browserHost]: BrowserAutomationHostCapabilitySchema.optional(),
|
||||||
@@ -8603,6 +8593,3 @@ export function parseServerInfoStatusPayload(payload: unknown): ServerInfoStatus
|
|||||||
}
|
}
|
||||||
return parsed.data;
|
return parsed.data;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type TailscaleStatus = z.infer<typeof TailscaleStatusSchema>;
|
|
||||||
export type DaemonTailscaleSetResponse = z.infer<typeof DaemonTailscaleSetResponseSchema>;
|
|
||||||
|
|||||||
@@ -217,6 +217,64 @@ describe("wire schema compatibility", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("rewind operations are opt-in and older fetch responses still parse", () => {
|
||||||
|
expect(
|
||||||
|
WSHelloMessageSchema.parse({
|
||||||
|
type: "hello",
|
||||||
|
clientId: "capable-client",
|
||||||
|
clientType: "mobile",
|
||||||
|
protocolVersion: 1,
|
||||||
|
capabilities: { timeline_rewind_operations: true },
|
||||||
|
}).capabilities,
|
||||||
|
).toEqual({ timeline_rewind_operations: true });
|
||||||
|
|
||||||
|
const rewind = {
|
||||||
|
type: "agent.timeline.rewind",
|
||||||
|
payload: {
|
||||||
|
subscriptionId: "sub-1",
|
||||||
|
agentId: "agent-1",
|
||||||
|
epoch: "epoch-1",
|
||||||
|
seq: 12,
|
||||||
|
retireFromSeq: 7,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
expect(SessionOutboundMessageSchema.parse(rewind)).toEqual(rewind);
|
||||||
|
|
||||||
|
const page = {
|
||||||
|
requestId: "fetch-1",
|
||||||
|
agentId: "agent-1",
|
||||||
|
agent: null,
|
||||||
|
direction: "after",
|
||||||
|
projection: "projected",
|
||||||
|
epoch: "epoch-1",
|
||||||
|
reset: false,
|
||||||
|
staleCursor: false,
|
||||||
|
gap: false,
|
||||||
|
window: { minSeq: 1, maxSeq: 14, nextSeq: 15 },
|
||||||
|
startCursor: { epoch: "epoch-1", seq: 13 },
|
||||||
|
endCursor: { epoch: "epoch-1", seq: 14 },
|
||||||
|
hasOlder: true,
|
||||||
|
hasNewer: false,
|
||||||
|
entries: [],
|
||||||
|
error: null,
|
||||||
|
};
|
||||||
|
const withRetirements = { ...page, retirements: [{ seq: 12, retireFromSeq: 7 }] };
|
||||||
|
expect(
|
||||||
|
SessionOutboundMessageSchema.parse({
|
||||||
|
type: "fetch_agent_timeline_response",
|
||||||
|
payload: withRetirements,
|
||||||
|
}),
|
||||||
|
).toMatchObject({ payload: { retirements: [{ seq: 12, retireFromSeq: 7 }] } });
|
||||||
|
// A daemon before rewind operations sends no retirements.
|
||||||
|
const older = SessionOutboundMessageSchema.parse({
|
||||||
|
type: "fetch_agent_timeline_response",
|
||||||
|
payload: page,
|
||||||
|
});
|
||||||
|
expect(older.type === "fetch_agent_timeline_response" && older.payload.retirements).toBe(
|
||||||
|
undefined,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
test("server info strips unknown legacy features while accepting former turn identity", () => {
|
test("server info strips unknown legacy features while accepting former turn identity", () => {
|
||||||
const parsed = ServerInfoStatusPayloadSchema.parse({
|
const parsed = ServerInfoStatusPayloadSchema.parse({
|
||||||
status: "server_info",
|
status: "server_info",
|
||||||
|
|||||||
@@ -139,7 +139,6 @@
|
|||||||
"p-limit": "^7.3.0",
|
"p-limit": "^7.3.0",
|
||||||
"p-memoize": "^8.0.0",
|
"p-memoize": "^8.0.0",
|
||||||
"p-throttle": "^8.1.0",
|
"p-throttle": "^8.1.0",
|
||||||
"parse5": "^7.3.0",
|
|
||||||
"pino": "^10.2.0",
|
"pino": "^10.2.0",
|
||||||
"pino-pretty": "^13.1.3",
|
"pino-pretty": "^13.1.3",
|
||||||
"qrcode": "^1.5.4",
|
"qrcode": "^1.5.4",
|
||||||
@@ -161,7 +160,7 @@
|
|||||||
"@playwright/test": "^1.56.1",
|
"@playwright/test": "^1.56.1",
|
||||||
"@types/express": "^4.17.20",
|
"@types/express": "^4.17.20",
|
||||||
"@types/markdown-it": "^14.2.0",
|
"@types/markdown-it": "^14.2.0",
|
||||||
"@types/node": "^20.9.0",
|
"@types/node": "^22.16.0",
|
||||||
"@types/qrcode": "^1.5.6",
|
"@types/qrcode": "^1.5.6",
|
||||||
"@types/uuid": "^9.0.7",
|
"@types/uuid": "^9.0.7",
|
||||||
"@types/ws": "^8.5.8",
|
"@types/ws": "^8.5.8",
|
||||||
@@ -172,5 +171,8 @@
|
|||||||
},
|
},
|
||||||
"overrides": {
|
"overrides": {
|
||||||
"lightningcss": "1.30.1"
|
"lightningcss": "1.30.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=22.16.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { buildAgentForkContextAttachment, curateAgentActivity } from "./activity
|
|||||||
import type { AgentTimelineItem } from "./agent-sdk-types.js";
|
import type { AgentTimelineItem } from "./agent-sdk-types.js";
|
||||||
import type { AgentTimelineRow } from "./agent-timeline-store-types.js";
|
import type { AgentTimelineRow } from "./agent-timeline-store-types.js";
|
||||||
import { formatAgentMessage, projectAgentMessages } from "./agent-messages/index.js";
|
import { formatAgentMessage, projectAgentMessages } from "./agent-messages/index.js";
|
||||||
import { InMemoryAgentTimelineStore } from "./agent-timeline-store.js";
|
import { AgentTimeline } from "./timeline/index.js";
|
||||||
|
|
||||||
function toolCallItem(params: {
|
function toolCallItem(params: {
|
||||||
callId: string;
|
callId: string;
|
||||||
@@ -41,12 +41,15 @@ function row(seq: number, item: AgentTimelineItem): AgentTimelineRow {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** Rows as the daemon hands them to a fork: projected by the timeline store. */
|
/** Rows as the daemon hands them to a fork: projected by the timeline store. */
|
||||||
function storeTimeline(items: readonly AgentTimelineItem[]) {
|
async function storeTimeline(items: readonly AgentTimelineItem[]) {
|
||||||
const store = new InMemoryAgentTimelineStore();
|
const store = new AgentTimeline();
|
||||||
store.initialize("agent-1");
|
const scope = { agentId: "agent-1" };
|
||||||
for (const item of items) store.append("agent-1", item);
|
await store.create(scope);
|
||||||
const { epoch, rows } = store.fetch("agent-1", { limit: 0 });
|
await store.append(
|
||||||
return { epoch, rows };
|
scope,
|
||||||
|
items.map((item) => ({ item })),
|
||||||
|
);
|
||||||
|
return await store.fetch(scope, { limit: 0 });
|
||||||
}
|
}
|
||||||
|
|
||||||
function backgroundTaskItem(input: { status: "running" | "completed"; log: string }) {
|
function backgroundTaskItem(input: { status: "running" | "completed"; log: string }) {
|
||||||
@@ -452,8 +455,8 @@ second line'`,
|
|||||||
expect(result.attachment.text).toContain("[Assistant] Done.");
|
expect(result.attachment.text).toContain("[Assistant] Done.");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("forks at a response that background work outlives, by message id", () => {
|
it("forks at a response that background work outlives, by message id", async () => {
|
||||||
const { rows } = storeTimeline([
|
const { rows } = await storeTimeline([
|
||||||
{ type: "user_message", text: "Audit in the background", messageId: "user-1" },
|
{ type: "user_message", text: "Audit in the background", messageId: "user-1" },
|
||||||
backgroundTaskItem({ status: "running", log: "scanning" }),
|
backgroundTaskItem({ status: "running", log: "scanning" }),
|
||||||
{ type: "assistant_message", text: "Audit started.", messageId: "assistant-1" },
|
{ type: "assistant_message", text: "Audit started.", messageId: "assistant-1" },
|
||||||
@@ -473,8 +476,8 @@ second line'`,
|
|||||||
expect(result.attachment.text).not.toContain("Any findings?");
|
expect(result.attachment.text).not.toContain("Any findings?");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("forks at a response that background work outlives, by timeline cursor", () => {
|
it("forks at a response that background work outlives, by timeline cursor", async () => {
|
||||||
const { epoch, rows } = storeTimeline([
|
const { epoch, rows } = await storeTimeline([
|
||||||
{ type: "user_message", text: "Audit in the background", messageId: "user-1" },
|
{ type: "user_message", text: "Audit in the background", messageId: "user-1" },
|
||||||
backgroundTaskItem({ status: "running", log: "scanning" }),
|
backgroundTaskItem({ status: "running", log: "scanning" }),
|
||||||
{ type: "assistant_message", text: "Audit started." },
|
{ type: "assistant_message", text: "Audit started." },
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
|
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||||
import { tmpdir } from "node:os";
|
import { tmpdir } from "node:os";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { expect, test } from "vitest";
|
import { expect, test, vi } from "vitest";
|
||||||
|
|
||||||
import { createTestLogger } from "../../test-utils/test-logger.js";
|
import { createTestLogger } from "../../test-utils/test-logger.js";
|
||||||
import { AgentManager } from "./agent-manager.js";
|
import { AgentManager } from "./agent-manager.js";
|
||||||
import { ensureAgentLoaded } from "./agent-loading.js";
|
import { AgentNotFoundError, ensureAgentLoaded, loadAgentHistory } from "./agent-loading.js";
|
||||||
import { startAgentRun } from "./agent-prompt.js";
|
import { startAgentRun } from "./agent-prompt.js";
|
||||||
import { AgentStorage } from "./agent-storage.js";
|
import { AgentStorage } from "./agent-storage.js";
|
||||||
import type {
|
import type {
|
||||||
@@ -227,6 +227,109 @@ test("reopening an agent with no resumable session keeps a metadata write that o
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("reads stored history without starting or requiring the provider, and imports history that is not stored", async () => {
|
||||||
|
const root = await mkdtemp(path.join(tmpdir(), "agent-loading-history-"));
|
||||||
|
const logger = createTestLogger();
|
||||||
|
const storage = new AgentStorage(path.join(root, "agents"), logger);
|
||||||
|
const baseClient = createTestAgentClients().codex;
|
||||||
|
if (!baseClient) {
|
||||||
|
throw new Error("expected Codex test client");
|
||||||
|
}
|
||||||
|
let resumes = 0;
|
||||||
|
const client: AgentClient = {
|
||||||
|
provider: baseClient.provider,
|
||||||
|
capabilities: baseClient.capabilities,
|
||||||
|
createSession: async (config: AgentSessionConfig, launchContext?: AgentLaunchContext) =>
|
||||||
|
await baseClient.createSession(config, launchContext),
|
||||||
|
resumeSession: async (
|
||||||
|
handle: AgentPersistenceHandle,
|
||||||
|
overrides?: Partial<AgentSessionConfig>,
|
||||||
|
launchContext?: AgentLaunchContext,
|
||||||
|
) => {
|
||||||
|
resumes += 1;
|
||||||
|
return await baseClient.resumeSession(handle, overrides, launchContext);
|
||||||
|
},
|
||||||
|
fetchCatalog: async (options) => await baseClient.fetchCatalog(options),
|
||||||
|
isAvailable: async () => await baseClient.isAvailable(),
|
||||||
|
};
|
||||||
|
const agentId = "00000000-0000-4000-8000-000000000601";
|
||||||
|
const managers: AgentManager[] = [];
|
||||||
|
function startDaemon(): AgentManager {
|
||||||
|
const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger });
|
||||||
|
managers.push(manager);
|
||||||
|
return manager;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const manager = startDaemon();
|
||||||
|
const agent = await manager.createAgent({ provider: "codex", cwd: root }, agentId, {
|
||||||
|
workspaceId: "workspace-a",
|
||||||
|
});
|
||||||
|
await manager.runAgent(agent.id, "hello");
|
||||||
|
const transcript = await manager.getTimeline(agent.id);
|
||||||
|
expect(transcript.map((item) => item.type)).toContain("assistant_message");
|
||||||
|
await manager.closeAgent(agent.id);
|
||||||
|
await manager.flush();
|
||||||
|
await storage.flush();
|
||||||
|
|
||||||
|
const stored = await loadAgentHistory(agentId, {
|
||||||
|
agentManager: manager,
|
||||||
|
agentStorage: storage,
|
||||||
|
logger,
|
||||||
|
});
|
||||||
|
expect(stored).toMatchObject({ kind: "stored", record: { id: agentId } });
|
||||||
|
expect(await manager.getTimeline(agentId)).toEqual(transcript);
|
||||||
|
expect(manager.getAgent(agentId)).toBeNull();
|
||||||
|
// Stored history needs no provider, so it still reads once the provider is removed.
|
||||||
|
await expect(
|
||||||
|
loadAgentHistory(agentId, {
|
||||||
|
agentManager: manager,
|
||||||
|
agentStorage: storage,
|
||||||
|
logger,
|
||||||
|
validProviders: [],
|
||||||
|
}),
|
||||||
|
).resolves.toMatchObject({ kind: "stored", record: { id: agentId } });
|
||||||
|
expect(resumes).toBe(0);
|
||||||
|
|
||||||
|
// A restarted daemon has no history in memory; the provider's own history is imported,
|
||||||
|
// which needs the provider.
|
||||||
|
const restarted = startDaemon();
|
||||||
|
await expect(
|
||||||
|
loadAgentHistory(agentId, {
|
||||||
|
agentManager: restarted,
|
||||||
|
agentStorage: storage,
|
||||||
|
logger,
|
||||||
|
validProviders: [],
|
||||||
|
}),
|
||||||
|
).rejects.toThrow("references unavailable provider 'codex'");
|
||||||
|
const loaded = await loadAgentHistory(agentId, {
|
||||||
|
agentManager: restarted,
|
||||||
|
agentStorage: storage,
|
||||||
|
logger,
|
||||||
|
});
|
||||||
|
expect(loaded).toMatchObject({ kind: "live", agent: { id: agentId } });
|
||||||
|
expect(resumes).toBe(1);
|
||||||
|
expect((await restarted.getTimeline(agentId)).map((item) => item.type)).toEqual(
|
||||||
|
transcript.map((item) => item.type),
|
||||||
|
);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
loadAgentHistory("00000000-0000-4000-8000-000000000602", {
|
||||||
|
agentManager: restarted,
|
||||||
|
agentStorage: storage,
|
||||||
|
logger,
|
||||||
|
}),
|
||||||
|
).rejects.toBeInstanceOf(AgentNotFoundError);
|
||||||
|
} finally {
|
||||||
|
for (const manager of managers) {
|
||||||
|
await manager.closeAgent(agentId).catch(() => undefined);
|
||||||
|
await manager.flush().catch(() => undefined);
|
||||||
|
}
|
||||||
|
await storage.flush().catch(() => undefined);
|
||||||
|
await rm(root, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
test.each([false, true])(
|
test.each([false, true])(
|
||||||
"loads history after its working directory is removed (archived: %s)",
|
"loads history after its working directory is removed (archived: %s)",
|
||||||
async (archived) => {
|
async (archived) => {
|
||||||
@@ -271,11 +374,11 @@ test.each([false, true])(
|
|||||||
});
|
});
|
||||||
|
|
||||||
expect(loaded.id).toBe(agentId);
|
expect(loaded.id).toBe(agentId);
|
||||||
// The transcript is replayed from the provider's persisted history, so the reply the
|
// The manager kept the transcript when the agent closed, so the reply the agent gave
|
||||||
// agent gave before the worktree went away is still readable.
|
// before the worktree went away is still readable.
|
||||||
const replies = manager
|
const replies = (await manager.getTimeline(agentId)).filter(
|
||||||
.getTimeline(agentId)
|
(item) => item.type === "assistant_message",
|
||||||
.filter((item) => item.type === "assistant_message");
|
);
|
||||||
expect(replies.length).toBeGreaterThan(0);
|
expect(replies.length).toBeGreaterThan(0);
|
||||||
expect(
|
expect(
|
||||||
replies.every((item) => item.type === "assistant_message" && item.text.length > 0),
|
replies.every((item) => item.type === "assistant_message" && item.text.length > 0),
|
||||||
@@ -318,7 +421,7 @@ test("timeline requests read unarchived stored history with a deleted cwd", asyn
|
|||||||
}
|
}
|
||||||
}, 30000);
|
}, 30000);
|
||||||
|
|
||||||
test("timeline reads keep runnable unarchived agents interactive for the next prompt", async () => {
|
test("timeline reads of stored history leave the provider closed until a prompt resumes it interactively", async () => {
|
||||||
const clients = createTestAgentClients();
|
const clients = createTestAgentClients();
|
||||||
const base = clients.codex!;
|
const base = clients.codex!;
|
||||||
const purposes: Array<AgentResumeSessionOptions | undefined> = [];
|
const purposes: Array<AgentResumeSessionOptions | undefined> = [];
|
||||||
@@ -339,7 +442,8 @@ test("timeline reads keep runnable unarchived agents interactive for the next pr
|
|||||||
const agent = await ctx.client.createAgent({ provider: "codex", cwd });
|
const agent = await ctx.client.createAgent({ provider: "codex", cwd });
|
||||||
await ctx.daemon.daemon.agentManager.closeAgent(agent.id);
|
await ctx.daemon.daemon.agentManager.closeAgent(agent.id);
|
||||||
await ctx.client.fetchAgentTimeline(agent.id);
|
await ctx.client.fetchAgentTimeline(agent.id);
|
||||||
expect(purposes).toEqual([{ purpose: "interactive" }]);
|
// The manager serves the stored timeline itself, so the read resumes no provider session.
|
||||||
|
expect(purposes).toEqual([]);
|
||||||
await ctx.client.sendMessage(agent.id, "continue after opening history");
|
await ctx.client.sendMessage(agent.id, "continue after opening history");
|
||||||
expect((await ctx.client.waitForFinish(agent.id, 15000)).status).toBe("idle");
|
expect((await ctx.client.waitForFinish(agent.id, 15000)).status).toBe("idle");
|
||||||
const timeline = await ctx.client.fetchAgentTimeline(agent.id);
|
const timeline = await ctx.client.fetchAgentTimeline(agent.id);
|
||||||
@@ -353,11 +457,9 @@ test("timeline reads keep runnable unarchived agents interactive for the next pr
|
|||||||
manager.tryRunOutOfBand(agent.id, "first prompt"),
|
manager.tryRunOutOfBand(agent.id, "first prompt"),
|
||||||
manager.tryRunOutOfBand(agent.id, "second prompt"),
|
manager.tryRunOutOfBand(agent.id, "second prompt"),
|
||||||
]);
|
]);
|
||||||
expect(purposes).toEqual([
|
// The prompt resumed once, and the concurrent prompts after the removed-cwd read share one
|
||||||
{ purpose: "interactive" },
|
// resume. Every resume is interactive, so no history session needs replacing.
|
||||||
{ purpose: "history" },
|
expect(purposes).toEqual([{ purpose: "interactive" }, { purpose: "interactive" }]);
|
||||||
undefined, // Reload uses the provider's interactive default.
|
|
||||||
]);
|
|
||||||
} finally {
|
} finally {
|
||||||
await ctx.cleanup();
|
await ctx.cleanup();
|
||||||
await rm(cwd, { recursive: true, force: true });
|
await rm(cwd, { recursive: true, force: true });
|
||||||
@@ -451,9 +553,13 @@ test.each(["mode", "thinking", "rewind"])(
|
|||||||
runtime.recordedLaunches.filter((launch) => launch.session === sessionFile),
|
runtime.recordedLaunches.filter((launch) => launch.session === sessionFile),
|
||||||
).toHaveLength(1);
|
).toHaveLength(1);
|
||||||
expect(manager.getAgent(agentId)?.currentModeId).toBe("full");
|
expect(manager.getAgent(agentId)?.currentModeId).toBe("full");
|
||||||
expect(runtime.latestSession().prompts).toEqual([
|
// The run reads its timeline before the provider starts the turn.
|
||||||
expect.objectContaining({ message: "continue" }),
|
await vi.waitFor(() =>
|
||||||
]);
|
expect(runtime.latestSession().prompts).toEqual([
|
||||||
|
expect.objectContaining({ message: "continue" }),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
runtime.latestSession().beginTurn();
|
||||||
runtime.latestSession().finishTurn();
|
runtime.latestSession().finishTurn();
|
||||||
await manager.waitForAgentEvent(agentId);
|
await manager.waitForAgentEvent(agentId);
|
||||||
await manager.archiveAgent(agentId);
|
await manager.archiveAgent(agentId);
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import type { Logger } from "pino";
|
|||||||
|
|
||||||
import type { AgentProvider } from "./agent-sdk-types.js";
|
import type { AgentProvider } from "./agent-sdk-types.js";
|
||||||
import type { AgentManager, ManagedAgent } from "./agent-manager.js";
|
import type { AgentManager, ManagedAgent } from "./agent-manager.js";
|
||||||
import type { AgentStorage } from "./agent-storage.js";
|
import type { AgentStorage, StoredAgentRecord } from "./agent-storage.js";
|
||||||
import {
|
import {
|
||||||
buildConfigOverrides,
|
buildConfigOverrides,
|
||||||
extractAttention,
|
extractAttention,
|
||||||
@@ -18,20 +18,11 @@ export class AgentNotFoundError extends Error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
interface PendingAgentInitialization {
|
const pendingAgentInitializations = new Map<string, Promise<ManagedAgent>>();
|
||||||
promise: Promise<ManagedAgent>;
|
|
||||||
options: { broadcastTimeline: boolean };
|
|
||||||
}
|
|
||||||
|
|
||||||
const pendingAgentInitializations = new Map<string, PendingAgentInitialization>();
|
|
||||||
|
|
||||||
export type AgentLoaderManager = Pick<
|
export type AgentLoaderManager = Pick<
|
||||||
AgentManager,
|
AgentManager,
|
||||||
| "createAgentFromRecord"
|
"createAgentFromRecord" | "getAgent" | "getRegisteredProviderIds" | "resumeAgentFromPersistence"
|
||||||
| "getAgent"
|
|
||||||
| "getRegisteredProviderIds"
|
|
||||||
| "hydrateTimelineFromProvider"
|
|
||||||
| "resumeAgentFromPersistence"
|
|
||||||
> &
|
> &
|
||||||
Partial<Pick<AgentManager, "waitForAgentClose">>;
|
Partial<Pick<AgentManager, "waitForAgentClose">>;
|
||||||
|
|
||||||
@@ -39,11 +30,54 @@ export interface EnsureAgentLoadedDeps {
|
|||||||
agentManager: AgentLoaderManager;
|
agentManager: AgentLoaderManager;
|
||||||
agentStorage: AgentStorage;
|
agentStorage: AgentStorage;
|
||||||
validProviders?: Iterable<AgentProvider>;
|
validProviders?: Iterable<AgentProvider>;
|
||||||
broadcastTimeline?: boolean;
|
|
||||||
purpose?: "history" | "interactive";
|
purpose?: "history" | "interactive";
|
||||||
logger: Logger;
|
logger: Logger;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The agent's history to read: from its runtime, or stored, with no provider session opened. */
|
||||||
|
export type AgentHistorySource =
|
||||||
|
| { kind: "live"; agent: ManagedAgent }
|
||||||
|
| { kind: "stored"; record: StoredAgentRecord };
|
||||||
|
|
||||||
|
export interface LoadAgentHistoryDeps extends EnsureAgentLoadedDeps {
|
||||||
|
agentManager: AgentLoaderManager & Pick<AgentManager, "hasStoredHistory">;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolves an agent for reading its history. A loaded agent is read live. A stored agent whose
|
||||||
|
* history the timeline holds is read without resuming its provider, so it reads even when its
|
||||||
|
* provider is no longer available. Otherwise the provider is resumed, which imports its history
|
||||||
|
* and requires the provider.
|
||||||
|
*/
|
||||||
|
export async function loadAgentHistory(
|
||||||
|
agentId: string,
|
||||||
|
deps: LoadAgentHistoryDeps,
|
||||||
|
): Promise<AgentHistorySource> {
|
||||||
|
const live = deps.agentManager.getAgent(agentId);
|
||||||
|
if (live) return { kind: "live", agent: live };
|
||||||
|
const record = await deps.agentStorage.get(agentId);
|
||||||
|
if (!record) throw new AgentNotFoundError(agentId);
|
||||||
|
if (await deps.agentManager.hasStoredHistory(agentId)) {
|
||||||
|
return { kind: "stored", record };
|
||||||
|
}
|
||||||
|
return { kind: "live", agent: await ensureAgentLoaded(agentId, deps) };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function requireLoadableRecord(
|
||||||
|
agentId: string,
|
||||||
|
deps: EnsureAgentLoadedDeps,
|
||||||
|
): Promise<StoredAgentRecord> {
|
||||||
|
const record = await deps.agentStorage.get(agentId);
|
||||||
|
if (!record) {
|
||||||
|
throw new AgentNotFoundError(agentId);
|
||||||
|
}
|
||||||
|
const validProviders = deps.validProviders ?? deps.agentManager.getRegisteredProviderIds();
|
||||||
|
if (!isStoredAgentProviderAvailable(record, validProviders)) {
|
||||||
|
throw new Error(`Agent ${agentId} references unavailable provider '${record.provider}'`);
|
||||||
|
}
|
||||||
|
return record;
|
||||||
|
}
|
||||||
|
|
||||||
export async function ensureUnarchivedAgentLoaded(
|
export async function ensureUnarchivedAgentLoaded(
|
||||||
agentId: string,
|
agentId: string,
|
||||||
deps: EnsureAgentLoadedDeps & {
|
deps: EnsureAgentLoadedDeps & {
|
||||||
@@ -75,8 +109,7 @@ export async function ensureAgentLoaded(
|
|||||||
|
|
||||||
const inflight = pendingAgentInitializations.get(agentId);
|
const inflight = pendingAgentInitializations.get(agentId);
|
||||||
if (inflight) {
|
if (inflight) {
|
||||||
inflight.options.broadcastTimeline ||= deps.broadcastTimeline === true;
|
return inflight;
|
||||||
return inflight.promise;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const existing = deps.agentManager.getAgent(agentId);
|
const existing = deps.agentManager.getAgent(agentId);
|
||||||
@@ -91,24 +124,12 @@ export async function ensureAgentLoaded(
|
|||||||
|
|
||||||
const laterInflight = pendingAgentInitializations.get(agentId);
|
const laterInflight = pendingAgentInitializations.get(agentId);
|
||||||
if (laterInflight) {
|
if (laterInflight) {
|
||||||
laterInflight.options.broadcastTimeline ||= deps.broadcastTimeline === true;
|
return laterInflight;
|
||||||
return laterInflight.promise;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const pendingOptions = {
|
|
||||||
broadcastTimeline: deps.broadcastTimeline === true,
|
|
||||||
};
|
|
||||||
const initPromise = (async () => {
|
const initPromise = (async () => {
|
||||||
const record = await deps.agentStorage.get(agentId);
|
const record = await requireLoadableRecord(agentId, deps);
|
||||||
if (!record) {
|
|
||||||
throw new AgentNotFoundError(agentId);
|
|
||||||
}
|
|
||||||
|
|
||||||
const validProviders = deps.validProviders ?? deps.agentManager.getRegisteredProviderIds();
|
const validProviders = deps.validProviders ?? deps.agentManager.getRegisteredProviderIds();
|
||||||
if (!isStoredAgentProviderAvailable(record, validProviders)) {
|
|
||||||
throw new Error(`Agent ${agentId} references unavailable provider '${record.provider}'`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const handle = toAgentPersistenceHandle(validProviders, record.persistence);
|
const handle = toAgentPersistenceHandle(validProviders, record.persistence);
|
||||||
|
|
||||||
let snapshot: ManagedAgent;
|
let snapshot: ManagedAgent;
|
||||||
@@ -130,20 +151,16 @@ export async function ensureAgentLoaded(
|
|||||||
deps.logger.info({ agentId, provider: record.provider }, "Agent created from stored config");
|
deps.logger.info({ agentId, provider: record.provider }, "Agent created from stored config");
|
||||||
}
|
}
|
||||||
|
|
||||||
await deps.agentManager.hydrateTimelineFromProvider(agentId, {
|
|
||||||
broadcast: () => pendingOptions.broadcastTimeline,
|
|
||||||
});
|
|
||||||
return deps.agentManager.getAgent(agentId) ?? snapshot;
|
return deps.agentManager.getAgent(agentId) ?? snapshot;
|
||||||
})();
|
})();
|
||||||
|
|
||||||
const pending: PendingAgentInitialization = { promise: initPromise, options: pendingOptions };
|
pendingAgentInitializations.set(agentId, initPromise);
|
||||||
pendingAgentInitializations.set(agentId, pending);
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
return await initPromise;
|
return await initPromise;
|
||||||
} finally {
|
} finally {
|
||||||
const current = pendingAgentInitializations.get(agentId);
|
const current = pendingAgentInitializations.get(agentId);
|
||||||
if (current === pending) {
|
if (current === initPromise) {
|
||||||
pendingAgentInitializations.delete(agentId);
|
pendingAgentInitializations.delete(agentId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ import { tmpdir } from "node:os";
|
|||||||
import { join } from "node:path";
|
import { join } from "node:path";
|
||||||
import { afterEach, describe, expect, test, vi } from "vitest";
|
import { afterEach, describe, expect, test, vi } from "vitest";
|
||||||
|
|
||||||
|
import pino, { type Logger } from "pino";
|
||||||
|
|
||||||
import { createTestLogger } from "../../test-utils/test-logger.js";
|
import { createTestLogger } from "../../test-utils/test-logger.js";
|
||||||
import { AgentManager, type AgentManagerEvent } from "./agent-manager.js";
|
import { AgentManager, type AgentManagerEvent } from "./agent-manager.js";
|
||||||
import { AGENT_STREAM_COALESCE_DEFAULT_WINDOW_MS } from "./agent-stream-coalescer.js";
|
import { AGENT_STREAM_COALESCE_DEFAULT_WINDOW_MS } from "./agent-stream-coalescer.js";
|
||||||
@@ -13,6 +15,8 @@ import { FakeOmp } from "./providers/omp/test-utils/fake-omp.js";
|
|||||||
import { PiRpcAgentClient } from "./providers/pi/agent.js";
|
import { PiRpcAgentClient } from "./providers/pi/agent.js";
|
||||||
import { FakePi } from "./providers/pi/test-utils/fake-pi.js";
|
import { FakePi } from "./providers/pi/test-utils/fake-pi.js";
|
||||||
import { projectTimelineRows } from "./timeline-projection.js";
|
import { projectTimelineRows } from "./timeline-projection.js";
|
||||||
|
import { AgentTimeline } from "./timeline/index.js";
|
||||||
|
import { DeferredTimelineBackend } from "./timeline/testing.js";
|
||||||
import type {
|
import type {
|
||||||
AgentCapabilityFlags,
|
AgentCapabilityFlags,
|
||||||
AgentClient,
|
AgentClient,
|
||||||
@@ -182,6 +186,7 @@ class TestAgentSession implements AgentSession {
|
|||||||
class TestAgentClient implements AgentClient {
|
class TestAgentClient implements AgentClient {
|
||||||
readonly capabilities = TEST_CAPABILITIES;
|
readonly capabilities = TEST_CAPABILITIES;
|
||||||
private sessionCounter = 0;
|
private sessionCounter = 0;
|
||||||
|
private history: AgentStreamEvent[] = [];
|
||||||
readonly sessions = new Map<string, TestAgentSession>();
|
readonly sessions = new Map<string, TestAgentSession>();
|
||||||
|
|
||||||
constructor(readonly provider: AgentProvider = "codex") {}
|
constructor(readonly provider: AgentProvider = "codex") {}
|
||||||
@@ -195,6 +200,7 @@ class TestAgentClient implements AgentClient {
|
|||||||
config,
|
config,
|
||||||
`${config.provider}-session-${++this.sessionCounter}`,
|
`${config.provider}-session-${++this.sessionCounter}`,
|
||||||
);
|
);
|
||||||
|
session.setHistory(this.history);
|
||||||
this.sessions.set(config.cwd, session);
|
this.sessions.set(config.cwd, session);
|
||||||
return session;
|
return session;
|
||||||
}
|
}
|
||||||
@@ -230,6 +236,11 @@ class TestAgentClient implements AgentClient {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The provider history of the sessions created from now on. */
|
||||||
|
setHistory(events: AgentStreamEvent[]): void {
|
||||||
|
this.history = [...events];
|
||||||
|
}
|
||||||
|
|
||||||
getSession(cwd: string): TestAgentSession {
|
getSession(cwd: string): TestAgentSession {
|
||||||
const session = this.sessions.get(cwd);
|
const session = this.sessions.get(cwd);
|
||||||
if (!session) {
|
if (!session) {
|
||||||
@@ -247,13 +258,18 @@ interface Harness {
|
|||||||
cleanup: () => void;
|
cleanup: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
function createHarness(options?: { provider?: AgentProvider }): Harness {
|
function createHarness(options?: {
|
||||||
|
provider?: AgentProvider;
|
||||||
|
timeline?: AgentTimeline;
|
||||||
|
logger?: Logger;
|
||||||
|
}): Harness {
|
||||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-stream-coalescing-"));
|
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-stream-coalescing-"));
|
||||||
const client = new TestAgentClient(options?.provider ?? "codex");
|
const client = new TestAgentClient(options?.provider ?? "codex");
|
||||||
const manager = new AgentManager({
|
const manager = new AgentManager({
|
||||||
clients: { [client.provider]: client },
|
clients: { [client.provider]: client },
|
||||||
idFactory: createIdFactory(),
|
idFactory: createIdFactory(),
|
||||||
logger: createTestLogger(),
|
logger: options?.logger ?? createTestLogger(),
|
||||||
|
timeline: options?.timeline,
|
||||||
});
|
});
|
||||||
const events: AgentManagerEvent[] = [];
|
const events: AgentManagerEvent[] = [];
|
||||||
manager.subscribe((event) => events.push(event), { replayState: false });
|
manager.subscribe((event) => events.push(event), { replayState: false });
|
||||||
@@ -272,6 +288,20 @@ function createIdFactory(): () => string {
|
|||||||
return () => AGENT_IDS[index++] ?? `00000000-0000-4000-8000-${String(index).padStart(12, "0")}`;
|
return () => AGENT_IDS[index++] ?? `00000000-0000-4000-8000-${String(index).padStart(12, "0")}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Resumes an agent whose history Paseo does not hold, so it imports the provider's. */
|
||||||
|
async function resumeWithProviderHistory(
|
||||||
|
harness: Harness,
|
||||||
|
history: AgentStreamEvent[],
|
||||||
|
): Promise<{ agentId: string }> {
|
||||||
|
harness.client.setHistory(history);
|
||||||
|
const agent = await harness.manager.resumeAgentFromPersistence(
|
||||||
|
{ provider: harness.client.provider, sessionId: "provider-history" },
|
||||||
|
{ cwd: harness.workdir },
|
||||||
|
AGENT_IDS[0],
|
||||||
|
);
|
||||||
|
return { agentId: agent.id };
|
||||||
|
}
|
||||||
|
|
||||||
async function createManagedSession(
|
async function createManagedSession(
|
||||||
harness: Harness,
|
harness: Harness,
|
||||||
options?: { agentId?: string; provider?: AgentProvider; workdir?: string },
|
options?: { agentId?: string; provider?: AgentProvider; workdir?: string },
|
||||||
@@ -671,15 +701,15 @@ describe("target coalesced behavior", () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
test("bounds tool output while hydrating provider history", async () => {
|
test("bounds tool output while importing provider history", async () => {
|
||||||
const harness = createHarness();
|
const harness = createHarness();
|
||||||
try {
|
try {
|
||||||
const { agentId, session } = await createManagedSession(harness);
|
|
||||||
const output = `${"a".repeat(512 * 1024)}${"z".repeat(512 * 1024)}`;
|
const output = `${"a".repeat(512 * 1024)}${"z".repeat(512 * 1024)}`;
|
||||||
const expectedItem = limitAgentTimelineItemContent(toolCall({ status: "completed", output }));
|
const expectedItem = limitAgentTimelineItemContent(toolCall({ status: "completed", output }));
|
||||||
session.setHistory([timelineEvent(toolCall({ status: "completed", output }))]);
|
|
||||||
|
|
||||||
await harness.manager.hydrateTimelineFromProvider(agentId, { force: true });
|
const { agentId } = await resumeWithProviderHistory(harness, [
|
||||||
|
timelineEvent(toolCall({ status: "completed", output })),
|
||||||
|
]);
|
||||||
|
|
||||||
expect(getTimelineItems(await harness.manager.getTimelineRows(agentId))).toEqual([
|
expect(getTimelineItems(await harness.manager.getTimelineRows(agentId))).toEqual([
|
||||||
expectedItem,
|
expectedItem,
|
||||||
@@ -1270,6 +1300,81 @@ describe("target coalesced behavior", () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test.each(["turn_completed", "turn_failed", "turn_canceled"] as const)(
|
||||||
|
"%s waits for the final chunk an asynchronous timeline is still committing",
|
||||||
|
async (terminalType) => {
|
||||||
|
const harness = createHarness({ timeline: new AgentTimeline(new DeferredTimelineBackend()) });
|
||||||
|
try {
|
||||||
|
const { agentId, session } = await createManagedSession(harness);
|
||||||
|
|
||||||
|
session.pushEvent(assistant("final chunk", "codex", "turn"));
|
||||||
|
session.pushEvent(terminalEvent(terminalType, "turn"));
|
||||||
|
|
||||||
|
const streamTypes = () =>
|
||||||
|
getStreamEvents(harness.events, agentId).map((event) =>
|
||||||
|
event.type === "agent_stream" ? event.event.type : event.type,
|
||||||
|
);
|
||||||
|
await expect.poll(streamTypes).toContain(terminalType);
|
||||||
|
const streamEvents = getStreamEvents(harness.events, agentId);
|
||||||
|
expect(streamEvents[0]).toMatchObject({
|
||||||
|
event: { type: "timeline", item: { type: "assistant_message", text: "final chunk" } },
|
||||||
|
seq: 1,
|
||||||
|
});
|
||||||
|
expect(streamTypes().indexOf(terminalType)).toBeGreaterThan(0);
|
||||||
|
} finally {
|
||||||
|
await harness.manager.flush();
|
||||||
|
harness.cleanup();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
test("a final chunk the timeline fails to commit surfaces a history error after the turn", async () => {
|
||||||
|
const backend = new DeferredTimelineBackend();
|
||||||
|
const logs: Array<Record<string, unknown>> = [];
|
||||||
|
const harness = createHarness({
|
||||||
|
timeline: new AgentTimeline(backend),
|
||||||
|
logger: pino({ level: "error" }, { write: (line: string) => logs.push(JSON.parse(line)) }),
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
const { agentId, session } = await createManagedSession(harness);
|
||||||
|
session.pushEvent(assistant("earlier chunk", "codex", "earlier"));
|
||||||
|
session.pushEvent(terminalEvent("turn_completed", "earlier"));
|
||||||
|
await expect.poll(() => getTimelineStreamEvents(harness.events, agentId)).toHaveLength(1);
|
||||||
|
await harness.manager.flush();
|
||||||
|
session.pushEvent({ type: "turn_started", provider: "codex", turnId: "turn" });
|
||||||
|
await expect.poll(() => harness.manager.getAgent(agentId)?.lifecycle).toBe("running");
|
||||||
|
backend.failNextAppend = true;
|
||||||
|
session.pushEvent(assistant("final chunk", "codex", "turn"));
|
||||||
|
session.pushEvent(terminalEvent("turn_completed", "turn"));
|
||||||
|
|
||||||
|
const completions = () =>
|
||||||
|
getStreamEvents(harness.events, agentId).filter(
|
||||||
|
(event) => event.type === "agent_stream" && event.event.type === "turn_completed",
|
||||||
|
);
|
||||||
|
await expect.poll(completions).toHaveLength(2);
|
||||||
|
await harness.manager.flush();
|
||||||
|
expect(harness.manager.getAgent(agentId)).toMatchObject({
|
||||||
|
lifecycle: "error",
|
||||||
|
lastError: "Conversation history could not be saved: disk full",
|
||||||
|
attention: { requiresAttention: true, attentionReason: "error" },
|
||||||
|
});
|
||||||
|
const earlier = { type: "assistant_message", text: "earlier chunk" };
|
||||||
|
expect(getTimelineStreamEvents(harness.events, agentId)).toEqual([
|
||||||
|
expect.objectContaining({ event: expect.objectContaining({ item: earlier }) }),
|
||||||
|
]);
|
||||||
|
expect(getTimelineItems(await harness.manager.getTimelineRows(agentId))).toEqual([earlier]);
|
||||||
|
expect(logs).toContainEqual(
|
||||||
|
expect.objectContaining({
|
||||||
|
msg: "Failed to record timeline item",
|
||||||
|
agentId,
|
||||||
|
err: expect.objectContaining({ message: "disk full" }),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
harness.cleanup();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
test("lifecycle paths are timer-safe", async () => {
|
test("lifecycle paths are timer-safe", async () => {
|
||||||
vi.useFakeTimers();
|
vi.useFakeTimers();
|
||||||
|
|
||||||
@@ -1490,14 +1595,16 @@ describe("target coalesced behavior", () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
test("history hydration projects immediately without waiting for a streaming window", async () => {
|
test("history import projects immediately without waiting for a streaming window", async () => {
|
||||||
vi.useFakeTimers();
|
vi.useFakeTimers();
|
||||||
const harness = createHarness();
|
const harness = createHarness();
|
||||||
try {
|
try {
|
||||||
const { agentId, session } = await createManagedSession(harness);
|
const { agentId } = await resumeWithProviderHistory(harness, [
|
||||||
session.setHistory([assistant("a1"), assistant("a2"), reasoning("r1"), reasoning("r2")]);
|
assistant("a1"),
|
||||||
|
assistant("a2"),
|
||||||
await harness.manager.hydrateTimelineFromProvider(agentId, { force: true });
|
reasoning("r1"),
|
||||||
|
reasoning("r2"),
|
||||||
|
]);
|
||||||
|
|
||||||
const rows = await harness.manager.getTimelineRows(agentId);
|
const rows = await harness.manager.getTimelineRows(agentId);
|
||||||
expect(getTimelineItems(rows)).toEqual([
|
expect(getTimelineItems(rows)).toEqual([
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user