mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-25 09:46:05 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b7af3da71f | ||
|
|
2789421fbd | ||
|
|
b7b5acf086 | ||
|
|
bf83a03ce9 | ||
|
|
80240eb851 | ||
|
|
0c11263d4d | ||
|
|
28c9806da8 | ||
|
|
a0add767c0 | ||
|
|
25f637e57c | ||
|
|
53fa9524cf | ||
|
|
5a8383d237 | ||
|
|
cf3caefa14 | ||
|
|
c747a58871 | ||
|
|
c36d398829 | ||
|
|
183bc736ec | ||
|
|
c4ce21a237 | ||
|
|
9a2236dac3 | ||
|
|
ecd0dd083e | ||
|
|
10c443a32b | ||
|
|
457d8d6ec5 | ||
|
|
80879eaf7c | ||
|
|
dc85c2bfbc | ||
|
|
5ed1f8d108 | ||
|
|
4178497d3d |
@@ -422,6 +422,7 @@
|
||||
"packages/app/src/components/headers/back-header.tsx",
|
||||
"packages/app/src/components/headers/screen-header.tsx",
|
||||
"packages/app/src/components/host-status-dot.tsx",
|
||||
"packages/app/src/components/hosts/host-picker.tsx",
|
||||
"packages/app/src/components/icons/paseo-logo.tsx",
|
||||
"packages/app/src/components/left-sidebar.tsx",
|
||||
"packages/app/src/components/plan-card.tsx",
|
||||
@@ -551,7 +552,9 @@
|
||||
"packages/app/src/components/download-toast.tsx",
|
||||
"packages/app/src/components/file-explorer-pane.tsx",
|
||||
"packages/app/src/components/headers/back-header.tsx",
|
||||
"packages/app/src/components/highlighted-code-block.tsx",
|
||||
"packages/app/src/components/hosts/host-filter.tsx",
|
||||
"packages/app/src/components/hosts/host-picker.tsx",
|
||||
"packages/app/src/components/import-session-sheet.tsx",
|
||||
"packages/app/src/components/left-sidebar.tsx",
|
||||
"packages/app/src/components/markdown/fence/mermaid/host.native.tsx",
|
||||
|
||||
@@ -54,6 +54,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/terminal-performance.md](docs/terminal-performance.md) | Terminal latency pipeline, coalescing/backpressure invariants, benchmark + perf spec usage |
|
||||
| [docs/terminal-rendering.md](docs/terminal-rendering.md) | Native terminal view: xterm owns the grid, cluster placement, emoji widths, mixed-direction limits, render regression |
|
||||
| [docs/timeline-sync.md](docs/timeline-sync.md) | Owned agent history, rewind retirements, live stream vs authoritative fetch, paged catch-up, client replica |
|
||||
| [docs/agent-stream-performance.md](docs/agent-stream-performance.md) | Assistant text pipeline — coalescing window, paced reveal, why arrival lumps are smoothed at render |
|
||||
| [docs/agent-stream-disclosure.md](docs/agent-stream-disclosure.md) | Expand/collapse in the chat timeline — hold contract, native anchor sequence, frame spacing, render-window cost |
|
||||
| [docs/markdown-renderer.md](docs/markdown-renderer.md) | Shared Markdown engine, the vendored library fork, native selection, links, images and library constraints |
|
||||
|
||||
@@ -48,7 +48,7 @@ Paseo is an open source agentic development environment for desktop, mobile, web
|
||||
- **Multi-provider:** Claude Code, Codex, Copilot, OpenCode, Pi, Antigravity, and Muse Code through the same interface. Pick the right model for each job.
|
||||
- **Voice control:** Dictate tasks or talk through problems in voice mode. Hands-free when you need it.
|
||||
- **Cross-device:** iOS, Android, desktop, web, and CLI. Start work at your desk, check in from your phone, script it from the terminal.
|
||||
- **Privacy-first:** No telemetry, tracking, or forced login. Remote access uses an optional end-to-end encrypted relay.
|
||||
- **Privacy-first:** Paseo doesn't have any telemetry, tracking, or forced log-ins.
|
||||
|
||||
[Run parallel tasks in Paseo](https://paseo.sh/docs/parallel-development): start agents in separate worktrees, review their diffs, run each app, and check it in the built-in browser.
|
||||
|
||||
|
||||
+3
-3
@@ -51,7 +51,7 @@
|
||||
- **多提供商:** 通过同一个界面使用 Claude Code、Codex、Copilot、OpenCode 和 Pi。为每个任务选择合适的模型。
|
||||
- **语音控制:** 在语音模式下口述任务或讨论问题。需要免手操作时很方便。
|
||||
- **跨设备:** 支持 iOS、Android、桌面端、Web 和 CLI。在桌前开始工作,用手机查看进度,也可以从终端脚本化操作。
|
||||
- **隐私优先**:无遥测、无追踪、不强制登录。远程访问可使用可选的端到端加密中继。
|
||||
- **隐私优先:** Paseo 没有遥测、追踪,也不会强制登录。
|
||||
|
||||
## 赞助商
|
||||
|
||||
@@ -93,7 +93,7 @@ npm install -g @getpaseo/cli
|
||||
paseo
|
||||
```
|
||||
|
||||
Paseo 启动后会询问是否启用端到端加密中继以进行设备配对。如果拒绝,可以通过 TCP、Tailscale 或其他 VPN 直接连接。这个方式适合服务器和远程机器。
|
||||
终端中会显示一个二维码。你可以从任意客户端连接。这个方式适合服务器和远程机器。
|
||||
|
||||
完整安装和配置见:
|
||||
|
||||
@@ -140,7 +140,7 @@ Monorepo 包结构速览:
|
||||
- `packages/app`:Expo 客户端(iOS、Android、Web)
|
||||
- `packages/cli`:用于 daemon 和 agent 工作流的 `paseo` CLI
|
||||
- `packages/desktop`:Electron 桌面 app
|
||||
- `packages/relay`:daemon 和客户端使用的中继传输与端到端加密包
|
||||
- `packages/relay`:用于远程连接的 relay 包
|
||||
- `packages/website`:营销站点和文档(`paseo.sh`)
|
||||
|
||||
常用命令:
|
||||
|
||||
+1
-1
@@ -33,7 +33,7 @@ The relay sees only: IP addresses, timing, message sizes, session IDs, and the p
|
||||
The daemon requires a valid cryptographic handshake before processing any commands. A compromised relay cannot:
|
||||
|
||||
- **Impersonate the daemon to your phone** — Without the daemon's secret key, it cannot derive the shared key, so any traffic it injects fails authenticated decryption on the phone
|
||||
- **Open a session without pairing** — The daemon's public key is carried only in the pairing offer and is never sent to the relay. With a daemon password configured, the daemon also rejects any relay client that does not send the right password inside the encrypted channel.
|
||||
- **Send commands as you** — The daemon only accepts traffic that decrypts and authenticates under a shared key derived with its own secret key. The phone's keypair is ephemeral per connection, so there is no persistent phone-side secret to steal; protection comes from the daemon's secret key never leaving the daemon.
|
||||
- **Read your traffic** — After the handshake every message is encrypted: ChaCha20-Poly1305 in protected mode, XSalsa20-Poly1305 (NaCl box) in legacy mode
|
||||
- **Forge messages** — Both constructions are authenticated encryption; a tampered message is rejected in either mode
|
||||
- **Replay old messages** — In protected mode the daemon contributes a fresh ephemeral key to every session and every record carries a strictly increasing counter, so a recorded session cannot be replayed into a new one and a duplicated, reordered, or reflected record closes the session. Legacy mode has neither property: it uses random nonces, and a daemon that still admits legacy clients accepts a recorded legacy transcript (hello, credentials, commands) as a new session. Set `daemon.relay.requireProtectedSecurity: true` to refuse legacy clients once every client you use has updated.
|
||||
|
||||
@@ -39,8 +39,8 @@ An unarchived agent may be `closed` without being deleted or archived. Closing r
|
||||
processes and subscriptions while retaining its Paseo identity, persistence handle, timeline,
|
||||
workspace, labels, title, usage, attention, timestamps, and parent relationship. Opening or prompting
|
||||
the agent runs through `ensureAgentLoaded()`, which resumes the durable provider session under the
|
||||
same Paseo agent ID. Provider history is not appended again when the canonical timeline is already
|
||||
primed.
|
||||
same Paseo agent ID. Resume does not read provider history when the agent already has a timeline;
|
||||
see [owned history](timeline-sync.md#owned-history).
|
||||
|
||||
Reload releases the old runtime before resuming its durable session: an idle provider process can
|
||||
still own an exclusive writer. A close failure retains that runtime for cleanup and blocks the
|
||||
@@ -256,7 +256,8 @@ lifecycle is separate from public workspace visibility and is not a public creat
|
||||
Archive is a **soft delete**: the agent record stays on disk with `archivedAt` set, the runtime is closed, and the agent disappears from active lists. Archive is **global** — it lives on the server and propagates to every connected client.
|
||||
|
||||
Archive sets `archivedAt`, invokes the provider's native archive hook, and cascades to managed
|
||||
children.
|
||||
children. The timeline and the provider children stay, so an archived chat reads them without its
|
||||
provider; deleting the agent removes them.
|
||||
|
||||
`create_agent_request` can opt an agent into `autoArchive`. In that mode the daemon archives the agent after the first terminal turn event (`turn_completed`, `turn_failed`, or `turn_canceled`). When the agent owns an isolated workspace, auto-archive archives that workspace too; the managed worktree is removed when its final workspace reference is gone.
|
||||
|
||||
@@ -352,6 +353,8 @@ Workspace status is an aggregate activity signal computed **per `workspaceId`**.
|
||||
|
||||
Running provider-native subagents contribute `running` to the workspace owned by their parent agent. Their completed, failed, and canceled states stay in the parent's subagents track.
|
||||
|
||||
Only the parent's current runtime makes a provider child running. A child's stored status is the last report about it, and that report can come from provider history or from a runtime an earlier daemon ran, so a stored `running` child does not make the workspace running or keep the parent's runtime alive. It counts again once the live session reports it running. Closing a runtime cancels the children that runtime reported running; children it never reported keep their stored status.
|
||||
|
||||
A finished or failed workspace can be marked unread after it has been reviewed. The daemon restores
|
||||
attention on its newest eligible workspace-root agent, `error` for an agent whose lifecycle is
|
||||
`error` and `finished` otherwise, without sending a new notification. Opening a workspace restores
|
||||
|
||||
@@ -94,6 +94,7 @@ workspace for a directory clears it. The store lives in memory and resets on dae
|
||||
| `server/directory-sync/` | Daemon-global latest-state sequences for projects, workspaces, and agents |
|
||||
| `server/workspace-labels/` | Host-local label catalog, assignment mutations, and explicit subscriptions |
|
||||
| `server/agent/agent-manager.ts` | Agent lifecycle state machine, timeline tracking, subscriber management |
|
||||
| `server/agent/timeline/` | Owned agent history, provider children, rewind retirements, behind a backend |
|
||||
| `server/agent/agent-storage.ts` | File-backed JSON persistence at `$PASEO_HOME/agents/` |
|
||||
| `server/agent/tools/` | Transport-neutral catalog for workspaces, agents, permissions, and automation |
|
||||
| `server/agent/mcp-server.ts` | Thin MCP adapter that registers the Paseo tool catalog with the MCP SDK |
|
||||
|
||||
@@ -133,9 +133,7 @@ A configured URL takes precedence even when unreachable; Paseo reports the conne
|
||||
|
||||
An explicitly configured server needs the bridge installed separately. Connect once and start a session: the setup error gives the local package directory. Copy that directory to the server's OpenCode global `plugins` directory, then retry. For a server on another machine, set `PASEO_OPENCODE_BRIDGE_PORT` in the Paseo OpenCode provider environment before starting Paseo, and set `PASEO_OPENCODE_BRIDGE_URL` to the URL the OpenCode server can use to reach that port. For example, an SSH reverse tunnel can expose the Paseo loopback port on the OpenCode host. The bridge token is exchanged through the OpenCode connection and is not written into the plugin package.
|
||||
|
||||
Agent MCP servers and per-agent environment work on a reused server with OpenCode 2.0.29 or newer. Paseo connects each agent's MCP servers itself and shows their tools only to that agent and its subagents. Other agents in the same directory and your own OpenCode sessions do not see them. The agent's environment applies to its shell commands, its subagents, and its stdio MCP servers.
|
||||
|
||||
The provider `env` configures the OpenCode process. When it sets variables other than the connection variables above and `XDG_CONFIG_HOME`, `XDG_STATE_HOME`, or `OPENCODE_CONFIG_DIR`, Paseo ignores a registered service and starts its own helper. With an explicit URL, Paseo reports those variables as an error.
|
||||
OpenCode's custom MCP registrations are shared by all sessions in a location. Paseo rejects custom MCP servers and per-agent process environment overrides on a reused server rather than applying them to other sessions or ignoring them. Session identity is applied to each session's shell environment. A Paseo-owned helper supports custom process and MCP settings; it is selected when there is no explicit URL or healthy registered service.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -181,6 +181,14 @@ Terminal activity contributes to the workspace status bucket **per `workspaceId`
|
||||
|
||||
---
|
||||
|
||||
## Runtime-only Agent Timelines
|
||||
|
||||
Agent timelines are not written to `$PASEO_HOME`. `AgentTimeline` owns each agent's history behind
|
||||
a backend, and the only backend is in memory, so a daemon restart loses it and the next resume
|
||||
imports provider history. See [owned history](timeline-sync.md#owned-history).
|
||||
|
||||
---
|
||||
|
||||
## 2. Daemon Configuration
|
||||
|
||||
**Path:** `$PASEO_HOME/config.json`
|
||||
|
||||
@@ -43,11 +43,7 @@ Math and video are disabled. Task lists and admonitions are enabled; task checkb
|
||||
|
||||
Mermaid fences use the existing isolated diagram runtime and fullscreen viewer. Web dispatches them through the library’s code-block override. Native has no block-renderer hook, so the renderer extracts only Mermaid fences and places the existing WebView host between library-rendered segments. This is the only block exception; see [native selection limitations](native-text-selection.md) for diagram grouping and leading inline images. Streaming keeps the last valid diagram visible while the next revision renders.
|
||||
|
||||
Code blocks and plain quotes have a copy control in their top trailing corner. Native code blocks use the library's compiled grammars. On native, the code block and quote container views share one control (`HeaderCopyButton` on Android, `ENRMHeaderCopyButton` on iOS). A quote reserves the code block's header band above its body, so the control never covers quote text at any font size. On web, code blocks use `HighlightedCodeBlock` through the library's `renderers.codeBlock` override, and quotes use `WebBlockquote` through `renderers.blockquote`. Both use `BlockCopyButton`. On compact layouts the control is always visible, so the web quote reserves a band above its body, as native does. On wide layouts the control appears on hover or focus, so the quote keeps a right gutter instead; a band there would leave an empty strip above every quote.
|
||||
|
||||
A quote copies its body without the `>` markers, with its nested Markdown, and reads the content at the time of the press, so a streaming quote copies what it shows. A nested quote or code block keeps its own control. Web quote copy uses the same two clipboard flavors as selection copy: `text/plain` is unescaped Markdown and `text/html` is rendered from escaped Markdown. A rendered Mermaid diagram copies as its fence because its wrapper carries the fence source. Native quote copy serializes the quote's parsed Markdown, so a workspace image copies as its cached file URL, as native selection copy does; native has no map back to the workspace path. A native Mermaid diagram in a quote renders outside it (see [native selection limitations](native-text-selection.md)), so each quote fragment copies only its own text. Admonitions get no control: web renders them with a separate library renderer. On web an admonition inside a copied quote copies as its `> [!TYPE]` source; the fork marks the box and its generated title for this. Selection copy keeps the text it shows, because the cloned range cannot tell a whole callout from part of one. On native, quotes inside list items get no control, because they render as text spans in the item. Web renders them as blocks, so they get one.
|
||||
|
||||
Selection copy has to tell links Paseo recognized in the text (paths, forge references, code spans) from links in the Markdown, so the web link renderer marks the recognized ones. Plain-text paste carries them as the text the reply showed, and rich paste keeps them as links only when they point to an `http` or `https` URL. Authored links and parser autolinks such as a bare `www.example.com` copy as links. The fork also keeps the library's block spacing around the web code block override, preserves web list numbering and link titles, marks pending parses with `aria-busy` so Find waits for rendered text, and carries link syntax through native and web tap events. Web inline code inside a link inherits only the link colour; its code font, size and background stay intact. Keep link variants colour-only: native pills replace text runs and prevent paths from wrapping; Android pills also use the surrounding block’s font size. [Upstream PR #997](https://github.com/software-mansion/enriched-markdown/pull/997) tracks these changes.
|
||||
Native code blocks use the library's copy control and compiled grammars. Web code blocks use `HighlightedCodeBlock` through the library's `renderers.codeBlock` override. Selection copy has to tell links Paseo recognized in the text (paths, forge references, code spans) from links in the Markdown, so the web link renderer marks the recognized ones. Plain-text paste carries them as the text the reply showed, and rich paste keeps them as links only when they point to an `http` or `https` URL. Authored links and parser autolinks such as a bare `www.example.com` copy as links. The fork also keeps the library's block spacing around the web code block override, preserves web list numbering and link titles, marks pending parses with `aria-busy` so Find waits for rendered text, and carries link syntax through native and web tap events. Web inline code inside a link inherits only the link colour; its code font, size and background stay intact. Keep link variants colour-only: native pills replace text runs and prevent paths from wrapping; Android pills also use the surrounding block’s font size. [Upstream PR #997](https://github.com/software-mansion/enriched-markdown/pull/997) tracks these changes.
|
||||
|
||||
The fork also keeps overflowing native horizontal blocks in control of their drags: Android claims parent interception at touch-down and releases it for vertical drags so the chat list can scroll; iOS keeps its scroll recognizer active for outward drags at the leading edge. This prevents compact sidebar pans from taking block scrolling without changing sidebar swipes on prose or non-overflowing blocks. Native changes require a client rebuild.
|
||||
|
||||
@@ -59,4 +55,4 @@ The library determines how incomplete Markdown appears during streaming. Complet
|
||||
|
||||
## Verification
|
||||
|
||||
Follow [QA](qa.md) and [mobile testing](mobile-testing.md). Exercise chat, file preview, plan and PR content on all three platforms. Include cross-paragraph selection, progressive streaming, a file-link tap, code copy/highlighting, quote copy (nested quote, code block in a quote, admonition, large font on native), a table and a workspace image. On iPad, repeat preview selection after opening and closing Explorer and after rotation. Check web find, selection-copy and source-message navigation after DOM changes.
|
||||
Follow [QA](qa.md) and [mobile testing](mobile-testing.md). Exercise chat, file preview, plan and PR content on all three platforms. Include cross-paragraph selection, progressive streaming, a file-link tap, code copy/highlighting, a table and a workspace image. On iPad, repeat preview selection after opening and closing Explorer and after rotation. Check web find, selection-copy and source-message navigation after DOM changes.
|
||||
|
||||
+1
-1
@@ -171,7 +171,7 @@ V2.0.4 also removed the activation endpoint that gated a cold location, and a co
|
||||
|
||||
Paseo installs its OpenCode tool bridge through `OPENCODE_CONFIG_CONTENT`. V1 accepts a plugin file; v2 silently skips configured files and requires a package directory with a server entry point. Both versions use the daemon's private loopback bridge for caller-scoped tools. The global manifest must use agent-scoped schemas before a session is bound, because every bridge call executes in an agent session. V2 discovers definitions from each bound session's catalog: plugin-contributed tools can be absent from the global manifest, and an allowlist cannot register a missing definition. Registration is location-wide, so session filtering and caller-scoped execution must remain in place. Bridge context lives only in daemon memory and is removed when the Paseo session closes. The content-addressed plugin artifacts contain no session data or secrets. V2 also needs this plugin when native Paseo tools are disabled: its prompt API has no structured-output format, so the plugin supplies a schema-validated final-answer tool.
|
||||
|
||||
No v2 agent gets a dedicated OpenCode server, because a reused server cannot provide one. OpenCode's MCP configuration is location-scoped, so Paseo never calls `mcp.add` for an agent. The daemon connects the agent's MCP servers itself (`v2/session-mcp.ts`), and the v2 plugin exposes their tools under OpenCode's native `<server>_<tool>` names. Each name registers once per location. The plugin's `context` hook gives each session its own definition and removes the tool from other sessions. If the user's own OpenCode configuration registered a tool with the same name first, other sessions keep that tool and its execution. Execution routes to the calling session's root binding. The hook also adds the servers' instructions to each request. OpenCode loads instruction entries before the hook runs, so an entry written when a child is adopted would miss the child's first request. The plugin calls OpenCode's `permission.assert` before each call, so `toolPolicy.preapproved` grants still apply. That API exists from OpenCode 2.0.29. Bind reports `features.mcpTools`, so an older server or a stale plugin fails the session at creation instead of hiding its tools. Per-agent `launch.env` reaches shells through `session.environment`, which child sessions do not inherit. The plugin asks the daemon to adopt each descendant in its first `context` hook, before its first model request.
|
||||
An agent with custom environment variables or user-configured MCP servers gets a dedicated OpenCode server. V2 supports session environment, but its MCP configuration remains location-scoped, so separate servers still prevent one agent from changing another agent's MCP setup. Configure custom MCP with `mcp.add`; do not follow it with `mcp.connect`, which only toggles config-backed servers.
|
||||
|
||||
OpenCode owns user message IDs. Do not pass Paseo-generated IDs to OpenCode prompt APIs; let OpenCode create `msg*` IDs and record the user timeline item from the `message.updated` event.
|
||||
|
||||
|
||||
+63
-11
@@ -5,15 +5,9 @@ Agent chat delivery has two paths:
|
||||
1. **Live stream** — `agent_stream` WebSocket messages for immediacy. These may be delta-shaped lifecycle updates.
|
||||
2. **Authoritative history** — `fetch_agent_timeline_request` for correctness. This always returns full projected timeline items, never lifecycle deltas.
|
||||
|
||||
The daemon retains projected items in memory. Each source event advances the stream sequence,
|
||||
then replaces the previous tool state or merges into the current text item. Intermediate payloads
|
||||
are never retained for history or catch-up. Provider history is the durable transcript authority
|
||||
and rebuilds the projection when an agent resumes.
|
||||
|
||||
Pagination bounds each read, not total resident history. Active and idle agents retain their
|
||||
projected transcript; archive releases it and later history reads rebuild it from the provider.
|
||||
Streaming overhead must remain proportional to the retained transcript. Cumulative text snapshots
|
||||
must be released after their deltas have been consumed.
|
||||
Pagination bounds each read, not total resident history. Streaming overhead must remain
|
||||
proportional to the retained transcript. Cumulative text snapshots must be released after their
|
||||
deltas have been consumed.
|
||||
|
||||
The invariants are:
|
||||
|
||||
@@ -32,6 +26,45 @@ bounded item is used for runtime timeline rows and live stream events. Provider
|
||||
applies the same rule so reopening an agent cannot restore an oversized payload. Fetches apply it
|
||||
again to assistant and reasoning rows the projection merges from many chunks.
|
||||
|
||||
## Owned history
|
||||
|
||||
The daemon owns each agent's history in `AgentTimeline`
|
||||
(`packages/server/src/server/agent/timeline/`): one ordered history per agent, with each provider
|
||||
child's descriptor and history in a child scope of the same agent. Each source event advances the
|
||||
stream sequence, then replaces the previous tool state or merges into the current text item.
|
||||
Intermediate payloads are never retained for history or catch-up.
|
||||
|
||||
History is append-only: rewind, import, reload and archive never delete or rewrite a row. Only
|
||||
deleting the agent, or a provider removing one of its own children, deletes history.
|
||||
|
||||
- **Rewind** retires a range of rows. They leave the conversation and stay stored, in the same
|
||||
epoch. See [Rewind retires rows](#rewind-retires-rows).
|
||||
- **Provider history** is imported only into an agent that has no history. After that, resume
|
||||
does not read it. Reload agent and Unarchive require the provider history to start with the
|
||||
same prompt IDs and text in order. They then append whole new turns, starting at the next
|
||||
prompt. Existing replies, including partial replies, stay as recorded. If the prompts differ,
|
||||
for example because the provider stored expanded attachment text, the chat stays unchanged and
|
||||
Paseo reports a mismatch. A provider child Paseo already holds, listed or retired, is never imported again.
|
||||
- **Archive and reload** keep the history and the provider children. An archived chat reads them
|
||||
without its provider. Deleting the agent deletes its history and every child's, retired ones
|
||||
included.
|
||||
|
||||
`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 only backend keeps everything in
|
||||
memory, so a daemon restart loses the owned history: the next resume imports provider history into
|
||||
a new epoch, and clients take the destructive reset below. Rewinds retired before the restart come
|
||||
back if the provider history still holds them. Retained history costs memory for every loaded,
|
||||
closed or archived agent until the daemon exits or the agent is deleted.
|
||||
|
||||
An open rewind is stored with the history. Resuming an agent whose history holds one settles it
|
||||
before the agent takes prompts: a recorded provider cut is committed, and an unknown outcome is
|
||||
judged from the resumed provider history. When that history proves nothing, the rewind stays open
|
||||
and the agent refuses prompts with the unknown-outcome error.
|
||||
|
||||
## Presence is not delivery
|
||||
|
||||
Client heartbeat reports presence:
|
||||
@@ -168,7 +201,7 @@ or retry backoff. This cannot keep a mobile socket alive after the operating sys
|
||||
bookkeeping without replacing timeline arrays, preserving an upward-scrolled viewport.
|
||||
- When the page overlaps or is adjacent to the local end cursor, only projected items newer than
|
||||
that cursor are applied. Already-covered rows are not replayed.
|
||||
- A true middle gap, epoch change, or rewind atomically replaces stale canonical history with the
|
||||
- A true middle gap or epoch change atomically replaces stale canonical history with the
|
||||
latest tail. The replacement reconciles positioned live rows beyond its coverage and unresolved
|
||||
local submissions; it never retains two discontiguous canonical ranges.
|
||||
|
||||
@@ -181,6 +214,24 @@ history replay. The pending approval UI can hide that tool from presentation, bu
|
||||
must retain its position. Creating a new history card on rejection places it after the prompt that
|
||||
rejected it; changing steer-event ordering would also put new assistant output before that prompt.
|
||||
|
||||
## Rewind retires rows
|
||||
|
||||
A conversation rewind commits a retirement `{ seq, retireFromSeq }`: active rows anchored in
|
||||
`[retireFromSeq, seq)` leave the conversation, and `seq` is the retirement's own position in the
|
||||
sequence. The provider children spawned by retired tool calls, and their descendants, are retired
|
||||
in the same commit. They leave the listing, keep their history, and drop late provider events.
|
||||
|
||||
Clients learn of a retirement live through `agent.timeline.rewind`, and on pages through
|
||||
`retirements`, which lists the retirements whose `seq` lies inside the page's span. The client
|
||||
drops the rows it holds in that range; rows without a timeline position are unechoed local sends
|
||||
and stay. Retired ranges and the retirement's `seq` count as covered, so forward cursors advance
|
||||
through them. Tail, before and prompt-jump pages are served from active rows, so one served before
|
||||
a retirement the client already applied is stale and is refetched (`viewed-timeline-sync.ts`).
|
||||
|
||||
Clients without `timeline_rewind_operations` cannot drop retired rows. For them the session derives
|
||||
a wire epoch that changes with each retirement, so they take the destructive replacement they
|
||||
always took on rewind. The shim is tagged `COMPAT(timelineRewindOperations)`.
|
||||
|
||||
## Provider child history
|
||||
|
||||
Child transcripts use the same projected-page reconciliation as the main conversation. The client
|
||||
@@ -345,7 +396,7 @@ the draft-create handoff is the one boundary that also permits the legacy canoni
|
||||
arrived first. Generic reducers and consumers do not reimplement message identity matching.
|
||||
|
||||
Ordinary bootstrap, same-epoch reset, and catch-up replacement preserve unmatched locally submitted
|
||||
rows because a provider may never echo them. A known epoch change or rewind replaces history and
|
||||
rows because a provider may never echo them. A known epoch change replaces history and
|
||||
drops acknowledged local rows omitted by the new canonical epoch; every transaction not yet
|
||||
acknowledged by the provider, and no other local row, crosses that destructive boundary. A cold
|
||||
reset without an existing epoch is destructive because the client has no continuity anchor.
|
||||
@@ -361,6 +412,7 @@ canonical assistant prefix, it stays in the head lane. No row may be returned in
|
||||
|
||||
## Relevant code
|
||||
|
||||
- Server owned history: `packages/server/src/server/agent/timeline/`
|
||||
- Server live stream forwarding: `packages/server/src/server/session.ts`
|
||||
- App sync planning: `packages/app/src/timeline/timeline-sync-plan.ts`
|
||||
- App viewed-agent synchronization: `packages/app/src/timeline/viewed-timeline-sync.ts`
|
||||
|
||||
@@ -13,6 +13,13 @@ import {
|
||||
import { expectNearBottom, scrollChatAwayFromBottom } from "../support/helpers/agent-bottom-anchor";
|
||||
import { holdRewindCompletion } from "../support/helpers/agent-timeline-gate";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
import { userScrollsTimelineToHistoryStart } from "../support/helpers/timeline-pagination";
|
||||
import {
|
||||
closeWorkspaceAgentTab,
|
||||
fetchAgentArchivedAt,
|
||||
primeAdditionalPage,
|
||||
resetSeededPageState,
|
||||
} from "../support/helpers/archive-tab";
|
||||
|
||||
async function completeSubmittedTurn(
|
||||
page: Page,
|
||||
@@ -48,26 +55,102 @@ async function expectTurnCompletesNormally(
|
||||
await expectAgentIdle(page);
|
||||
}
|
||||
|
||||
async function openAgentOnAnotherClient(
|
||||
page: Page,
|
||||
agent: Awaited<ReturnType<typeof seedMockAgentWorkspace>>,
|
||||
): Promise<void> {
|
||||
await primeAdditionalPage(page);
|
||||
await resetSeededPageState(page);
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
}
|
||||
|
||||
/** The prompts the chat shows, in order, each exactly once. */
|
||||
async function expectPrompts(page: Page, prompts: string[]): Promise<void> {
|
||||
const messages = page.getByTestId("user-message");
|
||||
await expect(messages).toHaveCount(prompts.length);
|
||||
await expect(messages).toContainText(prompts);
|
||||
}
|
||||
|
||||
async function reloadAgentFromTabMenu(page: Page, agentId: string): Promise<void> {
|
||||
const tabId = `workspace-tab-agent_${agentId}`;
|
||||
await page.getByTestId(tabId).filter({ visible: true }).first().click({ button: "right" });
|
||||
await page.getByTestId(`workspace-tab-context-agent_${agentId}-reload-agent`).click();
|
||||
}
|
||||
|
||||
async function archiveAgentByClosingTab(
|
||||
page: Page,
|
||||
agent: Awaited<ReturnType<typeof seedMockAgentWorkspace>>,
|
||||
): Promise<void> {
|
||||
await closeWorkspaceAgentTab(page, agent.agentId);
|
||||
await expect.poll(() => fetchAgentArchivedAt(agent.client, agent.agentId)).not.toBeNull();
|
||||
}
|
||||
|
||||
async function unarchiveAgent(page: Page): Promise<void> {
|
||||
await page.getByRole("button", { name: "Unarchive", exact: true }).click();
|
||||
await expect(page.getByText("This agent is archived", { exact: true })).toHaveCount(0, {
|
||||
timeout: 30_000,
|
||||
});
|
||||
}
|
||||
|
||||
async function expectToast(page: Page, message: string): Promise<void> {
|
||||
await expect(page.getByTestId("app-toast-message")).toHaveText(message, { timeout: 30_000 });
|
||||
}
|
||||
|
||||
// The mock provider's resumed session holds no history, so it never matches what Paseo shows.
|
||||
const UNSYNCED_RELOAD =
|
||||
"Reloaded agent, but the provider's history doesn't match this chat, so it wasn't synced";
|
||||
|
||||
/** The prompts of the whole conversation, after scrolling up through its older pages. */
|
||||
async function expectConversationPrompts(page: Page, prompts: string[]): Promise<void> {
|
||||
const messages = page.getByTestId("user-message");
|
||||
await expect
|
||||
.poll(async () => {
|
||||
await userScrollsTimelineToHistoryStart(page);
|
||||
return await messages.count();
|
||||
})
|
||||
.toBe(prompts.length);
|
||||
await expect(messages).toContainText(prompts);
|
||||
}
|
||||
|
||||
// A row React remounts loses this attribute; one that stays mounted keeps it.
|
||||
async function markMounted(row: Locator): Promise<void> {
|
||||
await row.evaluate((element) => element.setAttribute("data-e2e-mounted", "before-rewind"));
|
||||
}
|
||||
|
||||
async function expectStillMounted(row: Locator): Promise<void> {
|
||||
await expect(row).toHaveAttribute("data-e2e-mounted", "before-rewind");
|
||||
}
|
||||
|
||||
test.describe("Agent message rewind", () => {
|
||||
test("rewinds a submitted prompt without replaying history and preserves a human draft", async ({
|
||||
test("rewinds a prompt in place on every open client and keeps a human draft", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(90_000);
|
||||
test.setTimeout(150_000);
|
||||
const retainedPrompt = "Keep this completed turn after rewind.";
|
||||
const rewoundPrompt = "Remove this completed turn after rewind.";
|
||||
const nextPrompt = "Continue after the rewind.";
|
||||
const preservedDraft = "Keep this human draft after rewind.";
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "message-rewind-roundtrip-",
|
||||
title: "Message rewind roundtrip",
|
||||
model: "ten-second-stream",
|
||||
});
|
||||
const otherClient = await page.context().newPage();
|
||||
|
||||
try {
|
||||
const rewindCompletion = await holdRewindCompletion(page, agent.agentId);
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
await completeSubmittedTurn(page, agent, retainedPrompt);
|
||||
const retainedMessage = await completeSubmittedTurn(page, agent, retainedPrompt);
|
||||
const userMessage = await completeSubmittedTurn(page, agent, rewoundPrompt);
|
||||
|
||||
await test.step("a second client opens the same chat", async () => {
|
||||
await openAgentOnAnotherClient(otherClient, agent);
|
||||
await expectPrompts(otherClient, [retainedPrompt, rewoundPrompt]);
|
||||
});
|
||||
|
||||
await markMounted(retainedMessage);
|
||||
await scrollChatAwayFromBottom(page, {
|
||||
deltaY: -900,
|
||||
minDistanceFromBottom: 300,
|
||||
@@ -76,19 +159,92 @@ test.describe("Agent message rewind", () => {
|
||||
await blurComposerInput(page);
|
||||
rewindCompletion.clearTimelineStreamCount();
|
||||
|
||||
const rewind = rewindConversation(page, userMessage, rewoundPrompt);
|
||||
await rewindCompletion.waitForDelayedResponse();
|
||||
await expect(page.getByTestId("rewind-menu-conversation")).toBeDisabled();
|
||||
expect(rewindCompletion.timelineStreamCount()).toBe(0);
|
||||
rewindCompletion.release();
|
||||
await rewind;
|
||||
await test.step("the rewind stays pending until the daemon answers", async () => {
|
||||
const rewind = rewindConversation(page, userMessage, rewoundPrompt);
|
||||
await rewindCompletion.waitForDelayedResponse();
|
||||
await expect(page.getByTestId("rewind-menu-conversation")).toBeDisabled();
|
||||
expect(rewindCompletion.timelineStreamCount()).toBe(0);
|
||||
rewindCompletion.release();
|
||||
await rewind;
|
||||
});
|
||||
|
||||
await expect(page.getByTestId("user-message").filter({ hasText: rewoundPrompt })).toHaveCount(
|
||||
0,
|
||||
);
|
||||
await expectComposerDraft(page, preservedDraft);
|
||||
await expectComposerNotFocused(page);
|
||||
await expectNearBottom(page);
|
||||
await test.step("the rewound turn leaves without reloading the chat", async () => {
|
||||
await expectPrompts(page, [retainedPrompt]);
|
||||
await expectStillMounted(retainedMessage);
|
||||
expect(rewindCompletion.timelineFetchCount()).toBe(0);
|
||||
await expectComposerDraft(page, preservedDraft);
|
||||
await expectComposerNotFocused(page);
|
||||
await expectNearBottom(page);
|
||||
await expectPrompts(otherClient, [retainedPrompt]);
|
||||
});
|
||||
|
||||
await test.step("the next prompt appears once on both clients", async () => {
|
||||
await completeSubmittedTurn(otherClient, agent, nextPrompt);
|
||||
await expectPrompts(otherClient, [retainedPrompt, nextPrompt]);
|
||||
await expectPrompts(page, [retainedPrompt, nextPrompt]);
|
||||
});
|
||||
|
||||
await test.step("a reconnecting client loads the rewound conversation", async () => {
|
||||
await otherClient.reload();
|
||||
await expectPrompts(otherClient, [retainedPrompt, nextPrompt]);
|
||||
});
|
||||
} finally {
|
||||
await otherClient.close();
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps the rewound conversation through Reload agent, archive and unarchive", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(150_000);
|
||||
const keptPrompt = "Keep this turn through reload and archive.";
|
||||
const rewoundPrompt = "Rewind this turn before reloading.";
|
||||
const nextPrompt = "Continue after the rewind, then reload.";
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "message-rewind-reload-archive-",
|
||||
title: "Message rewind reload archive",
|
||||
model: "ten-second-stream",
|
||||
});
|
||||
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
await completeSubmittedTurn(page, agent, keptPrompt);
|
||||
const rewound = await completeSubmittedTurn(page, agent, rewoundPrompt);
|
||||
await rewindConversation(page, rewound, rewoundPrompt);
|
||||
await expectPrompts(page, [keptPrompt]);
|
||||
await completeSubmittedTurn(page, agent, nextPrompt);
|
||||
await expectPrompts(page, [keptPrompt, nextPrompt]);
|
||||
|
||||
await test.step("Reload agent keeps the chat and says the provider's history was not synced", async () => {
|
||||
await reloadAgentFromTabMenu(page, agent.agentId);
|
||||
await expectToast(page, UNSYNCED_RELOAD);
|
||||
await expectPrompts(page, [keptPrompt, nextPrompt]);
|
||||
await expectComposerVisible(page);
|
||||
});
|
||||
|
||||
await test.step("the archived chat shows the rewound conversation", async () => {
|
||||
await archiveAgentByClosingTab(page, agent);
|
||||
await openAgentRoute(page, agent);
|
||||
await expect(page.getByText("This agent is archived", { exact: true })).toBeVisible({
|
||||
timeout: 30_000,
|
||||
});
|
||||
await expectConversationPrompts(page, [keptPrompt, nextPrompt]);
|
||||
});
|
||||
|
||||
await test.step("unarchiving keeps the rewound conversation", async () => {
|
||||
await unarchiveAgent(page);
|
||||
await expectToast(page, UNSYNCED_RELOAD);
|
||||
await expectComposerVisible(page);
|
||||
await expectConversationPrompts(page, [keptPrompt, nextPrompt]);
|
||||
});
|
||||
|
||||
await test.step("a reconnecting client loads the same conversation", async () => {
|
||||
await page.reload();
|
||||
await expectComposerVisible(page);
|
||||
await expectConversationPrompts(page, [keptPrompt, nextPrompt]);
|
||||
});
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
|
||||
@@ -757,161 +757,6 @@ test("pasting an assistant selection preserves literal underscores and authored
|
||||
}
|
||||
});
|
||||
|
||||
const QUOTE_BODY = [
|
||||
"Draft for the team: **ship it** with [the notes](https://example.com/notes).",
|
||||
"",
|
||||
"> Nested reply.",
|
||||
"",
|
||||
"```ts",
|
||||
"const quoted = 1;",
|
||||
"```",
|
||||
"",
|
||||
"```mermaid",
|
||||
"flowchart LR",
|
||||
" Start --> Done",
|
||||
"```",
|
||||
"",
|
||||
"Thanks!",
|
||||
].join("\n");
|
||||
|
||||
const QUOTE_MARKDOWN = [
|
||||
"Text before the quote.",
|
||||
"",
|
||||
...QUOTE_BODY.split("\n").map((line) => (line ? `> ${line}` : ">")),
|
||||
"",
|
||||
"> [!NOTE]",
|
||||
"> Heads up before you paste.",
|
||||
"",
|
||||
"Text after the quote.",
|
||||
].join("\n");
|
||||
|
||||
function assistantQuote(page: Page, index: number): Locator {
|
||||
return assistantMessageBlocks(page).getByRole("blockquote").nth(index);
|
||||
}
|
||||
|
||||
/** A quote's own control is its first, ahead of any nested quote's. */
|
||||
function quoteCopyControl(quote: Locator): Locator {
|
||||
return quote.getByRole("button", { name: "Copy quote" }).first();
|
||||
}
|
||||
|
||||
async function copyQuote(quote: Locator): Promise<void> {
|
||||
await quote.hover();
|
||||
await quoteCopyControl(quote).click();
|
||||
await expect(quote.getByRole("button", { name: "Copied" })).toBeVisible();
|
||||
}
|
||||
|
||||
async function pasteIntoPlainAndRichFields(page: Page): Promise<{ plain: Locator; rich: Locator }> {
|
||||
await page.evaluate(() => {
|
||||
const fields = document.createElement("div");
|
||||
fields.style.cssText = "position: fixed; bottom: 0; left: 0; z-index: 10000; background: white";
|
||||
const plainText = document.createElement("textarea");
|
||||
plainText.setAttribute("aria-label", "Plain text paste");
|
||||
const richText = document.createElement("div");
|
||||
richText.contentEditable = "true";
|
||||
richText.setAttribute("role", "textbox");
|
||||
richText.setAttribute("aria-label", "Rich text paste");
|
||||
fields.append(plainText, richText);
|
||||
document.body.append(fields);
|
||||
});
|
||||
const plain = page.getByRole("textbox", { name: "Plain text paste" });
|
||||
await plain.focus();
|
||||
await page.keyboard.press("ControlOrMeta+v");
|
||||
const rich = page.getByRole("textbox", { name: "Rich text paste" });
|
||||
await rich.focus();
|
||||
await page.keyboard.press("ControlOrMeta+v");
|
||||
return { plain, rich };
|
||||
}
|
||||
|
||||
test("a quote's copy control copies only that quote's body", async ({ context, page }) => {
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "assistant-quote-copy-",
|
||||
title: "Assistant quote copy",
|
||||
initialPrompt: "Render the quote fixture.",
|
||||
featureValues: { mockAssistantResponse: QUOTE_MARKDOWN },
|
||||
});
|
||||
|
||||
try {
|
||||
await allowRichClipboard(context);
|
||||
await agent.client.waitForAgentUpsert(
|
||||
agent.agentId,
|
||||
(snapshot) => snapshot.status === "idle",
|
||||
30_000,
|
||||
);
|
||||
await openAgentRoute(page, agent);
|
||||
const quote = assistantQuote(page, 0);
|
||||
const nested = assistantQuote(page, 1);
|
||||
await expect(quote).toContainText("Thanks!");
|
||||
|
||||
await test.step("an admonition has no copy control", async () => {
|
||||
await expect(assistantMessageBlocks(page)).toContainText("Heads up before you paste.");
|
||||
await expect(
|
||||
assistantMessageBlocks(page).getByRole("button", { name: "Copy quote" }),
|
||||
).toHaveCount(2);
|
||||
});
|
||||
|
||||
await test.step("the control appears on hover or keyboard focus", async () => {
|
||||
const control = quoteCopyControl(quote);
|
||||
await expect(control).toHaveCSS("opacity", "0");
|
||||
await quote.hover();
|
||||
await expect(control).toHaveCSS("opacity", "1");
|
||||
await page.mouse.move(0, 0);
|
||||
await expect(control).toHaveCSS("opacity", "0");
|
||||
await control.focus();
|
||||
await expect(control).toHaveCSS("opacity", "1");
|
||||
await control.blur();
|
||||
});
|
||||
|
||||
await test.step("copying the quote takes its body, with a diagram as its fence", async () => {
|
||||
await expect(quote.getByRole("img", { name: "Diagram" })).toBeVisible({ timeout: 30_000 });
|
||||
await copyQuote(quote);
|
||||
const copied = await readRichClipboard(page);
|
||||
expect(copied.plainText).toBe(QUOTE_BODY);
|
||||
expect(copied.html).toContain("<strong>ship it</strong>");
|
||||
expect(copied.html).toContain("<blockquote>");
|
||||
});
|
||||
|
||||
await test.step("the copy pastes as Markdown and as rich text", async () => {
|
||||
const { plain, rich } = await pasteIntoPlainAndRichFields(page);
|
||||
await expect(plain).toHaveValue(QUOTE_BODY);
|
||||
await expect(rich.locator("strong")).toHaveText("ship it");
|
||||
await expect(rich.getByRole("link", { name: "the notes" })).toHaveAttribute(
|
||||
"href",
|
||||
"https://example.com/notes",
|
||||
);
|
||||
await expect(rich).not.toContainText("Text before the quote.");
|
||||
});
|
||||
|
||||
await test.step("a nested quote copies only itself", async () => {
|
||||
await copyQuote(nested);
|
||||
await expect
|
||||
.poll(async () => (await readRichClipboard(page)).plainText)
|
||||
.toBe("Nested reply.");
|
||||
});
|
||||
|
||||
await test.step("a code block in the quote keeps its own copy", async () => {
|
||||
const code = quote.getByText("const quoted = 1;", { exact: true });
|
||||
await code.hover();
|
||||
await quote.getByRole("button", { name: "Copy code" }).first().click();
|
||||
await expect.poll(() => readPlainClipboard(page)).toBe("const quoted = 1;");
|
||||
});
|
||||
|
||||
await test.step("a phone-sized layout shows the control above the full-width text", async () => {
|
||||
await page.mouse.move(0, 0);
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
const control = quoteCopyControl(quote);
|
||||
await expect(control).toHaveCSS("opacity", "1");
|
||||
const controlBox = await control.boundingBox();
|
||||
const firstLine = await quote.getByText(/^Draft for the team/).boundingBox();
|
||||
expect(controlBox && firstLine).toBeTruthy();
|
||||
// The text starts below the control instead of wrapping short of it.
|
||||
expect(firstLine!.y).toBeGreaterThanOrEqual(controlBox!.y + controlBox!.height);
|
||||
expect(firstLine!.x + firstLine!.width).toBeGreaterThan(controlBox!.x);
|
||||
});
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("copying a selection across an assistant image keeps its Markdown source and alt text", async ({
|
||||
context,
|
||||
page,
|
||||
|
||||
@@ -4,7 +4,6 @@ import {
|
||||
addConnectedHostAndReload,
|
||||
chooseHostBadgeDisplay,
|
||||
chooseHostColor,
|
||||
chooseHostIcon,
|
||||
expectHostAppearancePreview,
|
||||
expectHostBadgeIconOnly,
|
||||
expectHostBadgeName,
|
||||
@@ -116,21 +115,12 @@ test("customizes a host badge and preserves its appearance after reload", async
|
||||
expect(widths.content).toBeLessThanOrEqual(widths.client);
|
||||
});
|
||||
|
||||
await test.step("preview a color and icon and apply them to the sidebar badge and host popover", async () => {
|
||||
await test.step("preview a color and apply it to the sidebar badge", async () => {
|
||||
await openHostAppearanceSettings(page, badge.serverId);
|
||||
await chooseHostColor(page, "Teal");
|
||||
await chooseHostIcon(page, "Laptop");
|
||||
await expectHostAppearancePreview(page, { serverId: badge.serverId, hostName, color: "teal" });
|
||||
await leaveHostAppearanceSettings(page);
|
||||
await expectHostBadgeTinted(page, { ...badge, hostName, color: "teal" });
|
||||
|
||||
await page.getByTestId("sidebar-hosts-trigger").click();
|
||||
const hostRow = page.getByTestId(`sidebar-host-row-${badge.serverId}`);
|
||||
await expect(hostRow).toBeVisible();
|
||||
await expect(hostRow).toContainText("Direct");
|
||||
await expect(hostRow).toContainText(/\d+(?:\.\d+)?(?:µs|ms|s)/);
|
||||
await expect(hostRow).not.toContainText(/agents?/i);
|
||||
await page.keyboard.press("Escape");
|
||||
});
|
||||
|
||||
await test.step("keep the icon-only preference through reload", async () => {
|
||||
@@ -155,30 +145,3 @@ test("customizes a host badge and preserves its appearance after reload", async
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
base(
|
||||
"activates Add host from the sidebar host picker via focus+Enter and Arrow+Enter",
|
||||
async ({ page }) => {
|
||||
await gotoAppShell(page);
|
||||
const trigger = page.getByTestId("sidebar-hosts-trigger");
|
||||
await expect(trigger).toBeVisible();
|
||||
|
||||
// Focus + Enter on Add host must open the Add connection dialog rather than selecting the active host.
|
||||
const addConnectionDialog = page.getByRole("dialog").filter({ hasText: "Add connection" });
|
||||
await trigger.click();
|
||||
const addHostButton = page.getByRole("button", { name: "Add host", exact: true });
|
||||
await expect(addHostButton).toBeVisible();
|
||||
await addHostButton.focus();
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(addConnectionDialog).toBeVisible();
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(addConnectionDialog).toBeHidden();
|
||||
|
||||
// ArrowDown + Enter must also reach Add host from the host list.
|
||||
await trigger.click();
|
||||
await expect(addHostButton).toBeVisible();
|
||||
await page.keyboard.press("ArrowDown");
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(addConnectionDialog).toBeVisible();
|
||||
},
|
||||
);
|
||||
|
||||
@@ -235,7 +235,7 @@ test.describe("Rewind sheet", () => {
|
||||
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
|
||||
await expect(userMessage(page, secondPrompt)).toHaveCount(0);
|
||||
await expect(page.getByText("Cycle 1", { exact: true })).toHaveCount(0);
|
||||
await expectUserMessageCount(page, 1);
|
||||
await expectUserMessageCount(page, 0);
|
||||
await expectComposerDraft(page, firstPrompt);
|
||||
await expectComposerFocused(page);
|
||||
|
||||
@@ -243,7 +243,7 @@ test.describe("Rewind sheet", () => {
|
||||
await expectUserMessageVisible(page, replacementPrompt);
|
||||
await expect(userMessage(page, secondPrompt)).toHaveCount(0);
|
||||
await expect(page.getByText("Cycle 1", { exact: true })).toHaveCount(0);
|
||||
await expectUserMessageCount(page, 2);
|
||||
await expectUserMessageCount(page, 1);
|
||||
|
||||
await fillComposerDraft(page, "");
|
||||
await composerLocator(page).evaluate((element) => element.blur());
|
||||
@@ -254,7 +254,19 @@ test.describe("Rewind sheet", () => {
|
||||
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
|
||||
await expectComposerDraft(page, "");
|
||||
await expectComposerNotFocused(page);
|
||||
await expectUserMessageCount(page, 2);
|
||||
await expectUserMessageCount(page, 1);
|
||||
|
||||
const preservedDraft = "Keep this human draft after rewind.";
|
||||
await fillComposerDraft(page, preservedDraft);
|
||||
await composerLocator(page).evaluate((element) => element.blur());
|
||||
await userMessage(page, replacementPrompt).hover();
|
||||
await page.getByTestId("rewind-menu-trigger").last().click();
|
||||
await expect(page.getByTestId("rewind-menu-content")).toBeVisible();
|
||||
await selectRewindOption(page, "Rewind files");
|
||||
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
|
||||
await expectComposerDraft(page, preservedDraft);
|
||||
await expectComposerNotFocused(page);
|
||||
await expectUserMessageCount(page, 1);
|
||||
|
||||
await fillComposerDraft(page, "");
|
||||
await composerLocator(page).evaluate((element) => element.blur());
|
||||
@@ -265,7 +277,7 @@ test.describe("Rewind sheet", () => {
|
||||
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
|
||||
await expectComposerDraft(page, replacementPrompt);
|
||||
await expectComposerFocused(page);
|
||||
await expectUserMessageCount(page, 1);
|
||||
await expectUserMessageCount(page, 0);
|
||||
} finally {
|
||||
await session.cleanup();
|
||||
}
|
||||
|
||||
@@ -65,7 +65,8 @@ import {
|
||||
openSettingsHostSection,
|
||||
removeCurrentHostFromSettings,
|
||||
openSidebarHostPicker,
|
||||
sidebarHostRowButton,
|
||||
sidebarHostSettingsButton,
|
||||
expectStandaloneSidebarHostSettingsButton,
|
||||
activateSidebarHostSettingsWithKeyboard,
|
||||
bindCommandCenterToEnter,
|
||||
} from "../support/helpers/settings";
|
||||
@@ -191,16 +192,17 @@ test.describe("Settings sidebar scroll position", () => {
|
||||
});
|
||||
|
||||
test.describe("Settings sidebar navigation", () => {
|
||||
test("the sidebar host row opens Overview in one click", async ({ page, withWorkspace }) => {
|
||||
test("the sidebar host gear opens Overview in one click", async ({ page, withWorkspace }) => {
|
||||
const workspace = await withWorkspace({ prefix: "sidebar-host-settings-" });
|
||||
await openWorkspace(page, workspace);
|
||||
await openSidebarHostPicker(page);
|
||||
await sidebarHostRowButton(page).click();
|
||||
await expectStandaloneSidebarHostSettingsButton(page);
|
||||
await sidebarHostSettingsButton(page).click();
|
||||
|
||||
await expectAppRoute(page, buildSettingsHostSectionRoute(getServerId(), "host"));
|
||||
});
|
||||
|
||||
test("Enter opens the active sidebar host row", async ({ page, withWorkspace }) => {
|
||||
test("Enter opens the focused sidebar host gear", async ({ page, withWorkspace }) => {
|
||||
await bindCommandCenterToEnter(page);
|
||||
const workspace = await withWorkspace({ prefix: "keyboard-host-settings-" });
|
||||
await openWorkspace(page, workspace);
|
||||
@@ -564,7 +566,7 @@ test.describe("Settings — compact master-detail", () => {
|
||||
await openWorkspace(page, workspace);
|
||||
await page.getByRole("button", { name: "Open menu", exact: true }).click();
|
||||
await page.getByTestId("sidebar-hosts-trigger").click();
|
||||
await sidebarHostRowButton(page).click();
|
||||
await page.getByRole("button", { name: /Open .* settings/ }).click();
|
||||
|
||||
await expectAppRoute(page, buildSettingsHostSectionRoute(getServerId(), "host"));
|
||||
await expect(page.getByText("Overview", { exact: true })).toBeVisible();
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import path from "node:path";
|
||||
import {
|
||||
expectTimelinePromptVisible,
|
||||
holdOlderHistoryPages,
|
||||
scrollTimelineRowIntoView,
|
||||
userScrollsTimelineToHistoryStart,
|
||||
waitForTimelineGeometryToSettle,
|
||||
} from "../support/helpers/timeline-pagination";
|
||||
import { getActiveTabTestId } from "../support/helpers/launcher";
|
||||
import type { Page, Locator } from "@playwright/test";
|
||||
@@ -493,39 +491,6 @@ async function seedWholeTurnHistory() {
|
||||
return agent;
|
||||
}
|
||||
|
||||
/** Read every command across the scroll window, without requiring offscreen rows to mount. */
|
||||
async function expectExpandedCommandsReadable(page: Page, count: number) {
|
||||
const timeline = page.getByTestId("agent-chat-scroll");
|
||||
const commands = new Set<number>();
|
||||
await timeline.hover();
|
||||
await waitForTimelineGeometryToSettle(page);
|
||||
for (let step = 0; step < count && commands.size < count; step += 1) {
|
||||
const labels = await timeline
|
||||
.getByRole("button", { name: /echo stress-\d+/ })
|
||||
.allTextContents();
|
||||
for (const label of labels) {
|
||||
const command = /echo stress-(\d+)/.exec(label);
|
||||
if (command) commands.add(Number(command[1]));
|
||||
}
|
||||
if (commands.size < count) {
|
||||
await page.mouse.wheel(0, 300);
|
||||
await waitForTimelineGeometryToSettle(page);
|
||||
}
|
||||
}
|
||||
expect([...commands].sort((a, b) => a - b)).toEqual(
|
||||
Array.from({ length: count }, (_, index) => index),
|
||||
);
|
||||
}
|
||||
|
||||
async function returnToExpandedSummary(page: Page, summary: Locator) {
|
||||
await page.getByTestId("agent-chat-scroll").hover();
|
||||
for (let step = 0; step < 120 && !(await summary.isVisible()); step += 1) {
|
||||
await page.mouse.wheel(0, -300);
|
||||
await waitForTimelineGeometryToSettle(page);
|
||||
}
|
||||
await scrollTimelineRowIntoView(page, summary);
|
||||
}
|
||||
|
||||
async function expectInitialFillIsConcealed(page: Page) {
|
||||
await expect(page.getByTestId("agent-initial-fill")).toBeVisible();
|
||||
await expect(page.getByTestId("agent-chat-scroll")).toHaveCSS("opacity", "0");
|
||||
@@ -599,14 +564,14 @@ test("loads complete long turns and preserves expansion while revealing older hi
|
||||
).toBeVisible();
|
||||
await expect.poll(() => rowsBetweenLatestSummaryAndReply(page)).toBe(0);
|
||||
await latest.click();
|
||||
await expectExpandedCommandsReadable(page, 120);
|
||||
await expect.poll(() => rowsBetweenLatestSummaryAndReply(page)).toBe(120);
|
||||
await userScrollsTimelineToHistoryStart(page);
|
||||
await history.expectRequestedPages(3);
|
||||
history.releasePage(3);
|
||||
await expectTimelinePromptVisible(page, "Short 4: emit 1 coalesced agent stream updates");
|
||||
await expectExpandedCommandsReadable(page, 120);
|
||||
await page.getByTestId("scroll-to-bottom-button").click();
|
||||
await expect.poll(() => rowsBetweenLatestSummaryAndReply(page)).toBe(120);
|
||||
history.expectNoRepeatedEntries();
|
||||
await returnToExpandedSummary(page, latest);
|
||||
await scrollTimelineRowIntoView(page, latest);
|
||||
await latest.click();
|
||||
await expect.poll(() => rowsBetweenLatestSummaryAndReply(page)).toBe(0);
|
||||
} finally {
|
||||
|
||||
@@ -31,6 +31,8 @@ export interface RewindCompletionGate {
|
||||
clearTimelineStreamCount(): void;
|
||||
release(): void;
|
||||
timelineStreamCount(): number;
|
||||
/** Timeline reads this page sent since the last clear. */
|
||||
timelineFetchCount(): number;
|
||||
waitForDelayedResponse(): Promise<void>;
|
||||
}
|
||||
|
||||
@@ -186,12 +188,20 @@ export async function holdDaemonHydration(page: Page): Promise<DaemonHydrationGa
|
||||
};
|
||||
}
|
||||
|
||||
// The rewind response and the timeline change it causes; the change removes the rewound row too.
|
||||
const REWIND_COMPLETION_MESSAGES = new Set([
|
||||
"agent.rewind.response",
|
||||
"agent.timeline.rewind",
|
||||
"agent.timeline.replacement",
|
||||
]);
|
||||
|
||||
export async function holdRewindCompletion(
|
||||
page: Page,
|
||||
agentId: string,
|
||||
): Promise<RewindCompletionGate> {
|
||||
let released = false;
|
||||
let timelineStreamCount = 0;
|
||||
let timelineFetchCount = 0;
|
||||
const delayedForwards: Array<() => void> = [];
|
||||
let resolveDelayedResponse: (() => void) | null = null;
|
||||
const delayedResponse = new Promise<void>((resolve) => {
|
||||
@@ -200,7 +210,16 @@ export async function holdRewindCompletion(
|
||||
|
||||
await page.routeWebSocket(daemonWsRoutePattern(), (ws) => {
|
||||
const server = ws.connectToServer();
|
||||
ws.onMessage((message) => server.send(message));
|
||||
ws.onMessage((message) => {
|
||||
const sessionMessage = getSessionMessage(message);
|
||||
if (
|
||||
sessionMessage?.type === "fetch_agent_timeline_request" &&
|
||||
sessionMessage.agentId === agentId
|
||||
) {
|
||||
timelineFetchCount += 1;
|
||||
}
|
||||
server.send(message);
|
||||
});
|
||||
server.onMessage((message) => {
|
||||
const sessionMessage = getSessionMessage(message);
|
||||
const payload = sessionMessage ? getPayload(sessionMessage) : null;
|
||||
@@ -216,11 +235,11 @@ export async function holdRewindCompletion(
|
||||
}
|
||||
if (
|
||||
!released &&
|
||||
(sessionMessage?.type === "agent.rewind.response" ||
|
||||
sessionMessage?.type === "agent.timeline.replacement") &&
|
||||
sessionMessage &&
|
||||
REWIND_COMPLETION_MESSAGES.has(String(sessionMessage.type)) &&
|
||||
payload?.agentId === agentId
|
||||
) {
|
||||
// The replacement also signals completion and removes the rewound row/menu.
|
||||
// The rewind also signals completion and removes the rewound row/menu.
|
||||
// Hold it with the response so the pending-state assertion observes a pending rewind.
|
||||
delayedForwards.push(() => ws.send(message));
|
||||
if (sessionMessage.type === "agent.rewind.response") resolveDelayedResponse?.();
|
||||
@@ -233,6 +252,7 @@ export async function holdRewindCompletion(
|
||||
return {
|
||||
clearTimelineStreamCount() {
|
||||
timelineStreamCount = 0;
|
||||
timelineFetchCount = 0;
|
||||
},
|
||||
release() {
|
||||
released = true;
|
||||
@@ -241,6 +261,7 @@ export async function holdRewindCompletion(
|
||||
}
|
||||
},
|
||||
timelineStreamCount: () => timelineStreamCount,
|
||||
timelineFetchCount: () => timelineFetchCount,
|
||||
waitForDelayedResponse: () => delayedResponse,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -132,10 +132,7 @@ export async function waitForConnectedHost(
|
||||
): Promise<void> {
|
||||
await page.getByTestId("sidebar-hosts-trigger").click();
|
||||
const host = page.getByTestId(`sidebar-host-row-${input.serverId}`);
|
||||
const escapedEndpoint = input.endpoint.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
// Local daemons render "Local" without repeating localhost:<port>; remote hosts render the endpoint.
|
||||
await expect(host).toContainText(new RegExp(`${escapedEndpoint}|Local`), { timeout: 30_000 });
|
||||
await expect(host).toContainText(/\d+(?:\.\d+)?(?:µs|ms|s)/, { timeout: 30_000 });
|
||||
await expect(host).toContainText(input.endpoint, { timeout: 30_000 });
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(host).not.toBeVisible();
|
||||
}
|
||||
@@ -198,12 +195,6 @@ export async function chooseHostColor(page: Page, colorName: string): Promise<vo
|
||||
await expect(page.getByRole("button", { name: `Color, ${colorName}` })).toBeVisible();
|
||||
}
|
||||
|
||||
export async function chooseHostIcon(page: Page, iconName: string): Promise<void> {
|
||||
await page.getByTestId("host-appearance-icon").click();
|
||||
await page.getByRole("menuitem", { name: iconName, exact: true }).click();
|
||||
await expect(page.getByRole("button", { name: `Icon, ${iconName}` })).toBeVisible();
|
||||
}
|
||||
|
||||
export async function chooseHostBadgeDisplay(
|
||||
page: Page,
|
||||
option: "Name" | "Icon only" | "Hidden",
|
||||
|
||||
@@ -16,8 +16,8 @@ export async function openSidebarHostPicker(page: Page) {
|
||||
await page.getByRole("button", { name: "Hosts", exact: true }).click();
|
||||
}
|
||||
|
||||
export function sidebarHostRowButton(page: Page) {
|
||||
return page.getByTestId(`sidebar-host-row-${getServerId()}`);
|
||||
export function sidebarHostSettingsButton(page: Page) {
|
||||
return page.getByRole("button", { name: `Open ${TEST_HOST_LABEL} settings`, exact: true });
|
||||
}
|
||||
|
||||
export async function bindCommandCenterToEnter(page: Page) {
|
||||
@@ -32,10 +32,20 @@ export async function bindCommandCenterToEnter(page: Page) {
|
||||
});
|
||||
}
|
||||
|
||||
export async function expectStandaloneSidebarHostSettingsButton(page: Page) {
|
||||
const gear = sidebarHostSettingsButton(page);
|
||||
await expect(gear).toBeVisible();
|
||||
expect(await gear.evaluate((button) => button.parentElement?.closest("button") === null)).toBe(
|
||||
true,
|
||||
);
|
||||
}
|
||||
|
||||
export async function activateSidebarHostSettingsWithKeyboard(page: Page) {
|
||||
const host = sidebarHostRowButton(page);
|
||||
await expect(host).toBeVisible();
|
||||
const host = page.getByRole("button", { name: TEST_HOST_LABEL, exact: true });
|
||||
await expect(host).toBeFocused();
|
||||
await page.keyboard.press("ArrowDown");
|
||||
await page.keyboard.press("Tab");
|
||||
await expect(sidebarHostSettingsButton(page)).toBeFocused();
|
||||
await page.keyboard.press("Enter");
|
||||
}
|
||||
|
||||
|
||||
@@ -40,7 +40,7 @@
|
||||
"dev:ios": "npm --prefix ../.. run build:client && cross-env APP_VARIANT=development expo run:ios",
|
||||
"build:apk": "npm --prefix ../.. run build:apk",
|
||||
"build:apk:arm64": "npm --prefix ../.. run build:apk:arm64",
|
||||
"test:android": "expo prebuild --platform android --no-install && cd android && ./gradlew :paseo-native-trace:testReleaseUnitTest :paseo-hardware-keyboard:testReleaseUnitTest :react-native-enriched-markdown:testReleaseUnitTest --tests '*InlineCodeFormattingTest' --tests '*ListRenderingTest' --tests '*TaskListInteractionTest' --tests '*ListBlockquoteMeasurementTest' --tests '*BlockquoteCopyTest' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
|
||||
"test:android": "expo prebuild --platform android --no-install && cd android && ./gradlew :paseo-native-trace:testReleaseUnitTest :paseo-hardware-keyboard:testReleaseUnitTest :react-native-enriched-markdown:testReleaseUnitTest --tests '*InlineCodeFormattingTest' --tests '*ListRenderingTest' --tests '*TaskListInteractionTest' --tests '*ListBlockquoteMeasurementTest' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
|
||||
},
|
||||
"dependencies": {
|
||||
"@codemirror/commands": "6.10.4",
|
||||
|
||||
@@ -56,6 +56,7 @@ export function ChatFind({
|
||||
agentId,
|
||||
serverId,
|
||||
epoch,
|
||||
rewindSeq,
|
||||
items,
|
||||
viewportRef,
|
||||
revealLoadedMessage,
|
||||
@@ -95,8 +96,8 @@ export function ChatFind({
|
||||
);
|
||||
const state = useSyncExternalStore(model.subscribe, model.getSnapshot, model.getSnapshot);
|
||||
useEffect(() => {
|
||||
model.updateHistory(epoch, items);
|
||||
}, [model, epoch, items]);
|
||||
model.updateHistory(epoch, items, rewindSeq);
|
||||
}, [model, epoch, items, rewindSeq]);
|
||||
useEffect(() => () => model.close(), [model]);
|
||||
useEffect(() => {
|
||||
if (!active) model.close();
|
||||
|
||||
@@ -18,7 +18,7 @@ function message(seq: number, text = "target"): StreamItem {
|
||||
kind: "assistant_message",
|
||||
text,
|
||||
timestamp: new Date(0),
|
||||
timelineCursor: { epoch: "epoch", seq },
|
||||
timelineCursor: { epoch: "epoch", seq, anchorSeq: seq },
|
||||
};
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ it("loads an older location and searches a response merged across suppressed tas
|
||||
source.map((item, index) => ({
|
||||
event: { type: "timeline" as const, provider: "claude" as const, item },
|
||||
timestamp: new Date(0),
|
||||
timelineCursor: { epoch: "epoch", seq: index + 1 },
|
||||
timelineCursor: { epoch: "epoch", seq: index + 1, anchorSeq: index + 1 },
|
||||
})),
|
||||
{ source: "canonical" },
|
||||
);
|
||||
@@ -55,7 +55,7 @@ it("loads an older location and searches a response merged across suppressed tas
|
||||
},
|
||||
async load(_epoch, seq) {
|
||||
loaded.push(seq);
|
||||
model.updateHistory("epoch", history);
|
||||
model.updateHistory("epoch", history, null);
|
||||
},
|
||||
async reveal(_id, _query, occurrence) {
|
||||
revealed.push(occurrence);
|
||||
@@ -64,7 +64,7 @@ it("loads an older location and searches a response merged across suppressed tas
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", []);
|
||||
model.updateHistory("epoch", [], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
@@ -99,7 +99,7 @@ it("skips a source-only candidate and highlights a displayed match", async () =>
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)]);
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().selectedItemId).toBe("row-2");
|
||||
@@ -129,7 +129,7 @@ it("ignores replies after closing and does not navigate", async () => {
|
||||
},
|
||||
clear() {},
|
||||
});
|
||||
model.updateHistory("epoch", [message(1)]);
|
||||
model.updateHistory("epoch", [message(1)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => calls).toEqual(["search"]);
|
||||
@@ -155,7 +155,7 @@ it("retains a failed search for retry and distinguishes failure from zero matche
|
||||
};
|
||||
const model = new ChatFindModel(operations);
|
||||
try {
|
||||
model.updateHistory("epoch", []);
|
||||
model.updateHistory("epoch", [], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("error");
|
||||
@@ -185,7 +185,7 @@ it("reports a failed timeline load as a connection failure", async () => {
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", []);
|
||||
model.updateHistory("epoch", [], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("error");
|
||||
@@ -207,24 +207,160 @@ it("reports a search result that outlived its epoch as a changed history", async
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1)]);
|
||||
model.updateHistory("epoch", [message(1)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
model.updateHistory("epoch-2", [message(1)]);
|
||||
model.updateHistory("epoch-2", [message(1)], null);
|
||||
expect(model.getSnapshot()).toMatchObject({ phase: "error", failure: "historyChanged" });
|
||||
} finally {
|
||||
model.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("reports results that a rewind took messages from as a changed history", async () => {
|
||||
const model = new ChatFindModel({
|
||||
async search() {
|
||||
return response([{ seq: 2, role: "assistant" }]);
|
||||
},
|
||||
async load() {},
|
||||
async reveal() {
|
||||
return { count: 1, occurrence: 0 };
|
||||
},
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
expect(model.getSnapshot()).toMatchObject({ selectedItemId: "row-2", count: 1 });
|
||||
// Another client rewinds the turn holding the match; the epoch stays.
|
||||
model.updateHistory("epoch", [message(1)], 3);
|
||||
expect(model.getSnapshot()).toMatchObject({
|
||||
phase: "error",
|
||||
failure: "historyChanged",
|
||||
selectedItemId: null,
|
||||
});
|
||||
} finally {
|
||||
model.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("stops a search still receiving pages when a rewind lands between them", async () => {
|
||||
let pages = 0;
|
||||
let releaseSecondPage!: () => void;
|
||||
const secondPage = new Promise<void>((resolve) => {
|
||||
releaseSecondPage = resolve;
|
||||
});
|
||||
const model = new ChatFindModel({
|
||||
async search(_query, cursor) {
|
||||
pages += 1;
|
||||
if (cursor === undefined)
|
||||
return { ...response([{ seq: 2, role: "assistant" }]), nextCursor: 2 };
|
||||
await secondPage;
|
||||
return response([{ seq: 1, role: "assistant" }]);
|
||||
},
|
||||
async load() {},
|
||||
async reveal() {
|
||||
return { count: 1, occurrence: 0 };
|
||||
},
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => pages).toBe(2);
|
||||
model.updateHistory("epoch", [message(1)], 3);
|
||||
releaseSecondPage();
|
||||
await expect.poll(() => model.getSnapshot().failure).toBe("historyChanged");
|
||||
expect(model.getSnapshot()).toMatchObject({ phase: "error", selectedItemId: null });
|
||||
} finally {
|
||||
model.close();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
["Next", "next"],
|
||||
["Previous", "previous"],
|
||||
] as const)("reports a rewind after %s as a changed history", async (_label, step) => {
|
||||
const model = new ChatFindModel({
|
||||
async search() {
|
||||
return response([
|
||||
{ seq: 1, role: "assistant" },
|
||||
{ seq: 2, role: "assistant" },
|
||||
]);
|
||||
},
|
||||
async load() {},
|
||||
async reveal() {
|
||||
return { count: 1, occurrence: 0 };
|
||||
},
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
model[step]();
|
||||
await expect.poll(() => model.getSnapshot().selectedItemId).toBe("row-2");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
model.updateHistory("epoch", [message(1)], 3);
|
||||
expect(model.getSnapshot()).toMatchObject({
|
||||
phase: "error",
|
||||
failure: "historyChanged",
|
||||
selectedItemId: null,
|
||||
});
|
||||
} finally {
|
||||
model.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("stops a pending Next when a rewind lands before it reveals", async () => {
|
||||
let reveals = 0;
|
||||
let revealSecond!: () => void;
|
||||
const secondReveal = new Promise<void>((resolve) => {
|
||||
revealSecond = resolve;
|
||||
});
|
||||
const model = new ChatFindModel({
|
||||
async search() {
|
||||
return response([
|
||||
{ seq: 1, role: "assistant" },
|
||||
{ seq: 2, role: "assistant" },
|
||||
]);
|
||||
},
|
||||
async load() {},
|
||||
async reveal() {
|
||||
reveals += 1;
|
||||
if (reveals > 1) await secondReveal;
|
||||
return { count: 1, occurrence: 0 };
|
||||
},
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
model.next();
|
||||
await expect.poll(() => reveals).toBe(2);
|
||||
model.updateHistory("epoch", [message(1)], 3);
|
||||
revealSecond();
|
||||
await expect.poll(() => model.getSnapshot().failure).toBe("historyChanged");
|
||||
expect(model.getSnapshot()).toMatchObject({ phase: "error", selectedItemId: null });
|
||||
} finally {
|
||||
model.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("can load a search location before the initial chat history has arrived", async () => {
|
||||
const model = new ChatFindModel({
|
||||
async search() {
|
||||
return response([{ seq: 1, role: "assistant" }]);
|
||||
},
|
||||
async load() {
|
||||
model.updateHistory("epoch", [message(1)]);
|
||||
model.updateHistory("epoch", [message(1)], null);
|
||||
},
|
||||
async reveal() {
|
||||
return { count: 1, occurrence: 0 };
|
||||
@@ -232,7 +368,7 @@ it("can load a search location before the initial chat history has arrived", asy
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory(null, []);
|
||||
model.updateHistory(null, [], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
@@ -260,7 +396,7 @@ it("reports the position across the whole chat and corrects it with rendered cou
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)]);
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
@@ -297,7 +433,7 @@ it("counts one match per message from a host that reports no counts", async () =
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)]);
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
|
||||
@@ -76,6 +76,10 @@ export class ChatFindModel {
|
||||
private items: StreamItem[] = [];
|
||||
private epoch: string | null = null;
|
||||
private resultEpoch: string | null = null;
|
||||
/** The latest rewind applied to the history. A rewind keeps the epoch and retires messages. */
|
||||
private rewindSeq: number | null = null;
|
||||
/** The latest rewind when the current result set's search started; undefined until a search starts. */
|
||||
private searchedRewindSeq: number | null | undefined = undefined;
|
||||
private locations: Location[] = [];
|
||||
private resolved = new Map<Location, Target>();
|
||||
private current = -1;
|
||||
@@ -113,6 +117,7 @@ export class ChatFindModel {
|
||||
this.cancel();
|
||||
this.locations = [];
|
||||
this.resultEpoch = null;
|
||||
this.searchedRewindSeq = undefined;
|
||||
this.resolved.clear();
|
||||
this.current = -1;
|
||||
this.inMessage = { occurrence: 0, count: 0 };
|
||||
@@ -144,6 +149,7 @@ export class ChatFindModel {
|
||||
});
|
||||
}
|
||||
private async search(signal: AbortSignal) {
|
||||
this.searchedRewindSeq = this.rewindSeq;
|
||||
try {
|
||||
let cursor: number | undefined;
|
||||
do {
|
||||
@@ -168,15 +174,14 @@ export class ChatFindModel {
|
||||
this.fail(error, signal);
|
||||
}
|
||||
}
|
||||
updateHistory(epoch: string | null, items: StreamItem[]) {
|
||||
if (
|
||||
this.resultEpoch !== null &&
|
||||
epoch !== null &&
|
||||
epoch !== this.resultEpoch &&
|
||||
this.state.open
|
||||
) {
|
||||
/** `rewindSeq` is the sequence number of the latest rewind applied to this history. */
|
||||
updateHistory(epoch: string | null, items: StreamItem[], rewindSeq: number | null) {
|
||||
const replaced = this.resultEpoch !== null && epoch !== null && epoch !== this.resultEpoch;
|
||||
const rewound = this.searchedRewindSeq !== undefined && rewindSeq !== this.searchedRewindSeq;
|
||||
if ((replaced || rewound) && this.state.open) {
|
||||
this.fail(new ChatFindFailureError("historyChanged"), this.abort.signal);
|
||||
}
|
||||
this.rewindSeq = rewindSeq;
|
||||
this.epoch = epoch;
|
||||
this.items = items;
|
||||
this.historyListeners.forEach((listener) => listener());
|
||||
|
||||
@@ -9,6 +9,8 @@ export interface ChatFindProps {
|
||||
agentId: string;
|
||||
serverId: string;
|
||||
epoch: string | null;
|
||||
/** The sequence number of the latest rewind applied to this history, if any. */
|
||||
rewindSeq: number | null;
|
||||
items: StreamItem[];
|
||||
viewportRef: RefObject<StreamViewportHandle | null>;
|
||||
revealLoadedMessage(messageId: string): boolean;
|
||||
|
||||
@@ -139,7 +139,7 @@ describe("useChatOutline", () => {
|
||||
kind: "user_message",
|
||||
text: "live prompt",
|
||||
timestamp: new Date(seq),
|
||||
timelineCursor: { epoch: "epoch-1", seq },
|
||||
timelineCursor: { epoch: "epoch-1", seq, anchorSeq: seq },
|
||||
});
|
||||
rerender({ tail: [loadedPrompt(2)] });
|
||||
await waitFor(() => expect(runtime.listAgentTimelinePrompts).toHaveBeenCalledTimes(2));
|
||||
@@ -198,7 +198,7 @@ describe("useChatOutline", () => {
|
||||
kind: "assistant_message",
|
||||
text: "chunk",
|
||||
timestamp: new Date(),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
|
||||
},
|
||||
],
|
||||
timelineEpoch: "epoch-1",
|
||||
@@ -219,7 +219,7 @@ describe("useChatOutline", () => {
|
||||
kind: "user_message",
|
||||
text: "Replaced conversation",
|
||||
timestamp: new Date(2),
|
||||
timelineCursor: { epoch: "epoch-2", seq: 1 },
|
||||
timelineCursor: { epoch: "epoch-2", seq: 1, anchorSeq: 1 },
|
||||
},
|
||||
],
|
||||
timelineEpoch: "epoch-2",
|
||||
@@ -275,7 +275,7 @@ describe("useChatOutline", () => {
|
||||
kind: "user_message" as const,
|
||||
text: "prompt",
|
||||
timestamp: new Date(1),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
|
||||
},
|
||||
];
|
||||
const { result, rerender } = renderHook(
|
||||
@@ -326,7 +326,7 @@ describe("useChatOutline", () => {
|
||||
kind: "user_message" as const,
|
||||
text: "prompt",
|
||||
timestamp: new Date(1),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
|
||||
};
|
||||
const { result, rerender } = renderHook(
|
||||
({ tail, mountedHistoryMessageIds }) =>
|
||||
@@ -381,7 +381,7 @@ describe("useChatOutline", () => {
|
||||
kind: "user_message" as const,
|
||||
text: "prompt",
|
||||
timestamp: new Date(2),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
|
||||
};
|
||||
const revealLoadedMessage = vi.fn();
|
||||
revealLoadedMessage.mockReturnValue(false);
|
||||
|
||||
@@ -26,22 +26,14 @@ export function getMountedRecentStreamItems(): number {
|
||||
export function findMountedWindowStart(input: {
|
||||
items: StreamItem[];
|
||||
minMountedCount: number;
|
||||
// Caps how far turn alignment may rewind. History paging and the replica
|
||||
// cache omit it and still keep a whole turn.
|
||||
maxMountedCount?: number;
|
||||
}): number {
|
||||
const { items, minMountedCount } = input;
|
||||
if (items.length <= minMountedCount) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const mountedLimit =
|
||||
input.maxMountedCount === undefined
|
||||
? items.length
|
||||
: Math.max(minMountedCount, input.maxMountedCount);
|
||||
const earliestStart = Math.max(0, items.length - mountedLimit);
|
||||
let startIndex = Math.max(items.length - minMountedCount, 0);
|
||||
while (startIndex > earliestStart && continuesTurn(items[startIndex - 1], items[startIndex])) {
|
||||
while (startIndex > 0 && continuesTurn(items[startIndex - 1], items[startIndex])) {
|
||||
startIndex -= 1;
|
||||
}
|
||||
return startIndex;
|
||||
|
||||
@@ -2,7 +2,7 @@ import { LegendList, type LegendListRef } from "@legendapp/list/react-native";
|
||||
import React, { act, useSyncExternalStore } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { View } from "react-native";
|
||||
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||
import { afterEach, beforeEach, expect, it } from "vitest";
|
||||
import { disclosureAnchor } from "./native-disclosure-hold";
|
||||
|
||||
// The native chat timeline runs on the patched LegendList (patches/@legendapp+list+3.7.1.patch).
|
||||
@@ -90,7 +90,7 @@ function keyExtractor(item: Row) {
|
||||
return item.id;
|
||||
}
|
||||
|
||||
function rowHeight(item: Row) {
|
||||
function estimateRowSize(item: Row) {
|
||||
return item.height;
|
||||
}
|
||||
|
||||
@@ -289,7 +289,7 @@ it("expands the draw distance of a placed end-anchored list without moving its b
|
||||
keyExtractor={keyExtractor}
|
||||
estimatedListSize={ESTIMATED_LIST_SIZE}
|
||||
recycleItems={false}
|
||||
getEstimatedItemSize={rowHeight}
|
||||
getEstimatedItemSize={estimateRowSize}
|
||||
drawDistance={drawDistance}
|
||||
alignItemsAtEnd
|
||||
initialScrollAtEnd
|
||||
@@ -315,96 +315,3 @@ it("expands the draw distance of a placed end-anchored list without moving its b
|
||||
expect(expanded?.scroll).toBe(initial?.scroll);
|
||||
expect(expanded?.positionByKey(lastRow.id)).toBe(lastRowTop);
|
||||
});
|
||||
|
||||
it.each([2, 4])("reveals an end-anchored list with a footer %sx the viewport", async (scale) => {
|
||||
const rows: Row[] = Array.from({ length: 10 }, (_, index) => ({
|
||||
id: `row-${index}`,
|
||||
height: 40,
|
||||
}));
|
||||
const footerHeight = VIEWPORT_HEIGHT * scale;
|
||||
const listRef = React.createRef<LegendListRef>();
|
||||
const footer = React.createElement(View, { style: rowStyle(footerHeight) });
|
||||
const onReady = vi.fn();
|
||||
|
||||
act(() => {
|
||||
root.render(
|
||||
<LegendList
|
||||
ref={listRef}
|
||||
data={rows}
|
||||
renderItem={renderRow}
|
||||
keyExtractor={keyExtractor}
|
||||
estimatedListSize={ESTIMATED_LIST_SIZE}
|
||||
getEstimatedItemSize={rowHeight}
|
||||
drawDistance={50}
|
||||
recycleItems={false}
|
||||
alignItemsAtEnd
|
||||
initialScrollAtEnd
|
||||
ListFooterComponent={footer}
|
||||
onReady={onReady}
|
||||
style={LIST_STYLE}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
await expect
|
||||
.poll(async () => {
|
||||
await wait(16);
|
||||
return onReady.mock.calls.length;
|
||||
})
|
||||
.toBe(1);
|
||||
expect(listRef.current?.getState().scroll).toBe(
|
||||
rows.length * 40 + footerHeight - VIEWPORT_HEIGHT,
|
||||
);
|
||||
});
|
||||
|
||||
const END_PADDED_CONTENT_STYLE = { paddingBottom: 125 };
|
||||
|
||||
it("reveals buffered rows when the scroll view takes over initial end positioning", () => {
|
||||
const rowSize = 40;
|
||||
const rows: Row[] = Array.from({ length: 10 }, (_, index) => ({
|
||||
id: `row-${index}`,
|
||||
height: rowSize,
|
||||
}));
|
||||
const listRef = React.createRef<LegendListRef>();
|
||||
const onReady = vi.fn();
|
||||
|
||||
act(() => {
|
||||
root.render(
|
||||
<LegendList
|
||||
ref={listRef}
|
||||
data={rows}
|
||||
renderItem={renderRow}
|
||||
keyExtractor={keyExtractor}
|
||||
estimatedListSize={ESTIMATED_LIST_SIZE}
|
||||
getFixedItemSize={rowHeight}
|
||||
drawDistance={120}
|
||||
recycleItems={false}
|
||||
alignItemsAtEnd
|
||||
initialScrollAtEnd
|
||||
contentContainerStyle={END_PADDED_CONTENT_STYLE}
|
||||
onReady={onReady}
|
||||
style={LIST_STYLE}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
const list = listRef.current;
|
||||
if (!list) throw new Error("The list did not mount");
|
||||
const scroller: unknown = list.getScrollableNode();
|
||||
if (!(scroller instanceof HTMLElement)) throw new Error("The list has no scroll element");
|
||||
const endOffset =
|
||||
rows.length * rowSize + END_PADDED_CONTENT_STYLE.paddingBottom - VIEWPORT_HEIGHT;
|
||||
|
||||
act(() => {
|
||||
// Deliver the scroll view's observed end offset before canceling the list's initial scroll.
|
||||
// Keep both calls in one task so a later layout pass cannot complete the reveal for them.
|
||||
scroller.scrollTop = endOffset;
|
||||
scroller.dispatchEvent(new Event("scroll"));
|
||||
expect(onReady).not.toHaveBeenCalled();
|
||||
list.cancelScroll();
|
||||
});
|
||||
const state = list.getState();
|
||||
expect(state.scroll).toBe(endOffset);
|
||||
expect(state.start).toBeNull();
|
||||
expect(state.endBuffered).toBe(rows.length - 1);
|
||||
expect(state.sizeAtIndex(rows.length - 1)).toBe(rowSize);
|
||||
expect(onReady).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
@@ -3,7 +3,6 @@ import type { StreamItem } from "@/types/stream";
|
||||
import { projectPluginTimelineItems } from "@/plugins/timeline/projection";
|
||||
import { findMountedWindowStart } from "./history-window";
|
||||
import { buildAgentStreamRenderModel } from "./model";
|
||||
import { MAX_MOUNTED_WEB_WINDOW_ITEMS } from "./web-virtualization";
|
||||
|
||||
function createTimestamp(seed: number): Date {
|
||||
return new Date(`2026-01-01T00:00:${seed.toString().padStart(2, "0")}.000Z`);
|
||||
@@ -126,30 +125,6 @@ describe("buildAgentStreamRenderModel", () => {
|
||||
expect(model.history).not.toContain(head[0]);
|
||||
});
|
||||
|
||||
it("virtualizes a desktop web turn that runs past the mounted cap", () => {
|
||||
const length = MAX_MOUNTED_WEB_WINDOW_ITEMS + 80;
|
||||
const tail = Array.from({ length }, (_, index) => ({
|
||||
...userMessage(`row-${index}`, index % 60),
|
||||
turnId: "long-run",
|
||||
}));
|
||||
|
||||
const model = buildAgentStreamRenderModel({
|
||||
isTurnActive: false,
|
||||
activeTurnStartedAt: null,
|
||||
tail,
|
||||
head: [],
|
||||
platform: "web",
|
||||
isMobileBreakpoint: false,
|
||||
});
|
||||
|
||||
expect(model.segments.historyMounted).toHaveLength(MAX_MOUNTED_WEB_WINDOW_ITEMS);
|
||||
expect(model.segments.historyVirtualized).toHaveLength(80);
|
||||
expect(model.segments.historyMounted[0]?.id).toBe(
|
||||
`row-${length - MAX_MOUNTED_WEB_WINDOW_ITEMS}`,
|
||||
);
|
||||
expect(model.segments.historyVirtualized[0]?.id).toBe("row-0");
|
||||
});
|
||||
|
||||
it("keeps the full committed tail mounted on mobile web", () => {
|
||||
const tail = [userMessage("u1", 1), assistantMessage("a1", 2)];
|
||||
const head = [assistantMessage("live-a", 3)];
|
||||
|
||||
@@ -2,10 +2,7 @@ import type { ReactNode } from "react";
|
||||
import { deriveStreamTurnTiming, type StreamTurnTiming } from "@/timeline/turn-time";
|
||||
import type { StreamItem } from "@/types/stream";
|
||||
import { findMountedWindowStart, getMountedRecentStreamItems } from "./history-window";
|
||||
import {
|
||||
getWebPartialVirtualizationThreshold,
|
||||
MAX_MOUNTED_WEB_WINDOW_ITEMS,
|
||||
} from "./web-virtualization";
|
||||
import { getWebPartialVirtualizationThreshold } from "./web-virtualization";
|
||||
import { orderHeadForStreamRenderStrategy, orderTailForStreamRenderStrategy } from "./strategy";
|
||||
import { resolveStreamRenderStrategy } from "./strategy-resolver";
|
||||
|
||||
@@ -137,7 +134,6 @@ function splitOrderedTail(params: {
|
||||
const mountedWindowStart = findMountedWindowStart({
|
||||
items: orderedTail,
|
||||
minMountedCount: getMountedRecentStreamItems(),
|
||||
maxMountedCount: MAX_MOUNTED_WEB_WINDOW_ITEMS,
|
||||
});
|
||||
const split = {
|
||||
history: orderedTail,
|
||||
|
||||
@@ -320,7 +320,7 @@ describe("stream presentation through installed plugins", () => {
|
||||
const source = harness.source();
|
||||
const live = source.head[0];
|
||||
if (live?.kind !== "assistant_message") throw new Error("Expected a live assistant message");
|
||||
const canonical = { ...live, timelineCursor: { epoch: "epoch-1", seq: 42 } };
|
||||
const canonical = { ...live, timelineCursor: { epoch: "epoch-1", seq: 42, anchorSeq: 42 } };
|
||||
const present = createStreamPresentation();
|
||||
present({ ...presentationOptions, tail: [], head: [live], transform: undefined });
|
||||
const repointed = rows(
|
||||
@@ -330,7 +330,7 @@ describe("stream presentation through installed plugins", () => {
|
||||
{
|
||||
id: streamed[0]!.id,
|
||||
text: "Streamed answer",
|
||||
timelineCursor: { epoch: "epoch-1", seq: 42 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 42, anchorSeq: 42 },
|
||||
},
|
||||
]);
|
||||
});
|
||||
@@ -517,7 +517,7 @@ describe("timeline presentation", () => {
|
||||
messageId: "provider-message",
|
||||
clientMessageId: "client-message",
|
||||
turnId: "turn-1",
|
||||
timelineCursor: { epoch: "epoch", seq: 12 },
|
||||
timelineCursor: { epoch: "epoch", seq: 12, anchorSeq: 12 },
|
||||
});
|
||||
const presentMessage = () =>
|
||||
present({
|
||||
|
||||
@@ -33,7 +33,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
|
||||
it("forks a failed assistant turn from its Paseo timeline cursor without a provider message id", () => {
|
||||
const failedTurn = {
|
||||
...assistantMessage("assistant-error", 2),
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42 },
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
|
||||
};
|
||||
|
||||
expect(
|
||||
@@ -50,7 +50,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
|
||||
it("includes the provider message id with a supported timeline cursor", () => {
|
||||
const selected = {
|
||||
...assistantMessage("assistant-1", 2, "msg-assistant-1"),
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42 },
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
|
||||
};
|
||||
|
||||
expect(
|
||||
@@ -68,7 +68,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
|
||||
it("falls back to the provider message id when timeline cursors are unsupported", () => {
|
||||
const selected = {
|
||||
...assistantMessage("assistant-1", 2, "msg-assistant-1"),
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42 },
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
|
||||
};
|
||||
|
||||
expect(
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
import type { StreamItem, TimelinePosition } from "@/types/stream";
|
||||
import type { StreamItem } from "@/types/stream";
|
||||
|
||||
/** The daemon's timeline cursor; the row's anchor stays in the client. */
|
||||
interface TimelineBoundaryCursor {
|
||||
epoch: string;
|
||||
seq: number;
|
||||
}
|
||||
|
||||
export type AssistantTurnForkBoundary =
|
||||
| { boundaryCursor: TimelinePosition; boundaryMessageId?: string }
|
||||
| { boundaryCursor: TimelineBoundaryCursor; boundaryMessageId?: string }
|
||||
| { boundaryCursor?: undefined; boundaryMessageId: string };
|
||||
|
||||
export function resolveAssistantTurnForkBoundary(input: {
|
||||
@@ -15,7 +21,7 @@ export function resolveAssistantTurnForkBoundary(input: {
|
||||
}
|
||||
if (input.supportsTimelineCursor && item.timelineCursor) {
|
||||
return {
|
||||
boundaryCursor: item.timelineCursor,
|
||||
boundaryCursor: { epoch: item.timelineCursor.epoch, seq: item.timelineCursor.seq },
|
||||
...(item.messageId ? { boundaryMessageId: item.messageId } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -140,7 +140,7 @@ describe("collapseTurns", () => {
|
||||
it("stands at its host's timeline position, taking a new row when that position lands", () => {
|
||||
const live = collapse([user("u1"), shell("c1"), reply("r1")]);
|
||||
expect(live.summaryRowsByHostId.get("u1")).not.toHaveProperty("timelineCursor");
|
||||
const cursor = { epoch: "epoch-1", seq: 7 };
|
||||
const cursor = { epoch: "epoch-1", seq: 7, anchorSeq: 7 };
|
||||
const placed = [{ ...user("u1"), timelineCursor: cursor }, shell("c1"), reply("r1")];
|
||||
const canonical = collapse(placed, { previousSummaryRowsByHostId: live.summaryRowsByHostId });
|
||||
expect(canonical.summaryRowsByHostId.get("u1")).not.toBe(live.summaryRowsByHostId.get("u1"));
|
||||
|
||||
@@ -408,6 +408,10 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
const timelineEpoch = useSessionStore(
|
||||
(state) => state.sessions[resolvedServerId]?.agentTimelineCursor.get(agentId)?.epoch ?? null,
|
||||
);
|
||||
const timelineRewindSeq = useSessionStore((state) => {
|
||||
const rewind = state.sessions[resolvedServerId]?.agentTimelineLatestRewind.get(agentId);
|
||||
return rewind && rewind.epoch === timelineEpoch ? rewind.seq : null;
|
||||
});
|
||||
const isTimelineDetached = useSessionStore(
|
||||
(state) => state.sessions[resolvedServerId]?.agentTimelineHasNewer.get(agentId) === true,
|
||||
);
|
||||
@@ -1166,6 +1170,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
agentId={agentId}
|
||||
serverId={resolvedServerId}
|
||||
epoch={timelineEpoch}
|
||||
rewindSeq={timelineRewindSeq}
|
||||
items={findItems}
|
||||
viewportRef={viewportRef}
|
||||
revealLoadedMessage={revealLoadedMessage}
|
||||
|
||||
@@ -10,7 +10,6 @@ import {
|
||||
DEFAULT_WEB_PARTIAL_VIRTUALIZATION_THRESHOLD,
|
||||
estimateStreamItemHeight,
|
||||
findMountedWindowStart,
|
||||
MAX_MOUNTED_WEB_WINDOW_ITEMS,
|
||||
getWebMountedRecentStreamItems,
|
||||
getWebPartialVirtualizationThreshold,
|
||||
splitWebVirtualizedHistory,
|
||||
@@ -109,37 +108,6 @@ describe("findMountedWindowStart", () => {
|
||||
}),
|
||||
).toBe(39);
|
||||
});
|
||||
|
||||
it("keeps a whole turn when the caller does not cap the rewind", () => {
|
||||
const items = Array.from({ length: MAX_MOUNTED_WEB_WINDOW_ITEMS + 40 }, (_, index) => ({
|
||||
...toolCall(`t${index}`, index % 60),
|
||||
turnId: "long",
|
||||
}));
|
||||
|
||||
expect(findMountedWindowStart({ items, minMountedCount: 20 })).toBe(0);
|
||||
});
|
||||
|
||||
it("stops a long turn at the cap and still honors a larger minimum", () => {
|
||||
const items = Array.from({ length: 200 }, (_, index) => ({
|
||||
...toolCall(`t${index}`, index % 60),
|
||||
turnId: "long",
|
||||
}));
|
||||
|
||||
expect(
|
||||
findMountedWindowStart({
|
||||
items,
|
||||
minMountedCount: 20,
|
||||
maxMountedCount: MAX_MOUNTED_WEB_WINDOW_ITEMS,
|
||||
}),
|
||||
).toBe(200 - MAX_MOUNTED_WEB_WINDOW_ITEMS);
|
||||
expect(
|
||||
findMountedWindowStart({
|
||||
items,
|
||||
minMountedCount: 80,
|
||||
maxMountedCount: MAX_MOUNTED_WEB_WINDOW_ITEMS,
|
||||
}),
|
||||
).toBe(120);
|
||||
});
|
||||
});
|
||||
|
||||
describe("splitWebVirtualizedHistory", () => {
|
||||
@@ -162,39 +130,6 @@ describe("splitWebVirtualizedHistory", () => {
|
||||
expect(window.mountedEntries[0]?.item.id).toBe("u5");
|
||||
expect(window.mountedEntries).toHaveLength(50);
|
||||
});
|
||||
|
||||
it("virtualizes the older rows of a turn that is longer than the mounted cap", () => {
|
||||
const length = MAX_MOUNTED_WEB_WINDOW_ITEMS + 25;
|
||||
const items = Array.from({ length }, (_, index) => ({
|
||||
...toolCall(`t${index}`, index % 60),
|
||||
turnId: "long",
|
||||
}));
|
||||
|
||||
const window = splitWebVirtualizedHistory({
|
||||
entries: indexEntries(items),
|
||||
minMountedCount: DEFAULT_WEB_MOUNTED_RECENT_STREAM_ITEMS,
|
||||
});
|
||||
|
||||
expect(window.mountedEntries).toHaveLength(MAX_MOUNTED_WEB_WINDOW_ITEMS);
|
||||
expect(window.virtualizedEntries).toHaveLength(25);
|
||||
expect(window.mountedEntries[0]?.item.id).toBe(`t${length - MAX_MOUNTED_WEB_WINDOW_ITEMS}`);
|
||||
expect(window.virtualizedEntries[0]?.item.id).toBe("t0");
|
||||
});
|
||||
|
||||
it("keeps a turn that fits under the cap mounted together", () => {
|
||||
const items = Array.from({ length: 40 }, (_, index) => ({
|
||||
...toolCall(`t${index}`, index),
|
||||
turnId: "short",
|
||||
}));
|
||||
|
||||
const window = splitWebVirtualizedHistory({
|
||||
entries: indexEntries(items),
|
||||
minMountedCount: DEFAULT_WEB_MOUNTED_RECENT_STREAM_ITEMS,
|
||||
});
|
||||
|
||||
expect(window.virtualizedEntries).toHaveLength(0);
|
||||
expect(window.mountedEntries).toHaveLength(40);
|
||||
});
|
||||
});
|
||||
|
||||
describe("estimateStreamItemHeight", () => {
|
||||
|
||||
@@ -8,9 +8,6 @@ import {
|
||||
|
||||
export const DEFAULT_WEB_PARTIAL_VIRTUALIZATION_THRESHOLD = 100;
|
||||
export const DEFAULT_WEB_MOUNTED_RECENT_STREAM_ITEMS = DEFAULT_MOUNTED_RECENT_STREAM_ITEMS;
|
||||
// Collapsed tool rows are about 40px, so this stays past a desktop viewport.
|
||||
// Opening a long run mounts that tail and virtualizes the older rows.
|
||||
export const MAX_MOUNTED_WEB_WINDOW_ITEMS = 60;
|
||||
const COLLAPSED_TOOL_SEQUENCE_ROW_HEIGHT_ESTIMATE = 40;
|
||||
|
||||
type BottomAnchorE2ETestGlobals = typeof globalThis & {
|
||||
@@ -90,7 +87,6 @@ export function splitWebVirtualizedHistory(input: {
|
||||
const startIndex = findMountedWindowStart({
|
||||
items: input.entries.map((entry) => entry.item),
|
||||
minMountedCount: input.minMountedCount,
|
||||
maxMountedCount: MAX_MOUNTED_WEB_WINDOW_ITEMS,
|
||||
});
|
||||
return {
|
||||
virtualizedEntries: input.entries.slice(0, startIndex),
|
||||
|
||||
@@ -1,20 +1,5 @@
|
||||
import { createElement as h } from "react";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { within } from "@testing-library/dom";
|
||||
import { EnrichedMarkdownText } from "react-native-enriched-markdown";
|
||||
import { I18nextProvider } from "react-i18next";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { WEB_RENDERERS } from "@/components/markdown/renderers.web";
|
||||
import type { ToastApi } from "@/components/toast-host";
|
||||
import { ToastApiProvider } from "@/contexts/toast-api-context";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import {
|
||||
createAssistantSelectionClipboardContent,
|
||||
createElementClipboardContent,
|
||||
} from "./content.web";
|
||||
import { MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE } from "./markup";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { createAssistantSelectionClipboardContent } from "./content.web";
|
||||
|
||||
const fixture = `
|
||||
<div data-testid="assistant-message">
|
||||
@@ -968,158 +953,3 @@ it("copies a workspace image path instead of its temporary display URL", () => {
|
||||
"",
|
||||
);
|
||||
});
|
||||
|
||||
describe("quote copy", () => {
|
||||
let root: Root | undefined;
|
||||
let host: HTMLDivElement | undefined;
|
||||
const toast: ToastApi = { show: () => () => {}, copied: () => {}, error: () => {} };
|
||||
const queryClient = new QueryClient();
|
||||
|
||||
afterEach(() => {
|
||||
const mounted = root;
|
||||
if (mounted) flushSync(() => mounted.unmount());
|
||||
root = undefined;
|
||||
host?.remove();
|
||||
host = undefined;
|
||||
});
|
||||
|
||||
/** Renders Markdown through the web engine with the app's renderers, as a message does. */
|
||||
async function renderMarkdown(markdown: string, lastText: string): Promise<HTMLElement> {
|
||||
if (!host || !root) {
|
||||
host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
root = createRoot(host);
|
||||
}
|
||||
const mounted = root;
|
||||
flushSync(() =>
|
||||
mounted.render(
|
||||
h(
|
||||
QueryClientProvider,
|
||||
{ client: queryClient },
|
||||
h(
|
||||
I18nextProvider,
|
||||
{ i18n },
|
||||
h(ToastApiProvider, {
|
||||
api: toast,
|
||||
children: h(EnrichedMarkdownText, {
|
||||
markdown,
|
||||
flavor: "github",
|
||||
md4cFlags: { latexMath: false, admonitions: true },
|
||||
renderers: WEB_RENDERERS,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
const rendered = host;
|
||||
await vi.waitFor(() => expect(rendered.textContent).toContain(lastText));
|
||||
return rendered;
|
||||
}
|
||||
|
||||
it("copies a quote's body with its formatting and without the quote marker", async () => {
|
||||
const rendered = await renderMarkdown(
|
||||
"> Hello **team**, see [the PR](https://example.test/pr).\n>\n> - Review\n>\n> > Nested reply",
|
||||
"Nested reply",
|
||||
);
|
||||
|
||||
const content = createElementClipboardContent(fixtureElement(rendered, "blockquote"));
|
||||
|
||||
expect(content?.plainText).toBe(
|
||||
"Hello **team**, see [the PR](https://example.test/pr).\n\n- Review\n\n> Nested reply",
|
||||
);
|
||||
expect(content?.html).toContain("<strong>team</strong>");
|
||||
expect(content?.html).toContain("<blockquote>");
|
||||
expect(content?.html).not.toContain("Copy quote");
|
||||
});
|
||||
|
||||
it("gives a nested quote its own control that copies only the nested quote", async () => {
|
||||
const rendered = await renderMarkdown("> Outer\n>\n> > Nested reply", "Nested reply");
|
||||
const nested = fixtureElement(rendered, "blockquote", 1);
|
||||
|
||||
expect(within(rendered).getAllByRole("button", { name: "Copy quote" })).toHaveLength(2);
|
||||
expect(within(nested).getAllByRole("button", { name: "Copy quote" })).toHaveLength(1);
|
||||
expect(createElementClipboardContent(nested)?.plainText).toBe("Nested reply");
|
||||
});
|
||||
|
||||
it("copies a code block inside a quote as its fence and keeps the code's own control", async () => {
|
||||
const rendered = await renderMarkdown("> Run:\n>\n> ```sh\n> npm test\n> ```", "npm test");
|
||||
const quote = fixtureElement(rendered, "blockquote");
|
||||
|
||||
expect(within(quote).getByRole("button", { name: "Copy code" })).toBeTruthy();
|
||||
expect(createElementClipboardContent(quote)?.plainText).toBe("Run:\n\n```sh\nnpm test\n```");
|
||||
});
|
||||
|
||||
it("copies what a streaming quote shows at the time of the copy", async () => {
|
||||
const first = await renderMarkdown("> First draft", "First draft");
|
||||
const quote = fixtureElement(first, "blockquote");
|
||||
|
||||
const revised = await renderMarkdown("> First draft, revised", "revised");
|
||||
|
||||
expect(fixtureElement(revised, "blockquote")).toBe(quote);
|
||||
expect(createElementClipboardContent(quote)?.plainText).toBe("First draft, revised");
|
||||
});
|
||||
|
||||
it("copies literal Markdown characters raw in text/plain and escaped in text/html", async () => {
|
||||
const rendered = await renderMarkdown("> literal \\_word\\_ stays literal", "stays literal");
|
||||
|
||||
const content = createElementClipboardContent(fixtureElement(rendered, "blockquote"));
|
||||
|
||||
expect(content?.plainText).toBe("literal _word_ stays literal");
|
||||
expect(content?.html).toContain("literal _word_ stays literal");
|
||||
expect(content?.html).not.toContain("<em>");
|
||||
});
|
||||
|
||||
it("gives an admonition no copy control", async () => {
|
||||
const rendered = await renderMarkdown("> [!NOTE]\n> Heads up", "Heads up");
|
||||
|
||||
expect(within(rendered).queryByRole("button", { name: "Copy quote" })).toBeNull();
|
||||
});
|
||||
|
||||
it("copies a nested admonition as its callout source", async () => {
|
||||
const rendered = await renderMarkdown(
|
||||
"> Before\n>\n> > [!WARNING]\n> > Do not deploy.\n>\n> After",
|
||||
"After",
|
||||
);
|
||||
|
||||
const content = createElementClipboardContent(fixtureElement(rendered, "blockquote"));
|
||||
|
||||
expect(content?.plainText).toBe("Before\n\n> [!WARNING]\n> Do not deploy.\n\nAfter");
|
||||
});
|
||||
|
||||
it("copies a selection across an admonition as the text it shows, without a callout marker", async () => {
|
||||
const rendered = await renderMarkdown(
|
||||
"> Before\n>\n> > [!WARNING]\n> > Do not deploy.\n>\n> After",
|
||||
"After",
|
||||
);
|
||||
rendered.setAttribute("data-testid", "assistant-message");
|
||||
const body = tokenText(rendered, "Do not deploy.");
|
||||
|
||||
expect(
|
||||
copyBetween([body, "Do not ".length], [tokenText(rendered, "After"), 5])?.plainText,
|
||||
).toBe("deploy.\n\nAfter");
|
||||
expect(
|
||||
copyBetween([tokenText(rendered, "Before"), 0], [tokenText(rendered, "Warning"), 4])
|
||||
?.plainText,
|
||||
).toBe("Before\n\nWarn");
|
||||
expect(
|
||||
copyBetween([tokenText(rendered, "Before"), 0], [body, "Do not".length])?.plainText,
|
||||
).not.toContain("[!WARNING]");
|
||||
});
|
||||
|
||||
it("copies a rendered Mermaid diagram as its fence", () => {
|
||||
const quote = document.createElement("blockquote");
|
||||
quote.innerHTML = `<p>Before</p><div ${MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE}="graph TD; A-->B" data-paseo-markdown-language="mermaid"><svg aria-label="diagram"></svg></div><p>After</p>`;
|
||||
|
||||
expect(createElementClipboardContent(quote)?.plainText).toBe(
|
||||
"Before\n\n```mermaid\ngraph TD; A-->B\n```\n\nAfter",
|
||||
);
|
||||
});
|
||||
|
||||
it("copies nothing from a quote that holds only its control", () => {
|
||||
const quote = document.createElement("blockquote");
|
||||
quote.innerHTML = '<button data-paseo-markdown-ignore="true">Copy quote</button>';
|
||||
|
||||
expect(createElementClipboardContent(quote)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,12 +6,9 @@ import {
|
||||
type MarkdownClipboardContent,
|
||||
} from "@/utils/rich-clipboard";
|
||||
import {
|
||||
MARKDOWN_ADMONITION_TITLE_ATTRIBUTE,
|
||||
MARKDOWN_ADMONITION_TYPE_ATTRIBUTE,
|
||||
MARKDOWN_COPY_IMAGE_SOURCES_ATTRIBUTE,
|
||||
MARKDOWN_COPY_ALIGN_ATTRIBUTE,
|
||||
MARKDOWN_COPY_ALT_ATTRIBUTE,
|
||||
MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE,
|
||||
MARKDOWN_COPY_IGNORE_ATTRIBUTE,
|
||||
MARKDOWN_COPY_LANGUAGE_ATTRIBUTE,
|
||||
MARKDOWN_COPY_LIST_MARKER_ATTRIBUTE,
|
||||
@@ -94,17 +91,6 @@ function createTurndown(flavor: "markdown" | "plain"): TurndownService {
|
||||
} else {
|
||||
turndown.escape = (text) => text;
|
||||
}
|
||||
// An admonition copies as its `> [!TYPE]` source.
|
||||
turndown.addRule("admonition", {
|
||||
filter: (node) => node.hasAttribute(MARKDOWN_ADMONITION_TYPE_ATTRIBUTE),
|
||||
replacement: (content, node) => {
|
||||
const type = (node as Element)
|
||||
.getAttribute(MARKDOWN_ADMONITION_TYPE_ATTRIBUTE)!
|
||||
.toUpperCase();
|
||||
const body = content.replace(/^\n+|\n+$/g, "");
|
||||
return `\n\n${`[!${type}]\n${body}`.replace(/^/gm, "> ")}\n\n`;
|
||||
},
|
||||
});
|
||||
turndown.addRule("gfmStrikethrough", {
|
||||
filter: ["del", "s"],
|
||||
replacement: (content) => `~~${content}~~`,
|
||||
@@ -134,53 +120,6 @@ function isWebUrl(href: string): boolean {
|
||||
const markdownTurndown = createTurndown("markdown");
|
||||
const plainTurndown = createTurndown("plain");
|
||||
|
||||
/**
|
||||
* A fence rendered as something other than its code, such as a Mermaid diagram, carries
|
||||
* its source in an attribute. Put the code block back so the fence is what gets copied.
|
||||
*/
|
||||
function restoreFenceSources(container: Element): void {
|
||||
for (const region of container.querySelectorAll(`[${MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE}]`)) {
|
||||
const source = region.getAttribute(MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE);
|
||||
if (source === null) continue;
|
||||
const pre = document.createElement("pre");
|
||||
const code = document.createElement("code");
|
||||
const language = region.getAttribute(MARKDOWN_COPY_LANGUAGE_ATTRIBUTE);
|
||||
if (language) code.className = `language-${language}`;
|
||||
code.textContent = source;
|
||||
pre.append(code);
|
||||
region.replaceWith(pre);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clipboard payload for everything inside `element`, without the element's own syntax:
|
||||
* a quote's body carries no `>` prefix. Null when there is nothing to copy.
|
||||
*/
|
||||
export function createElementClipboardContent(element: Element): MarkdownClipboardContent | null {
|
||||
const container = document.createElement("div");
|
||||
container.append(...Array.from(element.childNodes, (child) => child.cloneNode(true)));
|
||||
const originals = element.querySelectorAll("*");
|
||||
const copies = container.querySelectorAll("*");
|
||||
originals.forEach((original, index) => copySemanticAttributes(original, copies[index]!));
|
||||
restoreFenceSources(container);
|
||||
restoreAdmonitions(container);
|
||||
restoreMarkdownElements(container);
|
||||
return clipboardContentFromMarkup(container);
|
||||
}
|
||||
|
||||
function clipboardContentFromMarkup(container: HTMLElement): MarkdownClipboardContent | null {
|
||||
const markdown = markdownTurndown.turndown(container).trim();
|
||||
if (!markdown) {
|
||||
return null;
|
||||
}
|
||||
// text/plain carries unescaped Markdown: a plain target shows backslashes literally.
|
||||
// text/html is rendered from escaped Markdown, so literal Markdown characters stay
|
||||
// literal in a rich target.
|
||||
const plainText = plainTurndown.turndown(container).trim();
|
||||
const content = createSelectionClipboardContent(markdown, plainText);
|
||||
return { ...content, html: flattenClipboardListMarkup(content.html) };
|
||||
}
|
||||
|
||||
export function createAssistantSelectionClipboardContent(
|
||||
selection: Selection | null,
|
||||
): MarkdownClipboardContent | null {
|
||||
@@ -206,7 +145,17 @@ export function createAssistantSelectionClipboardContent(
|
||||
container.append(cloneMarkdownSelection(part.range, part.message));
|
||||
}
|
||||
restoreMarkdownElements(container);
|
||||
return clipboardContentFromMarkup(container);
|
||||
|
||||
const markdown = markdownTurndown.turndown(container).trim();
|
||||
if (!markdown) {
|
||||
return null;
|
||||
}
|
||||
// text/plain carries unescaped Markdown: a plain target shows backslashes literally.
|
||||
// text/html is rendered from escaped Markdown, so literal Markdown characters stay
|
||||
// literal in a rich target.
|
||||
const plainText = plainTurndown.turndown(container).trim();
|
||||
const content = createSelectionClipboardContent(markdown, plainText);
|
||||
return { ...content, html: flattenClipboardListMarkup(content.html) };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -753,28 +702,6 @@ function numberOrderedListItems(list: Element, start: number): void {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The library renders an admonition as a box with a generated title. Keep it a quote
|
||||
* with its type, so it copies as its callout source rather than as the title's prose.
|
||||
* Only a whole-element copy does this: a selection cannot tell from its cloned markup
|
||||
* whether it holds the whole callout, so it copies the text it shows.
|
||||
*/
|
||||
function restoreAdmonitions(container: Element): void {
|
||||
const admonitions = Array.from(
|
||||
container.querySelectorAll(`[${MARKDOWN_ADMONITION_TYPE_ATTRIBUTE}]`),
|
||||
);
|
||||
for (const admonition of admonitions.toReversed()) {
|
||||
admonition.querySelector(`:scope > [${MARKDOWN_ADMONITION_TITLE_ATTRIBUTE}]`)?.remove();
|
||||
const quote = document.createElement("blockquote");
|
||||
quote.setAttribute(
|
||||
MARKDOWN_ADMONITION_TYPE_ATTRIBUTE,
|
||||
admonition.getAttribute(MARKDOWN_ADMONITION_TYPE_ATTRIBUTE) ?? "note",
|
||||
);
|
||||
quote.append(...admonition.childNodes);
|
||||
admonition.replaceWith(quote);
|
||||
}
|
||||
}
|
||||
|
||||
function unwrapIncompleteTables(container: HTMLElement): void {
|
||||
for (const table of container.querySelectorAll("table")) {
|
||||
if (hasUsableTableColumnContract(table)) {
|
||||
|
||||
@@ -6,13 +6,9 @@ export const MARKDOWN_COPY_UNWRAP_ATTRIBUTE = "data-paseo-markdown-unwrap";
|
||||
export const MARKDOWN_COPY_RECOGNIZED_LINK_ATTRIBUTE = "data-paseo-markdown-recognized-link";
|
||||
export const MARKDOWN_COPY_LIST_START_ATTRIBUTE = "data-paseo-markdown-list-start";
|
||||
export const MARKDOWN_COPY_LANGUAGE_ATTRIBUTE = "data-paseo-markdown-language";
|
||||
export const MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE = "data-paseo-markdown-fence-source";
|
||||
export const MARKDOWN_COPY_ALIGN_ATTRIBUTE = "data-paseo-markdown-align";
|
||||
export const MARKDOWN_COPY_SRC_ATTRIBUTE = "data-paseo-markdown-src";
|
||||
export const MARKDOWN_COPY_ALT_ATTRIBUTE = "data-paseo-markdown-alt";
|
||||
/** Set by the Markdown library's web admonition renderer on the box and on its generated title. */
|
||||
export const MARKDOWN_ADMONITION_TYPE_ATTRIBUTE = "data-enrm-admonition-type";
|
||||
export const MARKDOWN_ADMONITION_TITLE_ATTRIBUTE = "data-enrm-admonition-title";
|
||||
|
||||
/**
|
||||
* Trailing line breaks, with any indentation that followed the last one.
|
||||
|
||||
@@ -7,6 +7,7 @@ import { FOOTER_HEIGHT } from "@/constants/layout";
|
||||
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
|
||||
import { KeyboardTranslateView } from "@/keyboard/shift";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useToast } from "@/contexts/toast-context";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import { toErrorMessage } from "@/utils/error-messages";
|
||||
|
||||
@@ -19,6 +20,7 @@ export function ArchivedAgentCallout({ serverId, agentId }: ArchivedAgentCallout
|
||||
const { t } = useTranslation();
|
||||
const client = useHostRuntimeClient(serverId);
|
||||
const isConnected = useHostRuntimeIsConnected(serverId);
|
||||
const toast = useToast();
|
||||
const [isUnarchiving, setIsUnarchiving] = useState(false);
|
||||
const [unarchiveError, setUnarchiveError] = useState<string | null>(null);
|
||||
|
||||
@@ -27,12 +29,15 @@ export function ArchivedAgentCallout({ serverId, agentId }: ArchivedAgentCallout
|
||||
setIsUnarchiving(true);
|
||||
setUnarchiveError(null);
|
||||
try {
|
||||
await client.refreshAgent(agentId);
|
||||
const refreshed = await client.refreshAgent(agentId);
|
||||
if (refreshed.historyDiverged) {
|
||||
toast.show(t("workspace.tabs.toasts.reloadedAgentHistoryDiverged"), { variant: "warning" });
|
||||
}
|
||||
} catch (error) {
|
||||
setUnarchiveError(toErrorMessage(error));
|
||||
setIsUnarchiving(false);
|
||||
}
|
||||
}, [client, isConnected, isUnarchiving, agentId]);
|
||||
}, [client, isConnected, isUnarchiving, agentId, toast, t]);
|
||||
|
||||
return (
|
||||
<KeyboardTranslateView style={styles.container}>
|
||||
|
||||
@@ -1,9 +1,17 @@
|
||||
import React, { useCallback, useMemo, useState } from "react";
|
||||
import { View, Text, type StyleProp, type TextStyle, type ViewStyle } from "react-native";
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
Pressable,
|
||||
View,
|
||||
Text,
|
||||
type StyleProp,
|
||||
type TextStyle,
|
||||
type ViewStyle,
|
||||
} from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import * as Clipboard from "expo-clipboard";
|
||||
import { Check, Copy } from "lucide-react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { HighlightToken } from "@getpaseo/highlight";
|
||||
import { BlockCopyButton } from "@/components/markdown/block-copy-button";
|
||||
import { isNative, isWeb } from "@/constants/platform";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { syntaxTokenStyleFor } from "@/styles/syntax-token-styles";
|
||||
@@ -77,7 +85,6 @@ export const HighlightedCodeBlock = React.memo(function HighlightedCodeBlock({
|
||||
[renderedCode, language],
|
||||
);
|
||||
|
||||
const { t } = useTranslation();
|
||||
const isCompact = useIsCompactFormFactor();
|
||||
const [isHovered, setIsHovered] = useState(false);
|
||||
const handlePointerEnter = useCallback(() => setIsHovered(true), []);
|
||||
@@ -86,11 +93,7 @@ export const HighlightedCodeBlock = React.memo(function HighlightedCodeBlock({
|
||||
// Copy the code without its trailing blank lines. A fence body ends in a newline,
|
||||
// and ends in more than one when the author left a blank line before the closing
|
||||
// fence; pasting any of them into a terminal runs the last line.
|
||||
const copyCode = useCallback(async () => {
|
||||
const content = code.replace(TRAILING_CODE_LINE_BREAKS, "");
|
||||
if (!content) return false;
|
||||
return Clipboard.setStringAsync(content);
|
||||
}, [code]);
|
||||
const getCode = useCallback(() => code.replace(TRAILING_CODE_LINE_BREAKS, ""), [code]);
|
||||
|
||||
return (
|
||||
<View
|
||||
@@ -108,11 +111,7 @@ export const HighlightedCodeBlock = React.memo(function HighlightedCodeBlock({
|
||||
{renderedCode}
|
||||
</Text>
|
||||
)}
|
||||
<BlockCopyButton
|
||||
onCopy={copyCode}
|
||||
visible={controlsVisible}
|
||||
label={t("message.actions.copyCode")}
|
||||
/>
|
||||
<CopyButton getCode={getCode} visible={controlsVisible} />
|
||||
</View>
|
||||
);
|
||||
});
|
||||
@@ -169,3 +168,87 @@ function splitFenceStyle(inheritedStyles: TextStyle, textStyle: TextStyle): Spli
|
||||
innerTextStyle: [inheritedStyles, textOnly],
|
||||
};
|
||||
}
|
||||
|
||||
interface CopyButtonProps {
|
||||
getCode: () => string;
|
||||
visible: boolean;
|
||||
}
|
||||
|
||||
const COPIED_RESET_MS = 1500;
|
||||
|
||||
const CopyButton = React.memo(function CopyButton({ getCode, visible }: CopyButtonProps) {
|
||||
const { t } = useTranslation();
|
||||
const [copied, setCopied] = useState(false);
|
||||
const resetRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (resetRef.current) clearTimeout(resetRef.current);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const handlePress = useCallback(async () => {
|
||||
const content = getCode();
|
||||
if (!content) return;
|
||||
await Clipboard.setStringAsync(content);
|
||||
setCopied(true);
|
||||
if (resetRef.current) clearTimeout(resetRef.current);
|
||||
resetRef.current = setTimeout(() => {
|
||||
setCopied(false);
|
||||
resetRef.current = null;
|
||||
}, COPIED_RESET_MS);
|
||||
}, [getCode]);
|
||||
|
||||
const visibilityStyle = visible
|
||||
? copyButtonStyles.containerVisible
|
||||
: copyButtonStyles.containerHidden;
|
||||
const wrapperStyle = useMemo(
|
||||
() => [copyButtonStyles.container, visibilityStyle],
|
||||
[visibilityStyle],
|
||||
);
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
onPress={handlePress}
|
||||
style={wrapperStyle}
|
||||
pointerEvents={visible ? "auto" : "none"}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={copied ? t("message.actions.copied") : t("message.actions.copyCode")}
|
||||
hitSlop={8}
|
||||
dataSet={markdownCopyDataSet.ignore}
|
||||
>
|
||||
{({ hovered }) => {
|
||||
const iconColor = hovered
|
||||
? copyButtonStyles.iconHoveredColor.color
|
||||
: copyButtonStyles.iconColor.color;
|
||||
return copied ? (
|
||||
<Check size={14} color={iconColor} />
|
||||
) : (
|
||||
<Copy size={14} color={iconColor} />
|
||||
);
|
||||
}}
|
||||
</Pressable>
|
||||
);
|
||||
});
|
||||
|
||||
const copyButtonStyles = StyleSheet.create((theme) => ({
|
||||
container: {
|
||||
position: "absolute",
|
||||
top: theme.spacing[2],
|
||||
right: theme.spacing[2],
|
||||
padding: theme.spacing[1],
|
||||
},
|
||||
containerVisible: {
|
||||
opacity: 1,
|
||||
},
|
||||
containerHidden: {
|
||||
opacity: 0,
|
||||
},
|
||||
iconColor: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
},
|
||||
iconHoveredColor: {
|
||||
color: theme.colors.foreground,
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -1,28 +1,11 @@
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
type ReactElement,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Text, View } from "react-native";
|
||||
import { Check, Plus, Server } from "lucide-react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { useCallback, useMemo, type ReactElement, type ReactNode } from "react";
|
||||
import { Pressable, View } from "react-native";
|
||||
import { Plus, Server, Settings } from "lucide-react-native";
|
||||
import { StyleSheet, useUnistyles } from "react-native-unistyles";
|
||||
import { HostStatusDot } from "@/components/host-status-dot";
|
||||
import { Combobox, type ComboboxProps } from "@/components/ui/combobox";
|
||||
import { PressHighlight } from "@/components/ui/press-highlight";
|
||||
import { Combobox, ComboboxItem, type ComboboxProps } from "@/components/ui/combobox";
|
||||
import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
|
||||
import { defaultHostAppearance, resolveHostIcon, type HostAppearance } from "@/hosts/appearance";
|
||||
import { HostConnectionLine, HostIconGlyph, HostLatencyLabel } from "@/hosts/host-icon";
|
||||
import {
|
||||
getHostRuntimeStore,
|
||||
useHostRuntimeConnectionStatus,
|
||||
useHosts,
|
||||
} from "@/runtime/host-runtime";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||
import { useHostRuntimeSnapshot, type ActiveConnection } from "@/runtime/host-runtime";
|
||||
import { orderHostsLocalFirst } from "@/types/host-connection";
|
||||
import {
|
||||
ADD_HOST_OPTION_ID,
|
||||
@@ -39,16 +22,7 @@ export {
|
||||
};
|
||||
|
||||
const SEARCHABLE_THRESHOLD = 10;
|
||||
const DEFAULT_DESKTOP_MIN_WIDTH = 328;
|
||||
const LEADING_RAIL_SIZE = 16;
|
||||
const HOST_ROW_ICON_SIZE = 14;
|
||||
type RenderHostOption = NonNullable<ComboboxProps["renderOption"]>;
|
||||
|
||||
const ThemedCheck = withUnistyles(Check);
|
||||
const ThemedPlus = withUnistyles(Plus);
|
||||
const ThemedServer = withUnistyles(Server);
|
||||
const mutedIconMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
|
||||
|
||||
export interface HostPickerHost {
|
||||
serverId: string;
|
||||
label: string;
|
||||
@@ -62,166 +36,122 @@ export function HostStatusDotSlot({ serverId }: { serverId: string }): ReactElem
|
||||
);
|
||||
}
|
||||
|
||||
// Standard secure/plain web ports carry no information in the host display, so
|
||||
// "relay.paseo.sh:443" reads as "relay.paseo.sh" while "127.0.0.1:6767" is kept.
|
||||
function formatConnectionEndpoint(endpoint: string): string {
|
||||
return endpoint.replace(/:(?:443|80)$/, "");
|
||||
}
|
||||
|
||||
// Socket/pipe transports have no host:port — their endpoint is a filesystem
|
||||
// path, so they read as "Local". TCP and relay show the address being used.
|
||||
function formatActiveConnectionLabel(connection: ActiveConnection): string {
|
||||
if (connection.type === "directSocket" || connection.type === "directPipe") {
|
||||
return "Local";
|
||||
}
|
||||
return formatConnectionEndpoint(connection.endpoint);
|
||||
}
|
||||
|
||||
export interface HostPickerOptionProps {
|
||||
serverId: string;
|
||||
label: string;
|
||||
appearance: HostAppearance;
|
||||
showActiveConnection: boolean;
|
||||
selected?: boolean;
|
||||
active: boolean;
|
||||
onPress: () => void;
|
||||
onOpenHostSettings?: (serverId: string) => void;
|
||||
testID?: string;
|
||||
}
|
||||
|
||||
export function HostPickerOption({
|
||||
serverId,
|
||||
label,
|
||||
appearance,
|
||||
showActiveConnection,
|
||||
selected,
|
||||
active,
|
||||
onPress,
|
||||
onOpenHostSettings,
|
||||
testID,
|
||||
}: HostPickerOptionProps): ReactElement {
|
||||
const status = useHostRuntimeConnectionStatus(serverId);
|
||||
const detectedMachineKind = useSessionStore(
|
||||
(state) => state.sessions[serverId]?.serverInfo?.machineKind ?? null,
|
||||
);
|
||||
const resolvedIcon = resolveHostIcon({ appearance, detectedMachineKind });
|
||||
const [hovered, setHovered] = useState(false);
|
||||
const handlePointerEnter = useCallback(() => setHovered(true), []);
|
||||
const handlePointerLeave = useCallback(() => setHovered(false), []);
|
||||
const isOffline = status === "offline" || status === "error";
|
||||
const { theme } = useUnistyles();
|
||||
const activeConnection = useHostRuntimeSnapshot(serverId)?.activeConnection ?? null;
|
||||
const connectionLabel =
|
||||
showActiveConnection && activeConnection
|
||||
? formatActiveConnectionLabel(activeConnection)
|
||||
: undefined;
|
||||
const leadingSlot = useMemo(() => <HostStatusDotSlot serverId={serverId} />, [serverId]);
|
||||
const handleSettingsPress = useCallback(() => {
|
||||
onOpenHostSettings?.(serverId);
|
||||
}, [onOpenHostSettings, serverId]);
|
||||
const trailingAction = useMemo(() => {
|
||||
if (!onOpenHostSettings) return undefined;
|
||||
return (
|
||||
<Pressable
|
||||
onPress={handleSettingsPress}
|
||||
style={styles.settingsAction}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={`Open ${label} settings`}
|
||||
>
|
||||
<Settings size={theme.iconSize.sm} color={theme.colors.foregroundMuted} />
|
||||
</Pressable>
|
||||
);
|
||||
}, [
|
||||
handleSettingsPress,
|
||||
label,
|
||||
onOpenHostSettings,
|
||||
theme.colors.foregroundMuted,
|
||||
theme.iconSize.sm,
|
||||
]);
|
||||
|
||||
return (
|
||||
<View
|
||||
style={styles.rowEnvelope}
|
||||
onPointerEnter={handlePointerEnter}
|
||||
onPointerLeave={handlePointerLeave}
|
||||
>
|
||||
<PressHighlight
|
||||
testID={testID}
|
||||
onPress={onPress}
|
||||
highlightStyle={styles.rowHighlighted}
|
||||
style={[styles.hostRow, (hovered || active) && styles.rowHighlighted]}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={label}
|
||||
>
|
||||
<View style={styles.leadingRailSlot}>
|
||||
<HostStatusDot serverId={serverId} />
|
||||
</View>
|
||||
<View style={styles.hostBody}>
|
||||
<View style={styles.hostHeaderRow}>
|
||||
<HostIconGlyph
|
||||
icon={resolvedIcon}
|
||||
color={appearance.color}
|
||||
size={HOST_ROW_ICON_SIZE}
|
||||
style={styles.hostGlyph}
|
||||
/>
|
||||
<Text style={[styles.hostName, isOffline && styles.hostNameMuted]} numberOfLines={1}>
|
||||
{label}
|
||||
</Text>
|
||||
</View>
|
||||
<HostConnectionLine serverId={serverId} />
|
||||
</View>
|
||||
<View style={styles.hostTrailing}>
|
||||
<HostLatencyLabel serverId={serverId} />
|
||||
{selected ? <ThemedCheck size={ICON_SIZE.sm} uniProps={mutedIconMapping} /> : null}
|
||||
</View>
|
||||
</PressHighlight>
|
||||
</View>
|
||||
<ComboboxItem
|
||||
label={label}
|
||||
description={connectionLabel}
|
||||
leadingSlot={leadingSlot}
|
||||
trailingAction={trailingAction}
|
||||
selected={selected}
|
||||
active={active}
|
||||
onPress={onPress}
|
||||
testID={testID}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function AllHostsOption({
|
||||
const SYSTEM_HOST_PICKER_OPTION_LABELS: Record<"add" | "all" | "enableBuiltInDaemon", string> = {
|
||||
add: "Add host",
|
||||
all: "All hosts",
|
||||
enableBuiltInDaemon: "Enable built-in daemon",
|
||||
};
|
||||
|
||||
function SystemHostPickerOption({
|
||||
active,
|
||||
selected,
|
||||
onPress,
|
||||
kind,
|
||||
testID,
|
||||
}: {
|
||||
active: boolean;
|
||||
selected?: boolean;
|
||||
onPress: () => void;
|
||||
kind: "add" | "all" | "enableBuiltInDaemon";
|
||||
testID?: string;
|
||||
}): ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const [hovered, setHovered] = useState(false);
|
||||
const handlePointerEnter = useCallback(() => setHovered(true), []);
|
||||
const handlePointerLeave = useCallback(() => setHovered(false), []);
|
||||
const label = t("sidebar.display.hostFilter.all");
|
||||
|
||||
return (
|
||||
<View
|
||||
style={styles.rowEnvelope}
|
||||
onPointerEnter={handlePointerEnter}
|
||||
onPointerLeave={handlePointerLeave}
|
||||
>
|
||||
<PressHighlight
|
||||
testID={testID}
|
||||
onPress={onPress}
|
||||
highlightStyle={styles.rowHighlighted}
|
||||
style={[styles.actionRow, (hovered || active) && styles.rowHighlighted]}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={label}
|
||||
>
|
||||
<View style={styles.leadingRailSlot}>
|
||||
<ThemedServer size={LEADING_RAIL_SIZE} uniProps={mutedIconMapping} />
|
||||
</View>
|
||||
<Text style={styles.actionLabel} numberOfLines={1}>
|
||||
{label}
|
||||
</Text>
|
||||
{selected ? <ThemedCheck size={ICON_SIZE.sm} uniProps={mutedIconMapping} /> : null}
|
||||
</PressHighlight>
|
||||
</View>
|
||||
const { theme } = useUnistyles();
|
||||
const Icon = kind === "add" ? Plus : Server;
|
||||
const label = SYSTEM_HOST_PICKER_OPTION_LABELS[kind];
|
||||
const leadingSlot = useMemo(
|
||||
() => <Icon size={theme.iconSize.sm} color={theme.colors.foregroundMuted} />,
|
||||
[Icon, theme.colors.foregroundMuted, theme.iconSize.sm],
|
||||
);
|
||||
}
|
||||
|
||||
function ActionOptionRow({
|
||||
kind,
|
||||
active,
|
||||
showDivider,
|
||||
onPress,
|
||||
testID,
|
||||
}: {
|
||||
kind: "add" | "enableBuiltInDaemon";
|
||||
active: boolean;
|
||||
showDivider: boolean;
|
||||
onPress: () => void;
|
||||
testID?: string;
|
||||
}): ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const [hovered, setHovered] = useState(false);
|
||||
const handlePointerEnter = useCallback(() => setHovered(true), []);
|
||||
const handlePointerLeave = useCallback(() => setHovered(false), []);
|
||||
const label = kind === "add" ? t("settings.addHost") : t("settings.enableBuiltInDaemon");
|
||||
|
||||
return (
|
||||
<View>
|
||||
{showDivider ? <View style={styles.actionSectionDivider} /> : null}
|
||||
<View
|
||||
style={styles.rowEnvelope}
|
||||
onPointerEnter={handlePointerEnter}
|
||||
onPointerLeave={handlePointerLeave}
|
||||
>
|
||||
<PressHighlight
|
||||
testID={testID}
|
||||
onPress={onPress}
|
||||
highlightStyle={styles.rowHighlighted}
|
||||
style={[styles.actionRow, (hovered || active) && styles.rowHighlighted]}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={label}
|
||||
>
|
||||
<View style={styles.leadingRailSlot}>
|
||||
{kind === "add" ? (
|
||||
<ThemedPlus size={LEADING_RAIL_SIZE} uniProps={mutedIconMapping} />
|
||||
) : (
|
||||
<ThemedServer size={LEADING_RAIL_SIZE} uniProps={mutedIconMapping} />
|
||||
)}
|
||||
</View>
|
||||
<Text style={styles.actionLabel} numberOfLines={1}>
|
||||
{label}
|
||||
</Text>
|
||||
</PressHighlight>
|
||||
</View>
|
||||
</View>
|
||||
<ComboboxItem
|
||||
label={label}
|
||||
leadingSlot={leadingSlot}
|
||||
selected={selected}
|
||||
active={active}
|
||||
onPress={onPress}
|
||||
testID={testID}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -238,6 +168,7 @@ export interface HostPickerProps {
|
||||
includeEnableBuiltInDaemon?: boolean;
|
||||
onEnableBuiltInDaemon?: () => void;
|
||||
showActiveConnection?: boolean;
|
||||
onOpenHostSettings?: (serverId: string) => void;
|
||||
searchable?: boolean;
|
||||
title?: string;
|
||||
desktopPlacement?: ComboboxProps["desktopPlacement"];
|
||||
@@ -259,85 +190,74 @@ export function HostPicker({
|
||||
onAddHost,
|
||||
includeEnableBuiltInDaemon,
|
||||
onEnableBuiltInDaemon,
|
||||
showActiveConnection,
|
||||
onOpenHostSettings,
|
||||
searchable,
|
||||
title,
|
||||
desktopPlacement = "bottom-start",
|
||||
desktopMinWidth = DEFAULT_DESKTOP_MIN_WIDTH,
|
||||
desktopMinWidth,
|
||||
addHostTestID,
|
||||
hostOptionTestID,
|
||||
children,
|
||||
}: HostPickerProps): ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const localServerId = useLocalDaemonServerId();
|
||||
const allHostProfiles = useHosts();
|
||||
const orderedHosts = useMemo(
|
||||
() => orderHostsLocalFirst(hosts, localServerId),
|
||||
[hosts, localServerId],
|
||||
);
|
||||
|
||||
const appearanceByServerId = useMemo(() => {
|
||||
const map = new Map<string, HostAppearance>();
|
||||
for (const profile of allHostProfiles) {
|
||||
map.set(profile.serverId, profile.appearance);
|
||||
}
|
||||
return map;
|
||||
}, [allHostProfiles]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
getHostRuntimeStore().refreshActiveLatencies(orderedHosts.map((host) => host.serverId));
|
||||
}, [open, orderedHosts]);
|
||||
|
||||
const options = useMemo(() => {
|
||||
const hostOptions = orderedHosts.map((host) => ({ id: host.serverId, label: host.label }));
|
||||
if (includeAllHost) {
|
||||
hostOptions.unshift({ id: ALL_HOSTS_OPTION_ID, label: t("sidebar.display.hostFilter.all") });
|
||||
}
|
||||
if (includeAddHost) {
|
||||
hostOptions.push({ id: ADD_HOST_OPTION_ID, label: t("settings.addHost") });
|
||||
}
|
||||
if (includeEnableBuiltInDaemon) {
|
||||
if (includeAllHost) hostOptions.unshift({ id: ALL_HOSTS_OPTION_ID, label: "All hosts" });
|
||||
if (includeAddHost) hostOptions.push({ id: ADD_HOST_OPTION_ID, label: "Add host" });
|
||||
if (includeEnableBuiltInDaemon)
|
||||
hostOptions.push({
|
||||
id: ENABLE_BUILT_IN_DAEMON_OPTION_ID,
|
||||
label: t("settings.enableBuiltInDaemon"),
|
||||
label: "Enable built-in daemon",
|
||||
});
|
||||
}
|
||||
return hostOptions;
|
||||
}, [orderedHosts, includeAllHost, includeAddHost, includeEnableBuiltInDaemon, t]);
|
||||
|
||||
let firstActionOptionId: string | null = null;
|
||||
if (includeAddHost) {
|
||||
firstActionOptionId = ADD_HOST_OPTION_ID;
|
||||
} else if (includeEnableBuiltInDaemon) {
|
||||
firstActionOptionId = ENABLE_BUILT_IN_DAEMON_OPTION_ID;
|
||||
}
|
||||
}, [orderedHosts, includeAllHost, includeAddHost, includeEnableBuiltInDaemon]);
|
||||
|
||||
const isSearchable = searchable === true && orderedHosts.length > SEARCHABLE_THRESHOLD;
|
||||
const resolvedTitle = title ?? t("sidebar.actions.hosts");
|
||||
|
||||
const handleSelect = useCallback(
|
||||
(id: string) => {
|
||||
if (id === ADD_HOST_OPTION_ID) {
|
||||
onOpenChange(false);
|
||||
onAddHost?.();
|
||||
return;
|
||||
}
|
||||
if (id === ENABLE_BUILT_IN_DAEMON_OPTION_ID) {
|
||||
onOpenChange(false);
|
||||
} else if (id === ENABLE_BUILT_IN_DAEMON_OPTION_ID) {
|
||||
onEnableBuiltInDaemon?.();
|
||||
return;
|
||||
} else {
|
||||
onSelect(id);
|
||||
}
|
||||
onSelect(id);
|
||||
onOpenChange(false);
|
||||
},
|
||||
[onAddHost, onEnableBuiltInDaemon, onOpenChange, onSelect],
|
||||
);
|
||||
|
||||
const handleOpenHostSettings = useCallback(
|
||||
(serverId: string) => {
|
||||
onOpenHostSettings?.(serverId);
|
||||
onOpenChange(false);
|
||||
},
|
||||
[onOpenHostSettings, onOpenChange],
|
||||
);
|
||||
|
||||
const renderOption = useCallback<RenderHostOption>(
|
||||
({ option, selected, active, onPress }) => {
|
||||
if (option.id === ADD_HOST_OPTION_ID) {
|
||||
return (
|
||||
<SystemHostPickerOption
|
||||
kind="add"
|
||||
active={active}
|
||||
onPress={onPress}
|
||||
testID={addHostTestID}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (option.id === ALL_HOSTS_OPTION_ID) {
|
||||
return (
|
||||
<AllHostsOption
|
||||
<SystemHostPickerOption
|
||||
kind="all"
|
||||
active={active}
|
||||
selected={selected}
|
||||
onPress={onPress}
|
||||
@@ -345,48 +265,30 @@ export function HostPicker({
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (option.id === ADD_HOST_OPTION_ID) {
|
||||
return (
|
||||
<ActionOptionRow
|
||||
kind="add"
|
||||
active={active}
|
||||
showDivider={firstActionOptionId === ADD_HOST_OPTION_ID && orderedHosts.length > 0}
|
||||
onPress={onPress}
|
||||
testID={addHostTestID}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (option.id === ENABLE_BUILT_IN_DAEMON_OPTION_ID) {
|
||||
return (
|
||||
<ActionOptionRow
|
||||
kind="enableBuiltInDaemon"
|
||||
active={active}
|
||||
showDivider={
|
||||
firstActionOptionId === ENABLE_BUILT_IN_DAEMON_OPTION_ID && orderedHosts.length > 0
|
||||
}
|
||||
onPress={onPress}
|
||||
/>
|
||||
<SystemHostPickerOption kind="enableBuiltInDaemon" active={active} onPress={onPress} />
|
||||
);
|
||||
}
|
||||
const appearance = appearanceByServerId.get(option.id) ?? defaultHostAppearance();
|
||||
return (
|
||||
<HostPickerOption
|
||||
serverId={option.id}
|
||||
label={option.label}
|
||||
appearance={appearance}
|
||||
showActiveConnection={showActiveConnection === true}
|
||||
selected={selected}
|
||||
active={active}
|
||||
onPress={onPress}
|
||||
onOpenHostSettings={onOpenHostSettings ? handleOpenHostSettings : undefined}
|
||||
testID={hostOptionTestID?.(option.id)}
|
||||
/>
|
||||
);
|
||||
},
|
||||
[
|
||||
addHostTestID,
|
||||
appearanceByServerId,
|
||||
firstActionOptionId,
|
||||
hostOptionTestID,
|
||||
orderedHosts.length,
|
||||
onOpenHostSettings,
|
||||
showActiveConnection,
|
||||
handleOpenHostSettings,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -399,8 +301,8 @@ export function HostPicker({
|
||||
onSelect={handleSelect}
|
||||
renderOption={renderOption}
|
||||
searchable={isSearchable}
|
||||
searchPlaceholder={t("sidebar.host.searchPlaceholder")}
|
||||
title={resolvedTitle}
|
||||
searchPlaceholder="Search hosts"
|
||||
title={title ?? "Host"}
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
anchorRef={anchorRef}
|
||||
@@ -412,86 +314,16 @@ export function HostPicker({
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
settingsAction: {
|
||||
flex: 1,
|
||||
justifyContent: "center",
|
||||
paddingLeft: theme.spacing[1],
|
||||
paddingRight: theme.spacing[3],
|
||||
},
|
||||
statusDotSlot: {
|
||||
width: theme.iconSize.sm,
|
||||
height: theme.iconSize.sm,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
rowEnvelope: {
|
||||
position: "relative",
|
||||
},
|
||||
// Shared leading rail: the status dot on host rows and the '+' / All hosts glyph share one
|
||||
// centered 16px column aligned to the first line's 18px line-height.
|
||||
leadingRailSlot: {
|
||||
width: LEADING_RAIL_SIZE,
|
||||
height: 18,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
flexShrink: 0,
|
||||
},
|
||||
hostRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "flex-start",
|
||||
gap: theme.spacing[2],
|
||||
marginHorizontal: theme.spacing[1],
|
||||
paddingHorizontal: theme.spacing[2],
|
||||
paddingVertical: theme.spacing[2],
|
||||
borderRadius: theme.borderRadius.md,
|
||||
},
|
||||
rowHighlighted: {
|
||||
backgroundColor: theme.colors.surface1,
|
||||
},
|
||||
hostBody: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
gap: 2,
|
||||
},
|
||||
hostHeaderRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: 6,
|
||||
minWidth: 0,
|
||||
},
|
||||
hostGlyph: {
|
||||
flexShrink: 0,
|
||||
},
|
||||
hostName: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
fontSize: theme.fontSize.base,
|
||||
lineHeight: 18,
|
||||
color: theme.colors.foreground,
|
||||
},
|
||||
hostNameMuted: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
},
|
||||
hostTrailing: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
height: 18,
|
||||
gap: theme.spacing[2],
|
||||
flexShrink: 0,
|
||||
},
|
||||
actionSectionDivider: {
|
||||
height: theme.borderWidth[1],
|
||||
backgroundColor: theme.colors.border,
|
||||
marginVertical: theme.spacing[1],
|
||||
},
|
||||
actionRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
marginHorizontal: theme.spacing[1],
|
||||
paddingHorizontal: theme.spacing[2],
|
||||
paddingVertical: theme.spacing[2],
|
||||
borderRadius: theme.borderRadius.md,
|
||||
},
|
||||
actionLabel: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
fontSize: theme.fontSize.base,
|
||||
lineHeight: 18,
|
||||
color: theme.colors.foreground,
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
import Svg, { Circle } from "react-native-svg";
|
||||
|
||||
const TAILSCALE_DOTS = [3, 12, 21].flatMap((cy, row) =>
|
||||
[3, 12, 21].map((cx, column) => ({
|
||||
cx,
|
||||
cy,
|
||||
// The Tailscale mark is a 3x3 dot grid with a solid T (middle row + bottom center).
|
||||
solid: row === 1 || (row === 2 && column === 1),
|
||||
})),
|
||||
);
|
||||
|
||||
export interface TailscaleIconProps {
|
||||
size?: number;
|
||||
color?: string;
|
||||
}
|
||||
|
||||
export function TailscaleIcon({ size = 12, color = "currentColor" }: TailscaleIconProps) {
|
||||
return (
|
||||
<Svg width={size} height={size} viewBox="0 0 24 24" fill={color}>
|
||||
{TAILSCALE_DOTS.map((dot) => (
|
||||
<Circle
|
||||
key={`${dot.cx}:${dot.cy}`}
|
||||
cx={dot.cx}
|
||||
cy={dot.cy}
|
||||
r={3}
|
||||
fill={color}
|
||||
opacity={dot.solid ? 1 : 0.3}
|
||||
/>
|
||||
))}
|
||||
</Svg>
|
||||
);
|
||||
}
|
||||
@@ -388,10 +388,10 @@ function SidebarHostPicker({
|
||||
includeAddHost
|
||||
onAddHost={onAddHost}
|
||||
showActiveConnection
|
||||
onOpenHostSettings={onOpenHostSettings}
|
||||
searchable
|
||||
title={label}
|
||||
desktopPlacement="top-start"
|
||||
desktopMinWidth={328}
|
||||
desktopMinWidth={240}
|
||||
addHostTestID="sidebar-host-add"
|
||||
hostOptionTestID={sidebarHostOptionTestID}
|
||||
>
|
||||
|
||||
@@ -1,119 +0,0 @@
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { within } from "@testing-library/dom";
|
||||
import { userEvent } from "vitest/browser";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { I18nextProvider } from "react-i18next";
|
||||
import type { ToastApi } from "@/components/toast-host";
|
||||
import { ToastApiProvider } from "@/contexts/toast-api-context";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import { BlockCopyButton } from "./block-copy-button";
|
||||
|
||||
const LABEL = "Copy quote";
|
||||
|
||||
let errors: string[] = [];
|
||||
const toast: ToastApi = {
|
||||
show: () => () => {},
|
||||
copied: () => {},
|
||||
error: (message) => errors.push(message),
|
||||
};
|
||||
|
||||
describe("BlockCopyButton", () => {
|
||||
let root: Root;
|
||||
let host: HTMLDivElement;
|
||||
|
||||
beforeEach(async () => {
|
||||
await i18n.changeLanguage("en");
|
||||
errors = [];
|
||||
host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
root = createRoot(host);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
flushSync(() => root.unmount());
|
||||
host.remove();
|
||||
});
|
||||
|
||||
function render(onCopy: () => Promise<boolean>, visible = true) {
|
||||
flushSync(() =>
|
||||
root.render(
|
||||
<I18nextProvider i18n={i18n}>
|
||||
<ToastApiProvider api={toast}>
|
||||
<BlockCopyButton onCopy={onCopy} visible={visible} label={LABEL} />
|
||||
</ToastApiProvider>
|
||||
</I18nextProvider>,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function button(name = LABEL): HTMLElement {
|
||||
return within(host).getByRole("button", { name });
|
||||
}
|
||||
|
||||
it("shows Copied after a write and returns to its label", async () => {
|
||||
let calls = 0;
|
||||
render(async () => {
|
||||
calls += 1;
|
||||
return true;
|
||||
});
|
||||
|
||||
await userEvent.click(button());
|
||||
await vi.waitFor(() => expect(button("Copied")).toBeTruthy());
|
||||
await vi.waitFor(() => expect(button()).toBeTruthy(), { timeout: 2500 });
|
||||
expect(calls).toBe(1);
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["resolves false", async () => false],
|
||||
[
|
||||
"rejects",
|
||||
async (): Promise<boolean> => {
|
||||
throw new Error("Clipboard denied");
|
||||
},
|
||||
],
|
||||
])("tells the user and never shows Copied when the write %s", async (_case, failure) => {
|
||||
let calls = 0;
|
||||
render(() => {
|
||||
calls += 1;
|
||||
return calls === 1 ? failure() : Promise.resolve(true);
|
||||
});
|
||||
|
||||
await userEvent.click(button());
|
||||
await vi.waitFor(() => expect(errors).toEqual(["Unable to copy"]));
|
||||
expect(within(host).queryByRole("button", { name: "Copied" })).toBeNull();
|
||||
|
||||
await userEvent.click(button());
|
||||
await vi.waitFor(() => expect(button("Copied")).toBeTruthy());
|
||||
expect(calls).toBe(2);
|
||||
});
|
||||
|
||||
it("does not write twice while a write is pending", async () => {
|
||||
let finish!: (written: boolean) => void;
|
||||
let calls = 0;
|
||||
render(() => {
|
||||
calls += 1;
|
||||
return new Promise<boolean>((resolve) => {
|
||||
finish = resolve;
|
||||
});
|
||||
});
|
||||
|
||||
await userEvent.click(button());
|
||||
await userEvent.click(button());
|
||||
expect(calls).toBe(1);
|
||||
|
||||
finish(true);
|
||||
await vi.waitFor(() => expect(button("Copied")).toBeTruthy());
|
||||
expect(calls).toBe(1);
|
||||
});
|
||||
|
||||
it("stays hidden until its block reveals it or it takes keyboard focus", async () => {
|
||||
render(async () => true, false);
|
||||
expect(getComputedStyle(button()).opacity).toBe("0");
|
||||
|
||||
await userEvent.tab();
|
||||
expect(document.activeElement).toBe(button());
|
||||
await vi.waitFor(() => expect(getComputedStyle(button()).opacity).toBe("1"));
|
||||
});
|
||||
});
|
||||
@@ -1,109 +0,0 @@
|
||||
import { memo, useCallback, useEffect, useRef, useState } from "react";
|
||||
import { View } from "react-native";
|
||||
import { Check, Copy } from "lucide-react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { markdownCopyDataSet } from "@/assistant-selection-copy/markup";
|
||||
import { mutedIconColorMapping } from "@/components/ui/icon-color";
|
||||
import { smallIconButtonChromeFrameSize } from "@/components/ui/icon-button-chrome";
|
||||
import { paneContentToolbarIconSize, ToolbarButton } from "@/components/ui/pane-content-toolbar";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { useToast } from "@/contexts/toast-api-context";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
|
||||
const ThemedCopy = withUnistyles(Copy, mutedIconColorMapping);
|
||||
const ThemedCheck = withUnistyles(Check, mutedIconColorMapping);
|
||||
|
||||
const COPIED_RESET_MS = 1500;
|
||||
|
||||
/** How far the copy glyph sits from the top and trailing edges of its block. */
|
||||
export function blockCopyGlyphInset(theme: Theme): number {
|
||||
return theme.spacing[2] + theme.spacing[1];
|
||||
}
|
||||
|
||||
interface BlockCopyButtonProps {
|
||||
/** Writes the block to the clipboard. Resolves false, or rejects, when nothing was written. */
|
||||
onCopy: () => Promise<boolean>;
|
||||
/** The block's own reveal state. Keyboard focus shows the button regardless. */
|
||||
visible: boolean;
|
||||
label: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The copy control in the top trailing corner of a Markdown block. The block is its
|
||||
* positioned ancestor.
|
||||
*/
|
||||
export const BlockCopyButton = memo(function BlockCopyButton({
|
||||
onCopy,
|
||||
visible,
|
||||
label,
|
||||
}: BlockCopyButtonProps) {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const compact = useIsCompactFormFactor();
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [focused, setFocused] = useState(false);
|
||||
const writing = useRef(false);
|
||||
const resetRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const focus = useCallback(() => setFocused(true), []);
|
||||
const blur = useCallback(() => setFocused(false), []);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (resetRef.current) clearTimeout(resetRef.current);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const handlePress = useCallback(async () => {
|
||||
// A slow clipboard must not queue a second write behind the first.
|
||||
if (writing.current) return;
|
||||
writing.current = true;
|
||||
const written = await onCopy()
|
||||
.catch(() => false)
|
||||
.finally(() => {
|
||||
writing.current = false;
|
||||
});
|
||||
if (!written) {
|
||||
toast.error(t("common.errors.unableToCopy"));
|
||||
return;
|
||||
}
|
||||
setCopied(true);
|
||||
if (resetRef.current) clearTimeout(resetRef.current);
|
||||
resetRef.current = setTimeout(() => setCopied(false), COPIED_RESET_MS);
|
||||
}, [onCopy, t, toast]);
|
||||
|
||||
const shown = visible || focused;
|
||||
const Glyph = copied ? ThemedCheck : ThemedCopy;
|
||||
return (
|
||||
<View style={styles.corner(compact)} dataSet={markdownCopyDataSet.ignore}>
|
||||
<ToolbarButton
|
||||
compact={compact}
|
||||
label={copied ? t("message.actions.copied") : label}
|
||||
onPress={handlePress}
|
||||
onFocus={focus}
|
||||
onBlur={blur}
|
||||
style={shown ? styles.shown : styles.hidden}
|
||||
>
|
||||
<Glyph size={paneContentToolbarIconSize(compact)} />
|
||||
</ToolbarButton>
|
||||
</View>
|
||||
);
|
||||
});
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
// The glyph, not the button frame, sits on the inset; the frame overhangs it.
|
||||
corner: (compact: boolean) => {
|
||||
const frameOverhang =
|
||||
(smallIconButtonChromeFrameSize(compact) - paneContentToolbarIconSize(compact)) / 2;
|
||||
const inset = blockCopyGlyphInset(theme) - frameOverhang;
|
||||
return {
|
||||
position: "absolute" as const,
|
||||
top: inset,
|
||||
right: inset,
|
||||
pointerEvents: "box-none" as const,
|
||||
};
|
||||
},
|
||||
shown: { opacity: 1, pointerEvents: "auto" },
|
||||
hidden: { opacity: 0, pointerEvents: "none" },
|
||||
}));
|
||||
@@ -5,10 +5,6 @@ import { useTranslation } from "react-i18next";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { HighlightedCodeBlock } from "@/components/highlighted-code-block";
|
||||
import { ZoomableViewport } from "@/components/zoomable-viewport";
|
||||
import {
|
||||
MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE,
|
||||
MARKDOWN_COPY_LANGUAGE_ATTRIBUTE,
|
||||
} from "@/assistant-selection-copy/markup";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import type { MarkdownFenceRendererProps } from "./types";
|
||||
import { MermaidFullscreenViewer } from "./fullscreen-viewer.web";
|
||||
@@ -85,16 +81,6 @@ function MermaidFenceHostImpl({
|
||||
[visible],
|
||||
);
|
||||
const sourceVisible = !diagramVisible;
|
||||
// A visible diagram stands in for its fence, so copying the surrounding block takes
|
||||
// the source from here: the revision on screen, which lags `code` while a streamed
|
||||
// revision renders. The source view copies as its own code block.
|
||||
const diagramCopyAttributes =
|
||||
diagramVisible && visible
|
||||
? {
|
||||
[MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE]: visible.source,
|
||||
[MARKDOWN_COPY_LANGUAGE_ATTRIBUTE]: "mermaid",
|
||||
}
|
||||
: null;
|
||||
const viewportStyle = diagramVisible ? diagramStyle : measuringStyle;
|
||||
|
||||
return (
|
||||
@@ -125,7 +111,7 @@ function MermaidFenceHostImpl({
|
||||
) : null}
|
||||
</View>
|
||||
) : null}
|
||||
<div inert={!diagramVisible} style={boundaryStyle} {...diagramCopyAttributes}>
|
||||
<div inert={!diagramVisible} style={boundaryStyle}>
|
||||
<ZoomableViewport
|
||||
accessibilityLabel={t("message.diagram.diagram")}
|
||||
actions={actions}
|
||||
|
||||
@@ -1,71 +0,0 @@
|
||||
import { useCallback, useMemo, useRef, useState } from "react";
|
||||
import { withUnistyles } from "react-native-unistyles";
|
||||
import type { BlockquoteRendererProps } from "react-native-enriched-markdown";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { createElementClipboardContent } from "@/assistant-selection-copy/content.web";
|
||||
import { smallIconButtonChromeFrameSize } from "@/components/ui/icon-button-chrome";
|
||||
import { paneContentToolbarIconSize } from "@/components/ui/pane-content-toolbar";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { writeClipboardContent } from "@/utils/rich-clipboard";
|
||||
import { getDefaultMarkdownClipboardEnvironment } from "@/utils/rich-clipboard-default-environment";
|
||||
import { BlockCopyButton, blockCopyGlyphInset } from "./block-copy-button";
|
||||
|
||||
interface WebBlockquoteProps extends BlockquoteRendererProps {
|
||||
copyGlyphInset: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Room the quote reserves so the control never covers its text. Compact layouts always
|
||||
* show the control, so it gets a band above the body and the text keeps the full width.
|
||||
* Wide layouts reveal it on hover, where a band would leave an empty strip above every
|
||||
* quote, so the text wraps short of it instead.
|
||||
*/
|
||||
function copyRoom(compact: boolean, glyphInset: number) {
|
||||
if (compact) {
|
||||
return { paddingTop: glyphInset + paneContentToolbarIconSize(compact) + glyphInset };
|
||||
}
|
||||
return { paddingRight: smallIconButtonChromeFrameSize(compact) + glyphInset };
|
||||
}
|
||||
|
||||
/** A quote with a control that copies its body, for drafts an agent wrote to be pasted elsewhere. */
|
||||
export const WebBlockquote = withUnistyles(
|
||||
function WebBlockquote({ blockquoteProps, children, copyGlyphInset }: WebBlockquoteProps) {
|
||||
const { t } = useTranslation();
|
||||
const quote = useRef<HTMLQuoteElement>(null);
|
||||
const [hovered, setHovered] = useState(false);
|
||||
const compact = useIsCompactFormFactor();
|
||||
const enter = useCallback(() => setHovered(true), []);
|
||||
const leave = useCallback(() => setHovered(false), []);
|
||||
const style = useMemo(
|
||||
() => ({
|
||||
...blockquoteProps.style,
|
||||
position: "relative" as const,
|
||||
...copyRoom(compact, copyGlyphInset),
|
||||
}),
|
||||
[blockquoteProps.style, compact, copyGlyphInset],
|
||||
);
|
||||
const copy = useCallback(async () => {
|
||||
// Read the rendered body at press time: a streaming quote copies what it shows now.
|
||||
const content = quote.current && createElementClipboardContent(quote.current);
|
||||
if (!content) return false;
|
||||
return writeClipboardContent(content, getDefaultMarkdownClipboardEnvironment());
|
||||
}, []);
|
||||
return (
|
||||
<blockquote
|
||||
{...blockquoteProps}
|
||||
ref={quote}
|
||||
style={style}
|
||||
onPointerEnter={enter}
|
||||
onPointerLeave={leave}
|
||||
>
|
||||
<BlockCopyButton
|
||||
onCopy={copy}
|
||||
visible={hovered || compact}
|
||||
label={t("message.actions.copyQuote")}
|
||||
/>
|
||||
{children}
|
||||
</blockquote>
|
||||
);
|
||||
},
|
||||
(theme) => ({ copyGlyphInset: blockCopyGlyphInset(theme) }),
|
||||
);
|
||||
@@ -14,7 +14,6 @@ import { HighlightedCodeBlock } from "@/components/highlighted-code-block";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import { MermaidFence } from "./fence/mermaid";
|
||||
import { isRecognizedLink, markdownLinkSource } from "./source";
|
||||
import { WebBlockquote } from "./quote-block.web";
|
||||
|
||||
const ThemedCodeBlock = withUnistyles(HighlightedCodeBlock);
|
||||
const codeStyle = (theme: Theme) => ({
|
||||
@@ -112,8 +111,4 @@ const styles = StyleSheet.create((theme) => ({
|
||||
},
|
||||
}));
|
||||
|
||||
export const WEB_RENDERERS: MarkdownRenderers = {
|
||||
codeBlock: WebCodeBlock,
|
||||
link: WebLink,
|
||||
blockquote: WebBlockquote,
|
||||
};
|
||||
export const WEB_RENDERERS: MarkdownRenderers = { codeBlock: WebCodeBlock, link: WebLink };
|
||||
|
||||
@@ -9,6 +9,7 @@ import { useRewindComposerRestore } from "./composer-restore";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { shouldRestoreComposerForRewindMode } from "./rewind-mode";
|
||||
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
||||
import { hostSupportsFeature } from "@/runtime/host-features";
|
||||
|
||||
interface UseRewindAgentMutationInput {
|
||||
serverId?: string;
|
||||
@@ -42,7 +43,16 @@ export function useRewindAgentMutation(input: UseRewindAgentMutationInput): {
|
||||
throw new Error(t("common.errors.daemonClientUnavailable"));
|
||||
}
|
||||
await input.client.rewindAgent(input.agentId, input.messageId, mode);
|
||||
if (mode !== "files") {
|
||||
// COMPAT(timelineRewindOperations): added in v0.14.1, remove after 2027-05-10. A daemon with
|
||||
// the feature delivers the rewind on the live timeline; an older one replaced the timeline
|
||||
// and this client has to read it again.
|
||||
const appliesLive =
|
||||
input.serverId !== undefined &&
|
||||
hostSupportsFeature(
|
||||
useSessionStore.getState().sessions[input.serverId]?.serverInfo,
|
||||
"timelineRewindOperations",
|
||||
);
|
||||
if (mode !== "files" && !appliesLive) {
|
||||
const cursor = input.serverId
|
||||
? useSessionStore
|
||||
.getState()
|
||||
|
||||
@@ -73,9 +73,6 @@ export { buildDesktopFrameStyle } from "./combobox-frame-style";
|
||||
|
||||
const IS_WEB = isWeb;
|
||||
const TRAILING_ACTION_DATASET = { comboboxTrailingAction: true };
|
||||
const FOOTER_DATASET = { comboboxFooter: true };
|
||||
const FOCUSED_COMBOBOX_ACTION_SELECTOR =
|
||||
'[data-combobox-trailing-action] button, [data-combobox-trailing-action] [role="button"], [data-combobox-footer] button, [data-combobox-footer] [role="button"]';
|
||||
|
||||
export type ComboboxOption = ComboboxOptionModel;
|
||||
export type ComboboxDesktopPlacement = "top-start" | "bottom-start";
|
||||
@@ -405,7 +402,6 @@ export function ComboboxEmpty({ children }: { children: ReactNode }): ReactEleme
|
||||
type RenderOptionFn = NonNullable<ComboboxProps["renderOption"]>;
|
||||
|
||||
interface OptionRowProps {
|
||||
index: number;
|
||||
option: ComboboxOption;
|
||||
selected: boolean;
|
||||
active: boolean;
|
||||
@@ -413,27 +409,20 @@ interface OptionRowProps {
|
||||
renderOption: RenderOptionFn | undefined;
|
||||
}
|
||||
|
||||
function OptionRow({ index, option, selected, active, onSelect, renderOption }: OptionRowProps) {
|
||||
function OptionRow({ option, selected, active, onSelect, renderOption }: OptionRowProps) {
|
||||
const handlePress = useCallback(() => onSelect(option.id), [onSelect, option.id]);
|
||||
const optionDataset = useMemo(() => ({ comboboxOptionIndex: String(index) }), [index]);
|
||||
if (renderOption) {
|
||||
return (
|
||||
<View dataSet={optionDataset}>
|
||||
{renderOption({ option, selected, active, onPress: handlePress })}
|
||||
</View>
|
||||
);
|
||||
return <View>{renderOption({ option, selected, active, onPress: handlePress })}</View>;
|
||||
}
|
||||
return (
|
||||
<View dataSet={optionDataset}>
|
||||
<ComboboxItem
|
||||
label={option.label}
|
||||
description={option.description}
|
||||
kind={option.kind}
|
||||
selected={selected}
|
||||
active={active}
|
||||
onPress={handlePress}
|
||||
/>
|
||||
</View>
|
||||
<ComboboxItem
|
||||
label={option.label}
|
||||
description={option.description}
|
||||
kind={option.kind}
|
||||
selected={selected}
|
||||
active={active}
|
||||
onPress={handlePress}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -462,7 +451,6 @@ function OptionsList({
|
||||
{options.map((opt, index) => (
|
||||
<OptionRow
|
||||
key={opt.id}
|
||||
index={index}
|
||||
option={opt}
|
||||
selected={opt.id === value}
|
||||
active={index === activeIndex}
|
||||
@@ -964,9 +952,8 @@ function dispatchDesktopKey(
|
||||
return true;
|
||||
}
|
||||
if (key === "Enter") {
|
||||
// Consume the shortcut but keep the browser's default button activation when the user moved
|
||||
// keyboard focus onto a trailing action or footer button inside the combobox.
|
||||
if (isWeb && document.activeElement?.matches(FOCUSED_COMBOBOX_ACTION_SELECTOR)) {
|
||||
// Consume the shortcut but keep the browser's default button activation.
|
||||
if (isWeb && document.activeElement?.matches("[data-combobox-trailing-action] button")) {
|
||||
return true;
|
||||
}
|
||||
if (input.orderedVisibleOptions.length === 0) return false;
|
||||
@@ -1140,12 +1127,7 @@ function ComboboxSheetFrame({ footer, children }: { footer?: ReactNode; children
|
||||
[safeAreaBottom],
|
||||
);
|
||||
const footerView = useMemo(
|
||||
() =>
|
||||
footer ? (
|
||||
<View style={footerStyle} dataSet={FOOTER_DATASET}>
|
||||
{footer}
|
||||
</View>
|
||||
) : undefined,
|
||||
() => (footer ? <View style={footerStyle}>{footer}</View> : undefined),
|
||||
[footer, footerStyle],
|
||||
);
|
||||
return (
|
||||
@@ -1359,11 +1341,7 @@ function DesktopComboboxBody(props: DesktopBodyProps): ReactElement | null {
|
||||
renderOption={props.renderOption}
|
||||
/>
|
||||
)}
|
||||
{props.footer ? (
|
||||
<View style={styles.footer} dataSet={FOOTER_DATASET}>
|
||||
{props.footer}
|
||||
</View>
|
||||
) : null}
|
||||
{props.footer ? <View style={styles.footer}>{props.footer}</View> : null}
|
||||
</FloatingSurface>
|
||||
</View>
|
||||
</OverlayLayerProvider>
|
||||
@@ -1619,30 +1597,6 @@ export function Combobox({
|
||||
setActiveIndex,
|
||||
);
|
||||
|
||||
// Keep activeIndex aligned when a keyboard user Tabs onto a specific option button on web.
|
||||
useEffect(() => {
|
||||
if (!IS_WEB || !isOpen || isMobile) return;
|
||||
const handleFocusIn = (event: FocusEvent) => {
|
||||
const target = event.target;
|
||||
if (!(target instanceof Element)) return;
|
||||
const optionEl = target.closest("[data-combobox-option-index]");
|
||||
if (!optionEl) return;
|
||||
const nextIndex = Number.parseInt(
|
||||
optionEl.getAttribute("data-combobox-option-index") ?? "",
|
||||
10,
|
||||
);
|
||||
if (
|
||||
Number.isInteger(nextIndex) &&
|
||||
nextIndex >= 0 &&
|
||||
nextIndex < orderedVisibleOptions.length
|
||||
) {
|
||||
setActiveIndex(nextIndex);
|
||||
}
|
||||
};
|
||||
document.addEventListener("focusin", handleFocusIn);
|
||||
return () => document.removeEventListener("focusin", handleFocusIn);
|
||||
}, [isMobile, isOpen, orderedVisibleOptions.length]);
|
||||
|
||||
const handleSelect = useCallback(
|
||||
(id: string) => {
|
||||
onSelect(id);
|
||||
|
||||
@@ -385,6 +385,16 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
|
||||
console.warn("[Session] timeline replacement refresh failed", { serverId, error });
|
||||
});
|
||||
};
|
||||
const onRewind = (message: SessionOutboundMessage) => {
|
||||
if (message.type !== "agent.timeline.rewind") return;
|
||||
const { agentId, epoch, seq, retireFromSeq } = message.payload;
|
||||
sync.applyStreamEvent(agentId, {
|
||||
event: { type: "rewind", retireFromSeq },
|
||||
seq,
|
||||
epoch,
|
||||
timestamp: new Date(),
|
||||
});
|
||||
};
|
||||
const sync = getHostRuntimeStore().createViewedTimelineOwner(serverId, {
|
||||
canCheckFreshness: () =>
|
||||
client.getLastServerInfoMessage()?.features?.timelineFreshnessCheck === true,
|
||||
@@ -395,6 +405,7 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
|
||||
update: (message) => {
|
||||
if (message.type === "agent_stream") onStream(message);
|
||||
else if (message.type === "agent.timeline.replacement") onReplacement(message);
|
||||
else if (message.type === "agent.timeline.rewind") onRewind(message);
|
||||
},
|
||||
});
|
||||
return observation;
|
||||
|
||||
@@ -11,13 +11,8 @@ import { i18n } from "@/i18n/i18next";
|
||||
|
||||
const DESKTOP_SETTINGS_QUERY_KEY = ["desktop-settings"] as const;
|
||||
|
||||
export type DesktopUpdateMode = "automatic" | "notify" | "off";
|
||||
|
||||
export interface DesktopSettings {
|
||||
releaseChannel: ReleaseChannel;
|
||||
updates: {
|
||||
mode: DesktopUpdateMode;
|
||||
};
|
||||
notifications: {
|
||||
playSound: boolean;
|
||||
};
|
||||
@@ -29,16 +24,12 @@ export interface DesktopSettings {
|
||||
|
||||
export interface DesktopSettingsPatch {
|
||||
releaseChannel?: ReleaseChannel;
|
||||
updates?: Partial<DesktopSettings["updates"]>;
|
||||
notifications?: Partial<DesktopSettings["notifications"]>;
|
||||
daemon?: Partial<DesktopSettings["daemon"]>;
|
||||
}
|
||||
|
||||
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
|
||||
releaseChannel: "stable",
|
||||
updates: {
|
||||
mode: "automatic",
|
||||
},
|
||||
notifications: {
|
||||
playSound: true,
|
||||
},
|
||||
@@ -158,24 +149,13 @@ export async function migrateLegacyDesktopSettings(input: {
|
||||
await invokeDesktopCommand("migrate_legacy_desktop_settings", input);
|
||||
}
|
||||
|
||||
function parseUpdateMode(value: unknown): DesktopUpdateMode {
|
||||
if (value === "automatic" || value === "notify" || value === "off") {
|
||||
return value;
|
||||
}
|
||||
return DEFAULT_DESKTOP_SETTINGS.updates.mode;
|
||||
}
|
||||
|
||||
function parseDesktopSettings(raw: unknown): DesktopSettings {
|
||||
const record = isRecord(raw) ? raw : {};
|
||||
const updates = isRecord(record.updates) ? record.updates : {};
|
||||
const notifications = isRecord(record.notifications) ? record.notifications : {};
|
||||
const daemon = isRecord(record.daemon) ? record.daemon : {};
|
||||
|
||||
return {
|
||||
releaseChannel: record.releaseChannel === "beta" ? "beta" : "stable",
|
||||
updates: {
|
||||
mode: parseUpdateMode(updates.mode),
|
||||
},
|
||||
notifications: {
|
||||
playSound:
|
||||
typeof notifications.playSound === "boolean"
|
||||
@@ -201,10 +181,6 @@ function mergeDesktopSettings(
|
||||
): DesktopSettings {
|
||||
return {
|
||||
releaseChannel: updates.releaseChannel ?? current.releaseChannel,
|
||||
updates: {
|
||||
...current.updates,
|
||||
...updates.updates,
|
||||
},
|
||||
notifications: {
|
||||
...current.notifications,
|
||||
...updates.notifications,
|
||||
@@ -219,7 +195,6 @@ function mergeDesktopSettings(
|
||||
function normalizePatch(updates: DesktopSettingsPatch): Record<string, unknown> {
|
||||
return {
|
||||
...(updates.releaseChannel ? { releaseChannel: updates.releaseChannel } : {}),
|
||||
...(updates.updates ? { updates: updates.updates } : {}),
|
||||
...(updates.notifications ? { notifications: updates.notifications } : {}),
|
||||
...(updates.daemon ? { daemon: updates.daemon } : {}),
|
||||
};
|
||||
|
||||
@@ -128,43 +128,6 @@ describe("desktop app updater — check", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("reports 'available' when an update is available to download without auto-downloading", async () => {
|
||||
const { updater, port } = createUpdater({ now: () => 42 });
|
||||
port.nextCheckResult(
|
||||
buildFakeCheckResult({
|
||||
hasUpdate: true,
|
||||
readyToInstall: false,
|
||||
downloading: false,
|
||||
latestVersion: "1.2.3",
|
||||
}),
|
||||
);
|
||||
|
||||
await updater.checkForUpdates({ releaseChannel: "stable" });
|
||||
|
||||
expect(updater.getSnapshot()).toMatchObject({
|
||||
status: "available",
|
||||
availableUpdate: { latestVersion: "1.2.3", readyToInstall: false, downloading: false },
|
||||
lastCheckedAt: 42,
|
||||
});
|
||||
});
|
||||
|
||||
it("tracks download progress updates and clears them once install completes", async () => {
|
||||
const { updater, port } = createUpdater();
|
||||
port.nextInstallResult(buildFakeInstallResult({ installed: true }));
|
||||
|
||||
updater.setDownloadProgress({
|
||||
version: "1.2.3",
|
||||
percent: 42.4,
|
||||
transferred: 42,
|
||||
total: 100,
|
||||
bytesPerSecond: 10,
|
||||
});
|
||||
expect(updater.getSnapshot().downloadProgress?.percent).toBe(42.4);
|
||||
|
||||
await updater.installUpdate({ releaseChannel: "stable" });
|
||||
expect(updater.getSnapshot().downloadProgress).toBeNull();
|
||||
});
|
||||
|
||||
it("reports 'up-to-date' when the check resolves with no update", async () => {
|
||||
const { updater, port } = createUpdater();
|
||||
port.nextCheckResult(buildFakeCheckResult({ hasUpdate: false, readyToInstall: false }));
|
||||
@@ -377,26 +340,6 @@ describe("desktop app updater — install", () => {
|
||||
expect(updater.getSnapshot().status).toBe("up-to-date");
|
||||
});
|
||||
|
||||
it("moves to 'error' instead of 'up-to-date' when the install returns an errorMessage", async () => {
|
||||
const { updater, port } = createUpdater();
|
||||
port.nextInstallResult(
|
||||
buildFakeInstallResult({
|
||||
installed: false,
|
||||
message: "Update failed: ECONNRESET",
|
||||
errorMessage: "ECONNRESET",
|
||||
}),
|
||||
);
|
||||
|
||||
await updater.installUpdate({ releaseChannel: "stable" });
|
||||
|
||||
expect(updater.getSnapshot()).toMatchObject({
|
||||
status: "error",
|
||||
errorMessage: "ECONNRESET",
|
||||
downloadProgress: null,
|
||||
isInstalling: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("reports the install error and moves to 'error' when the install throws", async () => {
|
||||
const { updater, port, reportedInstallErrors } = createUpdater();
|
||||
const error = new Error("install failed");
|
||||
@@ -519,47 +462,6 @@ describe("formatStatusText", () => {
|
||||
).toBe("Restart now");
|
||||
});
|
||||
|
||||
it("formats download-available and live download progress status text", () => {
|
||||
expect(
|
||||
formatStatusText({
|
||||
status: "available",
|
||||
availableUpdate: buildFakeCheckResult({
|
||||
hasUpdate: true,
|
||||
readyToInstall: false,
|
||||
downloading: false,
|
||||
latestVersion: "1.2.3",
|
||||
}),
|
||||
installMessage: null,
|
||||
lastCheckedAt: 42,
|
||||
formatVersion,
|
||||
formatLastCheckedAt,
|
||||
}),
|
||||
).toBe("Update available: v1.2.3. Last checked at time-42.");
|
||||
|
||||
expect(
|
||||
formatStatusText({
|
||||
status: "installing",
|
||||
availableUpdate: buildFakeCheckResult({
|
||||
hasUpdate: true,
|
||||
readyToInstall: false,
|
||||
downloading: false,
|
||||
latestVersion: "1.2.3",
|
||||
}),
|
||||
downloadProgress: {
|
||||
version: "1.2.3",
|
||||
percent: 64.6,
|
||||
transferred: 65,
|
||||
total: 100,
|
||||
bytesPerSecond: 10,
|
||||
},
|
||||
installMessage: null,
|
||||
lastCheckedAt: null,
|
||||
formatVersion,
|
||||
formatLastCheckedAt,
|
||||
}),
|
||||
).toBe("Downloading v1.2.3... 65%");
|
||||
});
|
||||
|
||||
it("uses the active app language for local status wrappers", async () => {
|
||||
await i18n.changeLanguage("zh-CN");
|
||||
try {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import type {
|
||||
DesktopAppUpdateCheckResult,
|
||||
DesktopAppUpdateCheckIntent,
|
||||
DesktopAppUpdateDownloadProgress,
|
||||
DesktopAppUpdateInstallResult,
|
||||
DesktopReleaseChannel,
|
||||
} from "@/desktop/updates/desktop-updates";
|
||||
@@ -22,7 +21,6 @@ export const PENDING_RECHECK_MS = 10_000;
|
||||
export interface DesktopAppUpdaterSnapshot {
|
||||
status: DesktopAppUpdateStatus;
|
||||
availableUpdate: DesktopAppUpdateCheckResult | null;
|
||||
downloadProgress: DesktopAppUpdateDownloadProgress | null;
|
||||
errorMessage: string | null;
|
||||
installMessage: string | null;
|
||||
lastCheckedAt: number | null;
|
||||
@@ -55,7 +53,6 @@ export interface DesktopAppUpdaterDeps {
|
||||
export interface DesktopAppUpdater {
|
||||
getSnapshot(): DesktopAppUpdaterSnapshot;
|
||||
subscribe(listener: () => void): () => void;
|
||||
setDownloadProgress(progress: DesktopAppUpdateDownloadProgress | null): void;
|
||||
checkForUpdates(options?: {
|
||||
releaseChannel: DesktopReleaseChannel;
|
||||
intent?: DesktopAppUpdateCheckIntent;
|
||||
@@ -69,7 +66,6 @@ export interface DesktopAppUpdater {
|
||||
interface InternalState {
|
||||
status: DesktopAppUpdateStatus;
|
||||
availableUpdate: DesktopAppUpdateCheckResult | null;
|
||||
downloadProgress: DesktopAppUpdateDownloadProgress | null;
|
||||
errorMessage: string | null;
|
||||
installMessage: string | null;
|
||||
lastCheckedAt: number | null;
|
||||
@@ -80,7 +76,6 @@ interface InternalState {
|
||||
const INITIAL_STATE: InternalState = {
|
||||
status: "idle",
|
||||
availableUpdate: null,
|
||||
downloadProgress: null,
|
||||
errorMessage: null,
|
||||
installMessage: null,
|
||||
lastCheckedAt: null,
|
||||
@@ -92,7 +87,6 @@ function buildSnapshot(state: InternalState): DesktopAppUpdaterSnapshot {
|
||||
return {
|
||||
status: state.status,
|
||||
availableUpdate: state.availableUpdate,
|
||||
downloadProgress: state.downloadProgress,
|
||||
errorMessage: state.errorMessage,
|
||||
installMessage: state.installMessage,
|
||||
lastCheckedAt: state.lastCheckedAt,
|
||||
@@ -108,113 +102,9 @@ function getErrorMessage(error: unknown): string {
|
||||
return String(error);
|
||||
}
|
||||
|
||||
function formatInstallingStatusText(input: {
|
||||
availableUpdate: DesktopAppUpdateCheckResult | null;
|
||||
downloadProgress: DesktopAppUpdateDownloadProgress | null;
|
||||
formatVersion: (version: string | null | undefined) => string;
|
||||
}): string {
|
||||
const { availableUpdate, downloadProgress, formatVersion } = input;
|
||||
if (downloadProgress == null) {
|
||||
return i18n.t("desktop.updates.status.installing");
|
||||
}
|
||||
const percent = Math.round(downloadProgress.percent);
|
||||
const version = downloadProgress.version ?? availableUpdate?.latestVersion;
|
||||
if (version) {
|
||||
return i18n.t("desktop.updates.status.downloadingVersionProgress", {
|
||||
version: formatVersion(version),
|
||||
percent,
|
||||
});
|
||||
}
|
||||
return i18n.t("desktop.updates.status.downloadingProgress", { percent });
|
||||
}
|
||||
|
||||
function formatPendingStatusText(input: {
|
||||
availableUpdate: DesktopAppUpdateCheckResult | null;
|
||||
downloadProgress: DesktopAppUpdateDownloadProgress | null;
|
||||
lastCheckedAt: number | null;
|
||||
formatVersion: (version: string | null | undefined) => string;
|
||||
formatLastCheckedAt: (timestamp: number) => string;
|
||||
}): string {
|
||||
const { availableUpdate, downloadProgress, lastCheckedAt, formatVersion, formatLastCheckedAt } =
|
||||
input;
|
||||
const time = lastCheckedAt != null ? formatLastCheckedAt(lastCheckedAt) : undefined;
|
||||
if (availableUpdate?.latestVersion) {
|
||||
const version = formatVersion(availableUpdate.latestVersion);
|
||||
if (downloadProgress != null) {
|
||||
return i18n.t(
|
||||
time !== undefined
|
||||
? "desktop.updates.status.pendingWithVersionProgressAndLastChecked"
|
||||
: "desktop.updates.status.pendingWithVersionProgress",
|
||||
{ version, percent: Math.round(downloadProgress.percent), time },
|
||||
);
|
||||
}
|
||||
return i18n.t(
|
||||
time !== undefined
|
||||
? "desktop.updates.status.pendingWithVersionAndLastChecked"
|
||||
: "desktop.updates.status.pendingWithVersion",
|
||||
{ version, time },
|
||||
);
|
||||
}
|
||||
if (time !== undefined) {
|
||||
return i18n.t("desktop.updates.status.pendingWithLastChecked", { time });
|
||||
}
|
||||
return i18n.t("desktop.updates.status.pending");
|
||||
}
|
||||
|
||||
function formatAvailableStatusText(input: {
|
||||
availableUpdate: DesktopAppUpdateCheckResult | null;
|
||||
lastCheckedAt: number | null;
|
||||
formatVersion: (version: string | null | undefined) => string;
|
||||
formatLastCheckedAt: (timestamp: number) => string;
|
||||
}): string {
|
||||
const { availableUpdate, lastCheckedAt, formatVersion, formatLastCheckedAt } = input;
|
||||
const time = lastCheckedAt != null ? formatLastCheckedAt(lastCheckedAt) : undefined;
|
||||
const isDownloadRequired =
|
||||
availableUpdate?.hasUpdate === true && availableUpdate.readyToInstall === false;
|
||||
if (availableUpdate?.latestVersion) {
|
||||
const version = formatVersion(availableUpdate.latestVersion);
|
||||
if (isDownloadRequired) {
|
||||
return i18n.t(
|
||||
time !== undefined
|
||||
? "desktop.updates.status.downloadAvailableWithVersionAndLastChecked"
|
||||
: "desktop.updates.status.downloadAvailableWithVersion",
|
||||
{ version, time },
|
||||
);
|
||||
}
|
||||
return i18n.t(
|
||||
time !== undefined
|
||||
? "desktop.updates.status.availableWithVersionAndLastChecked"
|
||||
: "desktop.updates.status.availableWithVersion",
|
||||
{ version, time },
|
||||
);
|
||||
}
|
||||
if (isDownloadRequired) {
|
||||
return time !== undefined
|
||||
? i18n.t("desktop.updates.status.downloadAvailableWithLastChecked", { time })
|
||||
: i18n.t("desktop.updates.status.downloadAvailable");
|
||||
}
|
||||
return time !== undefined
|
||||
? i18n.t("desktop.updates.status.availableWithLastChecked", { time })
|
||||
: i18n.t("desktop.updates.status.available");
|
||||
}
|
||||
|
||||
function resolveCheckOutcome(result: DesktopAppUpdateCheckResult): {
|
||||
status: DesktopAppUpdateStatus;
|
||||
availableUpdate: DesktopAppUpdateCheckResult | null;
|
||||
} {
|
||||
if (result.readyToInstall || (result.hasUpdate && !result.downloading)) {
|
||||
return { status: "available", availableUpdate: result };
|
||||
}
|
||||
if (result.hasUpdate) {
|
||||
return { status: "pending", availableUpdate: result };
|
||||
}
|
||||
return { status: "up-to-date", availableUpdate: null };
|
||||
}
|
||||
|
||||
export function formatStatusText(input: {
|
||||
status: DesktopAppUpdateStatus;
|
||||
availableUpdate: DesktopAppUpdateCheckResult | null;
|
||||
downloadProgress?: DesktopAppUpdateDownloadProgress | null;
|
||||
installMessage: string | null;
|
||||
lastCheckedAt: number | null;
|
||||
formatVersion: (version: string | null | undefined) => string;
|
||||
@@ -223,45 +113,79 @@ export function formatStatusText(input: {
|
||||
const {
|
||||
status,
|
||||
availableUpdate,
|
||||
downloadProgress = null,
|
||||
installMessage,
|
||||
lastCheckedAt,
|
||||
formatVersion,
|
||||
formatLastCheckedAt,
|
||||
} = input;
|
||||
|
||||
if (status === "checking") return i18n.t("desktop.updates.status.checking");
|
||||
if (status === "checking") {
|
||||
return i18n.t("desktop.updates.status.checking");
|
||||
}
|
||||
|
||||
if (status === "installing") {
|
||||
return formatInstallingStatusText({ availableUpdate, downloadProgress, formatVersion });
|
||||
return i18n.t("desktop.updates.status.installing");
|
||||
}
|
||||
|
||||
if (status === "up-to-date") {
|
||||
return lastCheckedAt != null
|
||||
? i18n.t("desktop.updates.status.upToDateWithLastChecked", {
|
||||
time: formatLastCheckedAt(lastCheckedAt),
|
||||
})
|
||||
: i18n.t("desktop.updates.status.upToDate");
|
||||
if (lastCheckedAt != null) {
|
||||
return i18n.t("desktop.updates.status.upToDateWithLastChecked", {
|
||||
time: formatLastCheckedAt(lastCheckedAt),
|
||||
});
|
||||
}
|
||||
return i18n.t("desktop.updates.status.upToDate");
|
||||
}
|
||||
|
||||
if (status === "pending") {
|
||||
return formatPendingStatusText({
|
||||
availableUpdate,
|
||||
downloadProgress,
|
||||
lastCheckedAt,
|
||||
formatVersion,
|
||||
formatLastCheckedAt,
|
||||
});
|
||||
if (availableUpdate?.latestVersion) {
|
||||
return i18n.t(
|
||||
lastCheckedAt != null
|
||||
? "desktop.updates.status.pendingWithVersionAndLastChecked"
|
||||
: "desktop.updates.status.pendingWithVersion",
|
||||
{
|
||||
version: formatVersion(availableUpdate.latestVersion),
|
||||
time: lastCheckedAt != null ? formatLastCheckedAt(lastCheckedAt) : undefined,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
if (lastCheckedAt != null) {
|
||||
return i18n.t("desktop.updates.status.pendingWithLastChecked", {
|
||||
time: formatLastCheckedAt(lastCheckedAt),
|
||||
});
|
||||
}
|
||||
return i18n.t("desktop.updates.status.pending");
|
||||
}
|
||||
|
||||
if (status === "available") {
|
||||
return formatAvailableStatusText({
|
||||
availableUpdate,
|
||||
lastCheckedAt,
|
||||
formatVersion,
|
||||
formatLastCheckedAt,
|
||||
});
|
||||
if (availableUpdate?.latestVersion) {
|
||||
return i18n.t(
|
||||
lastCheckedAt != null
|
||||
? "desktop.updates.status.availableWithVersionAndLastChecked"
|
||||
: "desktop.updates.status.availableWithVersion",
|
||||
{
|
||||
version: formatVersion(availableUpdate.latestVersion),
|
||||
time: lastCheckedAt != null ? formatLastCheckedAt(lastCheckedAt) : undefined,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
if (lastCheckedAt != null) {
|
||||
return i18n.t("desktop.updates.status.availableWithLastChecked", {
|
||||
time: formatLastCheckedAt(lastCheckedAt),
|
||||
});
|
||||
}
|
||||
return i18n.t("desktop.updates.status.available");
|
||||
}
|
||||
|
||||
if (status === "installed") {
|
||||
return installMessage ?? i18n.t("desktop.updates.status.installed");
|
||||
}
|
||||
if (status === "error") return i18n.t("desktop.updates.status.failed");
|
||||
|
||||
if (status === "error") {
|
||||
return i18n.t("desktop.updates.status.failed");
|
||||
}
|
||||
|
||||
return i18n.t("desktop.updates.status.idle");
|
||||
}
|
||||
|
||||
@@ -278,16 +202,6 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
|
||||
}
|
||||
}
|
||||
|
||||
function setDownloadProgress(progress: DesktopAppUpdateDownloadProgress | null): void {
|
||||
if (progress === null && state.downloadProgress === null) {
|
||||
return;
|
||||
}
|
||||
commit({
|
||||
...state,
|
||||
downloadProgress: progress,
|
||||
});
|
||||
}
|
||||
|
||||
async function checkForUpdates(options?: {
|
||||
releaseChannel: DesktopReleaseChannel;
|
||||
intent?: DesktopAppUpdateCheckIntent;
|
||||
@@ -327,7 +241,6 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
|
||||
...state,
|
||||
status: "error",
|
||||
availableUpdate: null,
|
||||
downloadProgress: null,
|
||||
errorMessage: result.errorMessage,
|
||||
installMessage: null,
|
||||
lastCheckedAt: nextLastCheckedAt,
|
||||
@@ -335,13 +248,24 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
|
||||
return result;
|
||||
}
|
||||
|
||||
const outcome = resolveCheckOutcome(result);
|
||||
let nextStatus: DesktopAppUpdateStatus;
|
||||
let nextAvailable: DesktopAppUpdateCheckResult | null;
|
||||
|
||||
if (result.readyToInstall) {
|
||||
nextStatus = "available";
|
||||
nextAvailable = result;
|
||||
} else if (result.hasUpdate) {
|
||||
nextStatus = "pending";
|
||||
nextAvailable = result;
|
||||
} else {
|
||||
nextStatus = "up-to-date";
|
||||
nextAvailable = null;
|
||||
}
|
||||
|
||||
commit({
|
||||
...state,
|
||||
status: outcome.status,
|
||||
availableUpdate: outcome.availableUpdate,
|
||||
downloadProgress: outcome.status === "pending" ? state.downloadProgress : null,
|
||||
status: nextStatus,
|
||||
availableUpdate: nextAvailable,
|
||||
errorMessage: null,
|
||||
installMessage: null,
|
||||
lastCheckedAt: nextLastCheckedAt,
|
||||
@@ -360,7 +284,6 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
|
||||
commit({
|
||||
...state,
|
||||
status: "error",
|
||||
downloadProgress: null,
|
||||
errorMessage: message,
|
||||
lastCheckedAt: intent === "manual" ? deps.now() : state.lastCheckedAt,
|
||||
});
|
||||
@@ -384,23 +307,10 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
|
||||
releaseChannel: options.releaseChannel,
|
||||
});
|
||||
const nextLastCheckedAt = deps.now();
|
||||
if (!result.installed && result.errorMessage) {
|
||||
commit({
|
||||
...state,
|
||||
status: "error",
|
||||
downloadProgress: null,
|
||||
errorMessage: result.errorMessage,
|
||||
installMessage: null,
|
||||
lastCheckedAt: nextLastCheckedAt,
|
||||
isInstalling: false,
|
||||
});
|
||||
return result;
|
||||
}
|
||||
commit({
|
||||
...state,
|
||||
status: result.installed ? "installed" : "up-to-date",
|
||||
availableUpdate: null,
|
||||
downloadProgress: null,
|
||||
installMessage: result.message,
|
||||
lastCheckedAt: nextLastCheckedAt,
|
||||
isInstalling: false,
|
||||
@@ -416,7 +326,6 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
|
||||
commit({
|
||||
...state,
|
||||
status: "error",
|
||||
downloadProgress: null,
|
||||
errorMessage: message,
|
||||
isInstalling: false,
|
||||
});
|
||||
@@ -432,7 +341,6 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
|
||||
listeners.delete(listener);
|
||||
};
|
||||
},
|
||||
setDownloadProgress,
|
||||
checkForUpdates,
|
||||
installUpdate,
|
||||
};
|
||||
|
||||
@@ -1,21 +1,11 @@
|
||||
import { isElectronRuntime } from "@/desktop/host";
|
||||
import { listenToDesktopEvent, type DesktopEventUnlisten } from "@/desktop/electron/events";
|
||||
import { invokeDesktopCommand } from "@/desktop/electron/invoke";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
|
||||
export interface DesktopAppUpdateDownloadProgress {
|
||||
version: string | null;
|
||||
percent: number;
|
||||
transferred: number;
|
||||
total: number;
|
||||
bytesPerSecond: number;
|
||||
}
|
||||
|
||||
export interface DesktopAppUpdateCheckResult {
|
||||
hasUpdate: boolean;
|
||||
readyToInstall: boolean;
|
||||
downloading: boolean;
|
||||
currentVersion: string | null;
|
||||
latestVersion: string | null;
|
||||
body: string | null;
|
||||
@@ -27,7 +17,6 @@ export interface DesktopAppUpdateInstallResult {
|
||||
installed: boolean;
|
||||
version: string | null;
|
||||
message: string;
|
||||
errorMessage?: string | null;
|
||||
}
|
||||
|
||||
export interface DesktopRuntimeInfo {
|
||||
@@ -126,13 +115,9 @@ export async function checkDesktopAppUpdate({
|
||||
throw new Error("Unexpected response while checking desktop updates.");
|
||||
}
|
||||
|
||||
const hasUpdate = result.hasUpdate === true;
|
||||
const readyToInstall = result.readyToInstall === true;
|
||||
return {
|
||||
hasUpdate,
|
||||
readyToInstall,
|
||||
downloading:
|
||||
typeof result.downloading === "boolean" ? result.downloading : hasUpdate && !readyToInstall,
|
||||
hasUpdate: result.hasUpdate === true,
|
||||
readyToInstall: result.readyToInstall === true,
|
||||
currentVersion: toStringOrNull(result.currentVersion),
|
||||
latestVersion: toStringOrNull(result.latestVersion),
|
||||
body: toStringOrNull(result.body),
|
||||
@@ -141,36 +126,6 @@ export async function checkDesktopAppUpdate({
|
||||
};
|
||||
}
|
||||
|
||||
export function parseDesktopAppUpdateDownloadProgress(
|
||||
raw: unknown,
|
||||
): DesktopAppUpdateDownloadProgress | null {
|
||||
if (!isRecord(raw)) {
|
||||
return null;
|
||||
}
|
||||
const percent = toNumberOr(Number.NaN, raw.percent);
|
||||
if (!Number.isFinite(percent)) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
version: toStringOrNull(raw.version),
|
||||
percent: Math.max(0, Math.min(100, percent)),
|
||||
transferred: toNumberOr(0, raw.transferred),
|
||||
total: toNumberOr(0, raw.total),
|
||||
bytesPerSecond: toNumberOr(0, raw.bytesPerSecond),
|
||||
};
|
||||
}
|
||||
|
||||
export async function subscribeDesktopAppUpdateDownloadProgress(
|
||||
handler: (progress: DesktopAppUpdateDownloadProgress | null) => void,
|
||||
): Promise<DesktopEventUnlisten> {
|
||||
if (!shouldShowDesktopUpdateSection()) {
|
||||
return () => {};
|
||||
}
|
||||
return listenToDesktopEvent<unknown>("app-update-download-progress", (payload) => {
|
||||
handler(payload === null ? null : parseDesktopAppUpdateDownloadProgress(payload));
|
||||
});
|
||||
}
|
||||
|
||||
export async function installDesktopAppUpdate({
|
||||
releaseChannel,
|
||||
}: {
|
||||
@@ -181,12 +136,10 @@ export async function installDesktopAppUpdate({
|
||||
throw new Error("Unexpected response while installing desktop update.");
|
||||
}
|
||||
|
||||
const errorMessage = toStringOrNull(result.errorMessage);
|
||||
return {
|
||||
installed: result.installed === true,
|
||||
version: toStringOrNull(result.version),
|
||||
message: toStringOrNull(result.message) ?? i18n.t("desktop.updates.status.installed"),
|
||||
...(errorMessage ? { errorMessage } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -76,50 +76,6 @@ describe("resolveUpdateCalloutDescriptor", () => {
|
||||
expect(descriptor?.dismissalKey).toBe("desktop-update:installing:1.2.3");
|
||||
});
|
||||
|
||||
it("labels the callout as Download when the update has not been downloaded yet", () => {
|
||||
const descriptor = resolveUpdateCalloutDescriptor(
|
||||
input({ availableUpdate: { latestVersion: "1.2.3", readyToInstall: false } }),
|
||||
);
|
||||
|
||||
expect(descriptor?.title).toBe("Update available");
|
||||
expect(descriptor?.body).toEqual({
|
||||
kind: "available",
|
||||
versionLabel: "v1.2.3",
|
||||
readyToInstall: false,
|
||||
});
|
||||
expect(descriptor?.actions).toEqual([
|
||||
{ role: "changelog", label: "What's new" },
|
||||
{ role: "install", label: "Download", variant: "primary", disabled: false },
|
||||
]);
|
||||
});
|
||||
|
||||
it("shows download progress while downloading an update", () => {
|
||||
const descriptor = resolveUpdateCalloutDescriptor(
|
||||
input({
|
||||
status: "installing",
|
||||
isInstalling: true,
|
||||
downloadProgress: {
|
||||
version: "1.2.3",
|
||||
percent: 42.2,
|
||||
transferred: 42,
|
||||
total: 100,
|
||||
bytesPerSecond: 10,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
expect(descriptor?.title).toBe("Downloading update");
|
||||
expect(descriptor?.body).toEqual({
|
||||
kind: "downloading",
|
||||
versionLabel: "v1.2.3",
|
||||
percent: 42,
|
||||
});
|
||||
expect(descriptor?.actions).toEqual([
|
||||
{ role: "changelog", label: "What's new" },
|
||||
{ role: "install", label: "Downloading...", variant: "primary", disabled: true },
|
||||
]);
|
||||
});
|
||||
|
||||
it("shows a retry action and surfaces the error message on error", () => {
|
||||
const descriptor = resolveUpdateCalloutDescriptor(
|
||||
input({ status: "error", errorMessage: "Download failed", availableUpdate: null }),
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
import type { DesktopAppUpdateStatus } from "@/desktop/updates/use-desktop-app-updater";
|
||||
import type { DesktopAppUpdateDownloadProgress } from "@/desktop/updates/desktop-updates";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
|
||||
export type UpdateCalloutBody =
|
||||
| { kind: "available"; versionLabel: string | null; readyToInstall?: boolean }
|
||||
| { kind: "downloading"; versionLabel: string | null; percent: number }
|
||||
| { kind: "available"; versionLabel: string | null }
|
||||
| { kind: "installing" }
|
||||
| { kind: "error"; message: string };
|
||||
|
||||
@@ -33,8 +31,7 @@ export interface ResolveUpdateCalloutInput {
|
||||
isDesktopApp: boolean;
|
||||
status: DesktopAppUpdateStatus;
|
||||
isInstalling: boolean;
|
||||
availableUpdate: { latestVersion?: string | null; readyToInstall?: boolean } | null;
|
||||
downloadProgress?: DesktopAppUpdateDownloadProgress | null;
|
||||
availableUpdate: { latestVersion?: string | null } | null;
|
||||
errorMessage: string | null;
|
||||
}
|
||||
|
||||
@@ -43,59 +40,6 @@ function formatVersionLabel(latestVersion: string | null | undefined): string |
|
||||
return `v${latestVersion.replace(/^v/i, "")}`;
|
||||
}
|
||||
|
||||
function resolveCalloutPresentation(input: {
|
||||
isError: boolean;
|
||||
isInstalling: boolean;
|
||||
readyToInstall: boolean;
|
||||
latestVersion: string | null;
|
||||
downloadProgress: DesktopAppUpdateDownloadProgress | null | undefined;
|
||||
errorMessage: string | null;
|
||||
}): { title: string; body: UpdateCalloutBody } {
|
||||
if (input.isInstalling && input.downloadProgress != null) {
|
||||
return {
|
||||
title: i18n.t("desktop.updates.callout.downloadingTitle"),
|
||||
body: {
|
||||
kind: "downloading",
|
||||
versionLabel: formatVersionLabel(input.latestVersion),
|
||||
percent: Math.round(input.downloadProgress.percent),
|
||||
},
|
||||
};
|
||||
}
|
||||
if (input.isInstalling) {
|
||||
return {
|
||||
title: i18n.t("desktop.updates.callout.installingTitle"),
|
||||
body: { kind: "installing" },
|
||||
};
|
||||
}
|
||||
if (input.isError) {
|
||||
return {
|
||||
title: i18n.t("desktop.updates.callout.failedTitle"),
|
||||
body: {
|
||||
kind: "error",
|
||||
message: input.errorMessage ?? i18n.t("desktop.updates.callout.genericError"),
|
||||
},
|
||||
};
|
||||
}
|
||||
const versionLabel = formatVersionLabel(input.latestVersion);
|
||||
return {
|
||||
title: i18n.t("desktop.updates.callout.availableTitle"),
|
||||
body: input.readyToInstall
|
||||
? { kind: "available", versionLabel }
|
||||
: { kind: "available", versionLabel, readyToInstall: false },
|
||||
};
|
||||
}
|
||||
|
||||
function resolveInstallActionLabel(input: {
|
||||
isDownloading: boolean;
|
||||
isInstalling: boolean;
|
||||
readyToInstall: boolean;
|
||||
}): string {
|
||||
if (input.isDownloading) return i18n.t("desktop.updates.callout.downloadingAction");
|
||||
if (input.isInstalling) return i18n.t("desktop.updates.callout.installingAction");
|
||||
if (input.readyToInstall) return i18n.t("desktop.updates.callout.installAndRestart");
|
||||
return i18n.t("desktop.updates.callout.downloadAndRestart");
|
||||
}
|
||||
|
||||
export function resolveUpdateCalloutDescriptor(
|
||||
input: ResolveUpdateCalloutInput,
|
||||
): UpdateCalloutDescriptor | null {
|
||||
@@ -106,22 +50,26 @@ export function resolveUpdateCalloutDescriptor(
|
||||
|
||||
const isError = input.status === "error";
|
||||
const isInstalling = input.isInstalling;
|
||||
const isDownloading = isInstalling && input.downloadProgress != null;
|
||||
const isAvailable = !isInstalling && !isError;
|
||||
const readyToInstall = input.availableUpdate?.readyToInstall !== false;
|
||||
|
||||
const latestVersion =
|
||||
input.availableUpdate?.latestVersion ?? input.downloadProgress?.version ?? null;
|
||||
const latestVersion = input.availableUpdate?.latestVersion ?? null;
|
||||
const dismissalKey = `desktop-update:${input.status}:${latestVersion ?? "unknown"}`;
|
||||
|
||||
const { title, body } = resolveCalloutPresentation({
|
||||
isError,
|
||||
isInstalling,
|
||||
readyToInstall,
|
||||
latestVersion,
|
||||
downloadProgress: input.downloadProgress,
|
||||
errorMessage: input.errorMessage,
|
||||
});
|
||||
let title: string;
|
||||
let body: UpdateCalloutBody;
|
||||
if (isInstalling) {
|
||||
title = i18n.t("desktop.updates.callout.installingTitle");
|
||||
body = { kind: "installing" };
|
||||
} else if (isError) {
|
||||
title = i18n.t("desktop.updates.callout.failedTitle");
|
||||
body = {
|
||||
kind: "error",
|
||||
message: input.errorMessage ?? i18n.t("desktop.updates.callout.genericError"),
|
||||
};
|
||||
} else {
|
||||
title = i18n.t("desktop.updates.callout.availableTitle");
|
||||
body = { kind: "available", versionLabel: formatVersionLabel(latestVersion) };
|
||||
}
|
||||
|
||||
const actions: UpdateCalloutActionDescriptor[] = [
|
||||
{ role: "changelog", label: i18n.t("desktop.updates.callout.whatsNew") },
|
||||
@@ -131,7 +79,9 @@ export function resolveUpdateCalloutDescriptor(
|
||||
} else {
|
||||
actions.push({
|
||||
role: "install",
|
||||
label: resolveInstallActionLabel({ isDownloading, isInstalling, readyToInstall }),
|
||||
label: isInstalling
|
||||
? i18n.t("desktop.updates.callout.installingAction")
|
||||
: i18n.t("desktop.updates.callout.installAndRestart"),
|
||||
variant: "primary",
|
||||
disabled: isInstalling,
|
||||
});
|
||||
|
||||
@@ -34,12 +34,9 @@ type InstallOutcome =
|
||||
function buildCheckResult(
|
||||
overrides: Partial<DesktopAppUpdateCheckResult> = {},
|
||||
): DesktopAppUpdateCheckResult {
|
||||
const hasUpdate = overrides.hasUpdate ?? false;
|
||||
const readyToInstall = overrides.readyToInstall ?? false;
|
||||
return {
|
||||
hasUpdate,
|
||||
readyToInstall,
|
||||
downloading: overrides.downloading ?? (hasUpdate && !readyToInstall),
|
||||
hasUpdate: false,
|
||||
readyToInstall: false,
|
||||
currentVersion: null,
|
||||
latestVersion: null,
|
||||
body: null,
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { Gift } from "lucide-react-native";
|
||||
import { type ReactNode, useEffect, useMemo, useRef } from "react";
|
||||
import { View } from "react-native";
|
||||
import { type ReactNode, useEffect, useRef } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { StyleSheet, useUnistyles } from "react-native-unistyles";
|
||||
import { useUnistyles } from "react-native-unistyles";
|
||||
import {
|
||||
type SidebarCalloutAction,
|
||||
SidebarCalloutDescriptionText,
|
||||
@@ -20,24 +19,9 @@ import { openChangelog } from "@/changelog";
|
||||
const CHECK_INTERVAL_MS = 30 * 60 * 1000;
|
||||
|
||||
function renderBody(body: UpdateCalloutBody, t: ReturnType<typeof useTranslation>["t"]): ReactNode {
|
||||
if (body.kind === "downloading") {
|
||||
return (
|
||||
<UpdateDownloadingDescription
|
||||
versionLabel={body.versionLabel ?? undefined}
|
||||
percent={body.percent}
|
||||
t={t}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (body.kind === "installing") return t("desktop.updates.callout.installingDescription");
|
||||
if (body.kind === "error") return body.message;
|
||||
return (
|
||||
<UpdateAvailableDescription
|
||||
versionLabel={body.versionLabel ?? undefined}
|
||||
readyToInstall={body.readyToInstall !== false}
|
||||
t={t}
|
||||
/>
|
||||
);
|
||||
return <UpdateAvailableDescription versionLabel={body.versionLabel ?? undefined} t={t} />;
|
||||
}
|
||||
|
||||
function materializeActions(
|
||||
@@ -58,11 +42,8 @@ export function UpdateCalloutSource() {
|
||||
const { theme } = useUnistyles();
|
||||
const {
|
||||
isDesktopApp,
|
||||
updateMode,
|
||||
isLoadingSettings,
|
||||
status,
|
||||
availableUpdate,
|
||||
downloadProgress,
|
||||
errorMessage,
|
||||
checkForUpdates,
|
||||
installUpdate,
|
||||
@@ -77,7 +58,7 @@ export function UpdateCalloutSource() {
|
||||
void checkForUpdates();
|
||||
});
|
||||
useEffect(() => {
|
||||
if (!isDesktopApp || isLoadingSettings || updateMode === "off") return;
|
||||
if (!isDesktopApp) return;
|
||||
|
||||
void checkForUpdates({ intent: "automatic", silent: true });
|
||||
|
||||
@@ -90,7 +71,7 @@ export function UpdateCalloutSource() {
|
||||
clearInterval(intervalRef.current);
|
||||
}
|
||||
};
|
||||
}, [isDesktopApp, isLoadingSettings, updateMode, checkForUpdates]);
|
||||
}, [isDesktopApp, checkForUpdates]);
|
||||
|
||||
useEffect(() => {
|
||||
const descriptor = resolveUpdateCalloutDescriptor({
|
||||
@@ -98,7 +79,6 @@ export function UpdateCalloutSource() {
|
||||
status,
|
||||
isInstalling,
|
||||
availableUpdate,
|
||||
downloadProgress,
|
||||
errorMessage,
|
||||
});
|
||||
if (!descriptor) return;
|
||||
@@ -123,7 +103,6 @@ export function UpdateCalloutSource() {
|
||||
}, [
|
||||
availableUpdate,
|
||||
callouts,
|
||||
downloadProgress,
|
||||
errorMessage,
|
||||
install,
|
||||
isDesktopApp,
|
||||
@@ -138,94 +117,23 @@ export function UpdateCalloutSource() {
|
||||
return null;
|
||||
}
|
||||
|
||||
function formatAvailableSummary(
|
||||
t: ReturnType<typeof useTranslation>["t"],
|
||||
versionLabel: string | undefined,
|
||||
readyToInstall: boolean,
|
||||
): string {
|
||||
if (readyToInstall) {
|
||||
return versionLabel
|
||||
? t("desktop.updates.callout.versionReady", { version: versionLabel })
|
||||
: t("desktop.updates.callout.newVersionReady");
|
||||
}
|
||||
return versionLabel
|
||||
? t("desktop.updates.callout.versionAvailable", { version: versionLabel })
|
||||
: t("desktop.updates.callout.newVersionAvailable");
|
||||
}
|
||||
|
||||
function UpdateAvailableDescription({
|
||||
versionLabel,
|
||||
readyToInstall,
|
||||
t,
|
||||
}: {
|
||||
versionLabel?: string;
|
||||
readyToInstall: boolean;
|
||||
t: ReturnType<typeof useTranslation>["t"];
|
||||
}) {
|
||||
const summary = formatAvailableSummary(t, versionLabel, readyToInstall);
|
||||
|
||||
return (
|
||||
<>
|
||||
<SidebarCalloutDescriptionText>{summary}</SidebarCalloutDescriptionText>
|
||||
<SidebarCalloutDescriptionText>
|
||||
{versionLabel
|
||||
? t("desktop.updates.callout.versionReady", { version: versionLabel })
|
||||
: t("desktop.updates.callout.newVersionReady")}
|
||||
</SidebarCalloutDescriptionText>
|
||||
<SidebarCalloutDescriptionText>
|
||||
{t("desktop.updates.callout.restartWarning")}
|
||||
</SidebarCalloutDescriptionText>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function UpdateDownloadingDescription({
|
||||
versionLabel,
|
||||
percent,
|
||||
t,
|
||||
}: {
|
||||
versionLabel?: string;
|
||||
percent: number;
|
||||
t: ReturnType<typeof useTranslation>["t"];
|
||||
}) {
|
||||
const clampedPercent = Math.max(0, Math.min(100, percent));
|
||||
const accessibilityValue = useMemo(
|
||||
() => ({ min: 0, max: 100, now: clampedPercent }),
|
||||
[clampedPercent],
|
||||
);
|
||||
const progressFillStyle = useMemo(
|
||||
() => [styles.progressFill, { width: `${clampedPercent}%` as const }],
|
||||
[clampedPercent],
|
||||
);
|
||||
return (
|
||||
<View style={styles.progressContainer}>
|
||||
<SidebarCalloutDescriptionText>
|
||||
{versionLabel
|
||||
? t("desktop.updates.callout.downloadingVersionDescription", {
|
||||
version: versionLabel,
|
||||
percent: clampedPercent,
|
||||
})
|
||||
: t("desktop.updates.callout.downloadingDescription", { percent: clampedPercent })}
|
||||
</SidebarCalloutDescriptionText>
|
||||
<View
|
||||
style={styles.progressTrack}
|
||||
accessibilityRole="progressbar"
|
||||
accessibilityValue={accessibilityValue}
|
||||
>
|
||||
<View style={progressFillStyle} />
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
progressContainer: {
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
progressTrack: {
|
||||
height: 4,
|
||||
borderRadius: theme.borderRadius.full,
|
||||
backgroundColor: theme.colors.surface3,
|
||||
overflow: "hidden",
|
||||
},
|
||||
progressFill: {
|
||||
height: "100%",
|
||||
borderRadius: theme.borderRadius.full,
|
||||
backgroundColor: theme.colors.accent,
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -4,13 +4,11 @@ import {
|
||||
formatVersionWithPrefix,
|
||||
installDesktopAppUpdate,
|
||||
shouldShowDesktopUpdateSection,
|
||||
subscribeDesktopAppUpdateDownloadProgress,
|
||||
type DesktopAppUpdateCheckResult,
|
||||
type DesktopAppUpdateCheckIntent,
|
||||
type DesktopAppUpdateDownloadProgress,
|
||||
type DesktopAppUpdateInstallResult,
|
||||
} from "@/desktop/updates/desktop-updates";
|
||||
import { useDesktopSettings, type DesktopUpdateMode } from "@/desktop/settings/desktop-settings";
|
||||
import { useDesktopSettings } from "@/desktop/settings/desktop-settings";
|
||||
import { useDesktopIpcErrorReporter } from "@/desktop/hooks/desktop-ipc-error";
|
||||
import {
|
||||
PENDING_RECHECK_MS,
|
||||
@@ -24,12 +22,9 @@ export type { DesktopAppUpdateStatus };
|
||||
|
||||
export interface UseDesktopAppUpdaterReturn {
|
||||
isDesktopApp: boolean;
|
||||
updateMode: DesktopUpdateMode;
|
||||
isLoadingSettings: boolean;
|
||||
status: DesktopAppUpdateStatus;
|
||||
statusText: string;
|
||||
availableUpdate: DesktopAppUpdateCheckResult | null;
|
||||
downloadProgress: DesktopAppUpdateDownloadProgress | null;
|
||||
errorMessage: string | null;
|
||||
lastCheckedAt: number | null;
|
||||
isChecking: boolean;
|
||||
@@ -43,9 +38,8 @@ export interface UseDesktopAppUpdaterReturn {
|
||||
|
||||
export function useDesktopAppUpdater(): UseDesktopAppUpdaterReturn {
|
||||
const isDesktopApp = shouldShowDesktopUpdateSection();
|
||||
const { settings: desktopSettings, isLoading: isLoadingSettings } = useDesktopSettings();
|
||||
const { settings: desktopSettings } = useDesktopSettings();
|
||||
const releaseChannel = desktopSettings.releaseChannel;
|
||||
const updateMode = desktopSettings.updates.mode;
|
||||
const reportError = useDesktopIpcErrorReporter();
|
||||
|
||||
const updater = useMemo(
|
||||
@@ -90,40 +84,13 @@ export function useDesktopAppUpdater(): UseDesktopAppUpdaterReturn {
|
||||
|
||||
useEffect(() => {
|
||||
if (!isDesktopApp) {
|
||||
return undefined;
|
||||
}
|
||||
let active = true;
|
||||
let unlisten: (() => void) | null = null;
|
||||
void subscribeDesktopAppUpdateDownloadProgress((progress) => {
|
||||
if (active) {
|
||||
updater.setDownloadProgress(progress);
|
||||
}
|
||||
})
|
||||
.then((cleanup) => {
|
||||
if (active) {
|
||||
unlisten = cleanup;
|
||||
} else {
|
||||
cleanup();
|
||||
}
|
||||
return undefined;
|
||||
})
|
||||
.catch(() => undefined);
|
||||
|
||||
return () => {
|
||||
active = false;
|
||||
unlisten?.();
|
||||
};
|
||||
}, [isDesktopApp, updater]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isDesktopApp || isLoadingSettings || updateMode === "off") {
|
||||
return;
|
||||
}
|
||||
void checkForUpdates({ intent: "automatic", silent: true });
|
||||
}, [checkForUpdates, isDesktopApp, isLoadingSettings, updateMode]);
|
||||
}, [checkForUpdates, isDesktopApp]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isDesktopApp || snapshot.status !== "pending" || updateMode === "off") {
|
||||
if (!isDesktopApp || snapshot.status !== "pending") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@@ -134,24 +101,20 @@ export function useDesktopAppUpdater(): UseDesktopAppUpdaterReturn {
|
||||
return () => {
|
||||
clearInterval(intervalId);
|
||||
};
|
||||
}, [checkForUpdates, isDesktopApp, snapshot.status, updateMode]);
|
||||
}, [checkForUpdates, isDesktopApp, snapshot.status]);
|
||||
|
||||
return {
|
||||
isDesktopApp,
|
||||
updateMode,
|
||||
isLoadingSettings,
|
||||
status: snapshot.status,
|
||||
statusText: formatStatusText({
|
||||
status: snapshot.status,
|
||||
availableUpdate: snapshot.availableUpdate,
|
||||
downloadProgress: snapshot.downloadProgress,
|
||||
installMessage: snapshot.installMessage,
|
||||
lastCheckedAt: snapshot.lastCheckedAt,
|
||||
formatVersion: formatVersionWithPrefix,
|
||||
formatLastCheckedAt: (timestamp) => formatMessageTimestamp(new Date(timestamp)),
|
||||
}),
|
||||
availableUpdate: snapshot.availableUpdate,
|
||||
downloadProgress: snapshot.downloadProgress,
|
||||
errorMessage: snapshot.errorMessage,
|
||||
lastCheckedAt: snapshot.lastCheckedAt,
|
||||
isChecking: snapshot.isChecking,
|
||||
|
||||
@@ -166,7 +166,7 @@ describe("ensureAgentIsInitialized", () => {
|
||||
kind: "assistant_message",
|
||||
id: "canonical-item",
|
||||
text: "Canonical before restart",
|
||||
timelineCursor: { epoch: "epoch-1", seq: 12 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 12, anchorSeq: 12 },
|
||||
timestamp: new Date("2026-07-27T10:00:00.000Z"),
|
||||
},
|
||||
],
|
||||
|
||||
@@ -32,9 +32,6 @@ export interface FakeDesktopBridge extends DesktopSettingsBridge {
|
||||
|
||||
const DEFAULT_DESKTOP: DesktopSettings = {
|
||||
releaseChannel: "stable",
|
||||
updates: {
|
||||
mode: "automatic",
|
||||
},
|
||||
notifications: {
|
||||
playSound: true,
|
||||
},
|
||||
|
||||
@@ -656,7 +656,6 @@ describe("loadSettingsFromStorage", () => {
|
||||
isElectron: true,
|
||||
settings: {
|
||||
releaseChannel: "beta",
|
||||
updates: { mode: "automatic" },
|
||||
notifications: { playSound: true },
|
||||
daemon: { manageBuiltInDaemon: false, keepRunningAfterQuit: true },
|
||||
},
|
||||
|
||||
@@ -4,7 +4,6 @@ import {
|
||||
defaultHostAppearance,
|
||||
normalizeStoredHostAppearance,
|
||||
resolveHostBadgeDisplay,
|
||||
resolveHostIcon,
|
||||
selectHostBadges,
|
||||
} from "@/hosts/appearance";
|
||||
|
||||
@@ -17,7 +16,7 @@ function host(
|
||||
}
|
||||
|
||||
describe("normalizeStoredHostAppearance", () => {
|
||||
it("defaults without writing an icon field so untouched records stay downgrade-safe", () => {
|
||||
it("defaults when the stored registry predates the field or holds junk", () => {
|
||||
const expected = { color: "none", badgeDisplay: null };
|
||||
expect(normalizeStoredHostAppearance(undefined)).toEqual(expected);
|
||||
expect(normalizeStoredHostAppearance(null)).toEqual(expected);
|
||||
@@ -25,82 +24,16 @@ describe("normalizeStoredHostAppearance", () => {
|
||||
expect(normalizeStoredHostAppearance({})).toEqual(expected);
|
||||
expect(normalizeStoredHostAppearance({ color: "chartreuse" })).toEqual(expected);
|
||||
expect(normalizeStoredHostAppearance({ badgeDisplay: "loud" })).toEqual(expected);
|
||||
expect("icon" in defaultHostAppearance()).toBe(false);
|
||||
});
|
||||
|
||||
it("preserves an unknown stored icon on disk while falling back at render time", () => {
|
||||
const normalized = normalizeStoredHostAppearance({
|
||||
color: "teal",
|
||||
icon: "spaceship",
|
||||
badgeDisplay: "icon",
|
||||
});
|
||||
expect(normalized).toEqual({
|
||||
color: "teal",
|
||||
icon: "spaceship",
|
||||
badgeDisplay: "icon",
|
||||
});
|
||||
expect(resolveHostIcon({ appearance: normalized })).toBe("server");
|
||||
expect(resolveHostIcon({ appearance: normalized, detectedMachineKind: "laptop" })).toBe(
|
||||
"laptop",
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps icon absent on stored entries that predate host icons", () => {
|
||||
const normalized = normalizeStoredHostAppearance({ color: "teal", badgeDisplay: "icon" });
|
||||
expect(normalized).toEqual({
|
||||
color: "teal",
|
||||
badgeDisplay: "icon",
|
||||
});
|
||||
expect("icon" in normalized).toBe(false);
|
||||
});
|
||||
|
||||
it("round-trips a value the user actually chose", () => {
|
||||
expect(
|
||||
normalizeStoredHostAppearance({ color: "teal", icon: "laptop", badgeDisplay: "icon" }),
|
||||
).toEqual({
|
||||
expect(normalizeStoredHostAppearance({ color: "teal", badgeDisplay: "icon" })).toEqual({
|
||||
color: "teal",
|
||||
icon: "laptop",
|
||||
badgeDisplay: "icon",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveHostIcon", () => {
|
||||
it("prefers an explicit user icon over daemon auto-detection", () => {
|
||||
expect(
|
||||
resolveHostIcon({
|
||||
appearance: { color: "none", icon: "workstation", badgeDisplay: null },
|
||||
detectedMachineKind: "laptop",
|
||||
}),
|
||||
).toBe("workstation");
|
||||
});
|
||||
|
||||
it("uses the daemon-detected machine kind while the user icon is auto (null)", () => {
|
||||
expect(
|
||||
resolveHostIcon({
|
||||
appearance: defaultHostAppearance(),
|
||||
detectedMachineKind: "laptop",
|
||||
}),
|
||||
).toBe("laptop");
|
||||
expect(
|
||||
resolveHostIcon({
|
||||
appearance: defaultHostAppearance(),
|
||||
detectedMachineKind: "container",
|
||||
}),
|
||||
).toBe("container");
|
||||
});
|
||||
|
||||
it("falls back to server when the detected machine kind is absent or unknown", () => {
|
||||
expect(resolveHostIcon({ appearance: defaultHostAppearance() })).toBe("server");
|
||||
expect(
|
||||
resolveHostIcon({ appearance: defaultHostAppearance(), detectedMachineKind: null }),
|
||||
).toBe("server");
|
||||
expect(
|
||||
resolveHostIcon({ appearance: defaultHostAppearance(), detectedMachineKind: "future-kind" }),
|
||||
).toBe("server");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveHostBadgeDisplay", () => {
|
||||
it("hides the badge for the local host until the user chooses", () => {
|
||||
expect(
|
||||
@@ -117,13 +50,13 @@ describe("resolveHostBadgeDisplay", () => {
|
||||
it("prefers an explicit choice over either default", () => {
|
||||
expect(
|
||||
resolveHostBadgeDisplay({
|
||||
appearance: { color: "none", icon: "server", badgeDisplay: "icon" },
|
||||
appearance: { color: "none", badgeDisplay: "icon" },
|
||||
isLocalHost: true,
|
||||
}),
|
||||
).toBe("icon");
|
||||
expect(
|
||||
resolveHostBadgeDisplay({
|
||||
appearance: { color: "none", icon: "server", badgeDisplay: "hidden" },
|
||||
appearance: { color: "none", badgeDisplay: "hidden" },
|
||||
isLocalHost: false,
|
||||
}),
|
||||
).toBe("hidden");
|
||||
@@ -139,7 +72,7 @@ describe("resolveHostBadgeDisplay", () => {
|
||||
).toBeNull();
|
||||
expect(
|
||||
resolveHostBadgeDisplay({
|
||||
appearance: { color: "none", icon: "server", badgeDisplay: "icon" },
|
||||
appearance: { color: "none", badgeDisplay: "icon" },
|
||||
isLocalHost: false,
|
||||
localHostResolutionPending: true,
|
||||
}),
|
||||
@@ -160,7 +93,7 @@ describe("selectHostBadges", () => {
|
||||
it("omits a host the user hid and keeps its sibling", () => {
|
||||
const badges = selectHostBadges({
|
||||
hosts: [
|
||||
host("alpha", "Alpha", { color: "none", icon: "server", badgeDisplay: "hidden" }),
|
||||
host("alpha", "Alpha", { color: "none", badgeDisplay: "hidden" }),
|
||||
host("beta", "Beta"),
|
||||
],
|
||||
localServerId: null,
|
||||
@@ -171,14 +104,13 @@ describe("selectHostBadges", () => {
|
||||
serverId: "beta",
|
||||
label: "Beta",
|
||||
color: "none",
|
||||
icon: "server",
|
||||
showLabel: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps an icon-only host in the map without its label", () => {
|
||||
const badges = selectHostBadges({
|
||||
hosts: [host("alpha", "Alpha", { color: "teal", icon: "mini", badgeDisplay: "icon" })],
|
||||
hosts: [host("alpha", "Alpha", { color: "teal", badgeDisplay: "icon" })],
|
||||
localServerId: null,
|
||||
enabled: true,
|
||||
});
|
||||
@@ -186,7 +118,6 @@ describe("selectHostBadges", () => {
|
||||
serverId: "alpha",
|
||||
label: "Alpha",
|
||||
color: "teal",
|
||||
icon: "mini",
|
||||
showLabel: false,
|
||||
});
|
||||
});
|
||||
@@ -219,21 +150,4 @@ describe("selectHostBadges", () => {
|
||||
});
|
||||
expect(badges.size).toBe(0);
|
||||
});
|
||||
|
||||
it("applies daemon-detected machine kind for auto icons while respecting explicit overrides", () => {
|
||||
const badges = selectHostBadges({
|
||||
hosts: [
|
||||
host("alpha", "Alpha"),
|
||||
host("beta", "Beta", { color: "sky", icon: "workstation", badgeDisplay: "name" }),
|
||||
],
|
||||
localServerId: null,
|
||||
detectedMachineKindByServerId: new Map([
|
||||
["alpha", "laptop"],
|
||||
["beta", "cloud"],
|
||||
]),
|
||||
enabled: true,
|
||||
});
|
||||
expect(badges.get("alpha")?.icon).toBe("laptop");
|
||||
expect(badges.get("beta")?.icon).toBe("workstation");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,69 +6,25 @@ export type HostColor = "none" | IdentityColorName;
|
||||
|
||||
export const HOST_COLORS: readonly HostColor[] = ["none", ...IDENTITY_COLOR_NAMES];
|
||||
|
||||
export const HOST_ICONS = [
|
||||
"server",
|
||||
"laptop",
|
||||
"desktop",
|
||||
"mini",
|
||||
"workstation",
|
||||
"cloud",
|
||||
"container",
|
||||
"board",
|
||||
"terminal",
|
||||
] as const;
|
||||
|
||||
export type HostIcon = (typeof HOST_ICONS)[number];
|
||||
|
||||
export const DEFAULT_HOST_ICON: HostIcon = "server";
|
||||
|
||||
const HOST_ICON_SET = new Set<string>(HOST_ICONS);
|
||||
|
||||
export function normalizeDetectedHostIcon(value: string | null | undefined): HostIcon | null {
|
||||
const trimmed = value?.trim();
|
||||
if (trimmed && HOST_ICON_SET.has(trimmed)) {
|
||||
return trimmed as HostIcon;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export type HostBadgeDisplay = "name" | "icon" | "hidden";
|
||||
|
||||
export const HOST_BADGE_DISPLAYS: readonly HostBadgeDisplay[] = ["name", "icon", "hidden"];
|
||||
|
||||
/**
|
||||
* Per-device host presentation.
|
||||
* - `icon` is omitted while untouched ("Auto") so existing records stay byte-for-byte compatible
|
||||
* with older builds whose stored appearance schema is strict. An unknown icon string written by
|
||||
* a newer build is preserved on disk and falls back at render time via `resolveHostIcon`.
|
||||
* - `badgeDisplay` is null while untouched so runtime defaults apply (hidden for local / name for
|
||||
* remote) without baking runtime facts at parse time.
|
||||
* Per-device host presentation. `badgeDisplay` is null while the user has not chosen,
|
||||
* because the default differs by host (local hides, remote shows) and local-ness is only
|
||||
* knowable from a desktop-only async query — never at parse time.
|
||||
*/
|
||||
export interface HostAppearance {
|
||||
color: HostColor;
|
||||
icon?: string;
|
||||
badgeDisplay: HostBadgeDisplay | null;
|
||||
}
|
||||
|
||||
const StoredHostAppearanceSchema = z.strictObject({
|
||||
export const HostAppearanceSchema: z.ZodType<HostAppearance> = z.strictObject({
|
||||
color: z.enum(["none", ...IDENTITY_COLOR_NAMES]),
|
||||
// Optional loose string on disk so untouched hosts stay readable after a downgrade and an icon
|
||||
// added by a newer build survives read/write instead of being dropped or overwritten.
|
||||
icon: z.string().nullable().optional(),
|
||||
badgeDisplay: z.enum(["name", "icon", "hidden"]).nullable(),
|
||||
});
|
||||
|
||||
export const HostAppearanceSchema = StoredHostAppearanceSchema.transform(
|
||||
(value): HostAppearance => {
|
||||
const icon = value.icon?.trim();
|
||||
return {
|
||||
color: value.color,
|
||||
...(icon ? { icon } : {}),
|
||||
badgeDisplay: value.badgeDisplay,
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
export function defaultHostAppearance(): HostAppearance {
|
||||
return { color: "none", badgeDisplay: null };
|
||||
}
|
||||
@@ -78,17 +34,6 @@ export function normalizeStoredHostAppearance(value: unknown): HostAppearance {
|
||||
return result.success ? result.data : defaultHostAppearance();
|
||||
}
|
||||
|
||||
export function resolveHostIcon(input: {
|
||||
appearance: HostAppearance;
|
||||
detectedMachineKind?: string | null;
|
||||
}): HostIcon {
|
||||
return (
|
||||
normalizeDetectedHostIcon(input.appearance.icon) ??
|
||||
normalizeDetectedHostIcon(input.detectedMachineKind) ??
|
||||
DEFAULT_HOST_ICON
|
||||
);
|
||||
}
|
||||
|
||||
export function resolveHostBadgeDisplay(input: {
|
||||
appearance: HostAppearance;
|
||||
isLocalHost: boolean;
|
||||
@@ -107,7 +52,6 @@ export interface HostBadgeModel {
|
||||
serverId: string;
|
||||
label: string;
|
||||
color: HostColor;
|
||||
icon: HostIcon;
|
||||
showLabel: boolean;
|
||||
}
|
||||
|
||||
@@ -122,7 +66,6 @@ export function selectHostBadges(input: {
|
||||
hosts: readonly HostAppearanceSource[];
|
||||
localServerId: string | null;
|
||||
localHostResolutionPending?: boolean;
|
||||
detectedMachineKindByServerId?: ReadonlyMap<string, string | null>;
|
||||
enabled: boolean;
|
||||
}): ReadonlyMap<string, HostBadgeModel> {
|
||||
const badges = new Map<string, HostBadgeModel>();
|
||||
@@ -142,10 +85,6 @@ export function selectHostBadges(input: {
|
||||
serverId: host.serverId,
|
||||
label: host.label.trim() || host.serverId,
|
||||
color: host.appearance.color,
|
||||
icon: resolveHostIcon({
|
||||
appearance: host.appearance,
|
||||
detectedMachineKind: input.detectedMachineKindByServerId?.get(host.serverId) ?? null,
|
||||
}),
|
||||
showLabel: display === "name",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,134 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
describeActiveConnection,
|
||||
describeHostConnection,
|
||||
formatConnectionEndpoint,
|
||||
isTailscaleEndpoint,
|
||||
} from "./connection-display";
|
||||
|
||||
describe("isTailscaleEndpoint", () => {
|
||||
it("recognizes MagicDNS .ts.net hostnames with or without ports", () => {
|
||||
expect(isTailscaleEndpoint("mac-mini.tail123.ts.net:6767")).toBe(true);
|
||||
expect(isTailscaleEndpoint("Mac-Mini.Tail123.TS.NET:443")).toBe(true);
|
||||
expect(isTailscaleEndpoint("devbox.tailnet.ts.net")).toBe(true);
|
||||
expect(isTailscaleEndpoint(".ts.net")).toBe(false);
|
||||
});
|
||||
|
||||
it("recognizes Tailscale IPv4 CGNAT (100.64.0.0/10) and IPv6 ULA addresses", () => {
|
||||
expect(isTailscaleEndpoint("100.64.0.1:6767")).toBe(true);
|
||||
expect(isTailscaleEndpoint("100.100.42.9:6767")).toBe(true);
|
||||
expect(isTailscaleEndpoint("100.127.255.254:6767")).toBe(true);
|
||||
expect(isTailscaleEndpoint("100.63.255.255:6767")).toBe(false);
|
||||
expect(isTailscaleEndpoint("100.128.0.1:6767")).toBe(false);
|
||||
expect(isTailscaleEndpoint("[fd7a:115c:a1e0::1]:6767")).toBe(true);
|
||||
});
|
||||
|
||||
it("does not misclassify LAN, localhost, or ordinary domains", () => {
|
||||
expect(isTailscaleEndpoint("localhost:6767")).toBe(false);
|
||||
expect(isTailscaleEndpoint("127.0.0.1:6767")).toBe(false);
|
||||
expect(isTailscaleEndpoint("192.168.1.25:6767")).toBe(false);
|
||||
expect(isTailscaleEndpoint("relay.paseo.sh:443")).toBe(false);
|
||||
expect(isTailscaleEndpoint("not-ts.net.example.com:6767")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("describeActiveConnection", () => {
|
||||
it("describes local socket and pipe connections without exposing paths", () => {
|
||||
expect(
|
||||
describeActiveConnection({
|
||||
type: "directSocket",
|
||||
endpoint: "/tmp/paseo.sock",
|
||||
display: "socket",
|
||||
}),
|
||||
).toEqual({ kind: "local" });
|
||||
expect(
|
||||
describeActiveConnection({
|
||||
type: "directPipe",
|
||||
endpoint: "\\\\.\\pipe\\paseo",
|
||||
display: "pipe",
|
||||
}),
|
||||
).toEqual({ kind: "local" });
|
||||
});
|
||||
|
||||
it("describes loopback TCP on the local host as local, and remote loopback as direct", () => {
|
||||
const loopback = {
|
||||
type: "directTcp",
|
||||
endpoint: "localhost:6767",
|
||||
display: "localhost:6767",
|
||||
} as const;
|
||||
expect(describeActiveConnection(loopback, { isLocalHost: true })).toEqual({ kind: "local" });
|
||||
expect(describeActiveConnection(loopback, { isLocalHost: false })).toEqual({
|
||||
kind: "direct",
|
||||
endpoint: "localhost:6767",
|
||||
});
|
||||
});
|
||||
|
||||
it("strips standard web ports on relay, tailscale, and direct connections", () => {
|
||||
expect(
|
||||
describeActiveConnection({ type: "relay", endpoint: "relay.paseo.sh:443", display: "relay" }),
|
||||
).toEqual({ kind: "relay", endpoint: "relay.paseo.sh" });
|
||||
expect(
|
||||
describeActiveConnection({
|
||||
type: "directTcp",
|
||||
endpoint: "mac-mini.tail123.ts.net:6767",
|
||||
display: "mac-mini.tail123.ts.net:6767",
|
||||
}),
|
||||
).toEqual({ kind: "tailscale", endpoint: "mac-mini.tail123.ts.net:6767" });
|
||||
expect(
|
||||
describeActiveConnection({
|
||||
type: "directTcp",
|
||||
endpoint: "devbox.example.com:443",
|
||||
display: "devbox.example.com:443",
|
||||
}),
|
||||
).toEqual({ kind: "direct", endpoint: "devbox.example.com" });
|
||||
});
|
||||
|
||||
it("preserves SSH and routed targets", () => {
|
||||
expect(
|
||||
describeActiveConnection({
|
||||
type: "remoteSsh",
|
||||
endpoint: "mo@workstation",
|
||||
display: "mo@workstation",
|
||||
}),
|
||||
).toEqual({ kind: "ssh", endpoint: "mo@workstation" });
|
||||
expect(
|
||||
describeActiveConnection({
|
||||
type: "routed",
|
||||
endpoint: "srv_origin",
|
||||
display: "via srv_origin",
|
||||
}),
|
||||
).toEqual({ kind: "routed", endpoint: "srv_origin" });
|
||||
});
|
||||
|
||||
it("strips default HTTP/HTTPS ports only", () => {
|
||||
expect(formatConnectionEndpoint("relay.paseo.sh:443")).toBe("relay.paseo.sh");
|
||||
expect(formatConnectionEndpoint("example.com:80")).toBe("example.com");
|
||||
expect(formatConnectionEndpoint("127.0.0.1:6767")).toBe("127.0.0.1:6767");
|
||||
});
|
||||
|
||||
it("describes configured host connections before an active connection is online", () => {
|
||||
expect(
|
||||
describeHostConnection({
|
||||
id: "direct:mac-mini.tail123.ts.net:6767",
|
||||
type: "directTcp",
|
||||
endpoint: "mac-mini.tail123.ts.net:6767",
|
||||
}),
|
||||
).toEqual({ kind: "tailscale", endpoint: "mac-mini.tail123.ts.net:6767" });
|
||||
expect(
|
||||
describeHostConnection({
|
||||
id: "relay:wss:relay.paseo.sh:443",
|
||||
type: "relay",
|
||||
relayEndpoint: "relay.paseo.sh:443",
|
||||
useTls: true,
|
||||
daemonPublicKeyB64: "key",
|
||||
}),
|
||||
).toEqual({ kind: "relay", endpoint: "relay.paseo.sh" });
|
||||
expect(
|
||||
describeHostConnection({
|
||||
id: "ssh:mo%40workstation::",
|
||||
type: "remoteSsh",
|
||||
host: "mo@workstation",
|
||||
}),
|
||||
).toEqual({ kind: "ssh", endpoint: "mo@workstation" });
|
||||
});
|
||||
});
|
||||
@@ -1,120 +0,0 @@
|
||||
import type { ActiveConnection } from "@/runtime/host-runtime";
|
||||
import type { HostConnection } from "@/types/host-connection";
|
||||
|
||||
export type HostConnectionKind = "local" | "relay" | "tailscale" | "ssh" | "direct" | "routed";
|
||||
|
||||
export interface HostConnectionDisplay {
|
||||
kind: HostConnectionKind;
|
||||
/** Address shown beside the connection kind. Omitted for local transports. */
|
||||
endpoint?: string;
|
||||
}
|
||||
|
||||
// Standard secure/plain web ports carry no information in the host display, so
|
||||
// "relay.paseo.sh:443" reads as "relay.paseo.sh" while "127.0.0.1:6767" is kept.
|
||||
export function formatConnectionEndpoint(endpoint: string): string {
|
||||
return endpoint.replace(/:(?:443|80)$/, "");
|
||||
}
|
||||
|
||||
function extractEndpointHost(endpoint: string): string {
|
||||
const trimmed = endpoint.trim().toLowerCase();
|
||||
if (!trimmed) return "";
|
||||
|
||||
const withoutScheme = trimmed.replace(/^[a-z][a-z0-9+.-]*:\/\//, "");
|
||||
const authority = withoutScheme.split("/")[0] ?? "";
|
||||
const hostPort = authority.includes("@")
|
||||
? authority.slice(authority.lastIndexOf("@") + 1)
|
||||
: authority;
|
||||
|
||||
if (hostPort.startsWith("[")) {
|
||||
const closeBracket = hostPort.indexOf("]");
|
||||
return closeBracket > 1 ? hostPort.slice(1, closeBracket) : hostPort;
|
||||
}
|
||||
|
||||
const firstColon = hostPort.indexOf(":");
|
||||
const lastColon = hostPort.lastIndexOf(":");
|
||||
if (firstColon !== -1 && firstColon === lastColon) {
|
||||
return hostPort.slice(0, firstColon);
|
||||
}
|
||||
return hostPort;
|
||||
}
|
||||
|
||||
function isTailscaleIpv4(host: string): boolean {
|
||||
const parts = host.split(".");
|
||||
if (parts.length !== 4) return false;
|
||||
const octets = parts.map((part) => (/^\d+$/.test(part) ? Number(part) : Number.NaN));
|
||||
if (octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {
|
||||
return false;
|
||||
}
|
||||
// Tailscale assigns addresses from the RFC 6598 CGNAT range 100.64.0.0/10.
|
||||
return octets[0] === 100 && octets[1] >= 64 && octets[1] <= 127;
|
||||
}
|
||||
|
||||
function isTailscaleIpv6(host: string): boolean {
|
||||
return host.startsWith("fd7a:115c:a1e0:");
|
||||
}
|
||||
|
||||
export function isTailscaleEndpoint(endpoint: string): boolean {
|
||||
const host = extractEndpointHost(endpoint);
|
||||
if (!host) return false;
|
||||
if (host.endsWith(".ts.net") && host.length > ".ts.net".length) {
|
||||
return true;
|
||||
}
|
||||
return isTailscaleIpv4(host) || isTailscaleIpv6(host);
|
||||
}
|
||||
|
||||
export function isLoopbackEndpoint(endpoint: string): boolean {
|
||||
const host = extractEndpointHost(endpoint);
|
||||
return host === "localhost" || host === "127.0.0.1" || host === "::1";
|
||||
}
|
||||
|
||||
export function describeActiveConnection(
|
||||
connection: ActiveConnection,
|
||||
options?: { isLocalHost?: boolean },
|
||||
): HostConnectionDisplay {
|
||||
switch (connection.type) {
|
||||
case "directSocket":
|
||||
case "directPipe":
|
||||
return { kind: "local" };
|
||||
case "relay":
|
||||
return { kind: "relay", endpoint: formatConnectionEndpoint(connection.endpoint) };
|
||||
case "remoteSsh":
|
||||
return { kind: "ssh", endpoint: connection.endpoint };
|
||||
case "routed":
|
||||
return { kind: "routed", endpoint: connection.endpoint };
|
||||
case "directTcp": {
|
||||
if (options?.isLocalHost && isLoopbackEndpoint(connection.endpoint)) {
|
||||
return { kind: "local" };
|
||||
}
|
||||
if (isTailscaleEndpoint(connection.endpoint)) {
|
||||
return { kind: "tailscale", endpoint: formatConnectionEndpoint(connection.endpoint) };
|
||||
}
|
||||
return { kind: "direct", endpoint: formatConnectionEndpoint(connection.endpoint) };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function describeHostConnection(
|
||||
connection: HostConnection,
|
||||
options?: { isLocalHost?: boolean },
|
||||
): HostConnectionDisplay {
|
||||
switch (connection.type) {
|
||||
case "directSocket":
|
||||
case "directPipe":
|
||||
return { kind: "local" };
|
||||
case "relay":
|
||||
return { kind: "relay", endpoint: formatConnectionEndpoint(connection.relayEndpoint) };
|
||||
case "remoteSsh":
|
||||
return { kind: "ssh", endpoint: connection.host };
|
||||
case "routed":
|
||||
return { kind: "routed", endpoint: connection.originServerId };
|
||||
case "directTcp": {
|
||||
if (options?.isLocalHost && isLoopbackEndpoint(connection.endpoint)) {
|
||||
return { kind: "local" };
|
||||
}
|
||||
if (isTailscaleEndpoint(connection.endpoint)) {
|
||||
return { kind: "tailscale", endpoint: formatConnectionEndpoint(connection.endpoint) };
|
||||
}
|
||||
return { kind: "direct", endpoint: formatConnectionEndpoint(connection.endpoint) };
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
import { Text, View } from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { type HostBadgeModel, type HostColor } from "@/hosts/appearance";
|
||||
import { HostIconGlyph } from "@/hosts/host-icon-glyph";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { Server } from "lucide-react-native";
|
||||
import { HOST_COLORS, type HostBadgeModel, type HostColor } from "@/hosts/appearance";
|
||||
import { identityForeground } from "@/styles/identity-colors";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
|
||||
/**
|
||||
* The glyph size the badge draws at. Rows that place the badge alongside their own glyphs
|
||||
@@ -10,9 +11,30 @@ import { identityForeground } from "@/styles/identity-colors";
|
||||
*/
|
||||
export const HOST_BADGE_ICON_SIZE = 12;
|
||||
|
||||
const ThemedServer = withUnistyles(Server);
|
||||
|
||||
const mutedMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
|
||||
|
||||
// One stable mapping per host color for the life of the module — a fresh `uniProps` identity
|
||||
// on every render makes withUnistyles re-subscribe each pass. The scheme is read inside the
|
||||
// mapping rather than baked in, so a theme change repaints the glyph without a React render.
|
||||
//
|
||||
// Glyph and label share one color, so a badge reads as one object rather than a colored icon
|
||||
// with an unrelated grey word beside it.
|
||||
const HOST_ICON_MAPPINGS: Record<HostColor, (theme: Theme) => { color: string }> = (() => {
|
||||
const byColor = {} as Record<HostColor, (theme: Theme) => { color: string }>;
|
||||
for (const color of HOST_COLORS) {
|
||||
byColor[color] =
|
||||
color === "none"
|
||||
? mutedMapping
|
||||
: (theme: Theme) => ({ color: identityForeground(color, theme.colorScheme) });
|
||||
}
|
||||
return byColor;
|
||||
})();
|
||||
|
||||
/**
|
||||
* Which machine something lives on, drawn the same way everywhere it appears: the host's device
|
||||
* glyph and, when the host is configured to show one, its name — both in the host's identity color.
|
||||
* Which machine something lives on, drawn the same way everywhere it appears: a server glyph
|
||||
* and, when the host is configured to show one, its name — both in the host's identity color.
|
||||
*
|
||||
* A hostname is the least interesting thing on any line that carries it and the only one whose
|
||||
* length nobody chose, so the badge yields space before its neighbours rather than alongside
|
||||
@@ -25,11 +47,10 @@ export function HostBadge({ badge }: { badge: HostBadgeModel }) {
|
||||
testID={`host-badge-${badge.serverId}`}
|
||||
accessibilityLabel={badge.label}
|
||||
>
|
||||
<HostIconGlyph
|
||||
icon={badge.icon}
|
||||
color={badge.color}
|
||||
<ThemedServer
|
||||
size={HOST_BADGE_ICON_SIZE}
|
||||
style={styles.icon}
|
||||
uniProps={HOST_ICON_MAPPINGS[badge.color]}
|
||||
/>
|
||||
{badge.showLabel ? (
|
||||
<Text style={[styles.label, labelColorStyle(badge.color)]} numberOfLines={1}>
|
||||
|
||||
@@ -7,16 +7,14 @@ import {
|
||||
EditingTextInput as TextInput,
|
||||
type EditingTextInputHandle,
|
||||
} from "@/components/ui/text-input";
|
||||
import { Server } from "lucide-react-native";
|
||||
import { create } from "zustand";
|
||||
import { StyleSheet, useUnistyles } from "react-native-unistyles";
|
||||
import { HostStatusDot } from "@/components/host-status-dot";
|
||||
import { HostStatusDotSlot } from "@/components/hosts/host-picker";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
|
||||
import { resolveHostIcon } from "@/hosts/appearance";
|
||||
import { HostConnectionLine, HostIconGlyph, HostLatencyLabel } from "@/hosts/host-icon";
|
||||
import { OverlayLayerProvider, useGlobalOverlayLayer } from "@/lib/overlay-root";
|
||||
import { getHostRuntimeStore, useHosts } from "@/runtime/host-runtime";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { useHosts } from "@/runtime/host-runtime";
|
||||
import { orderHostsLocalFirst, type HostProfile } from "@/types/host-connection";
|
||||
|
||||
type HostFilter = (host: HostProfile) => boolean;
|
||||
@@ -103,52 +101,36 @@ function HostChooserRow({
|
||||
active: boolean;
|
||||
onChooseHost: (serverId: string) => void;
|
||||
}) {
|
||||
const detectedMachineKind = useSessionStore(
|
||||
(state) => state.sessions[host.serverId]?.serverInfo?.machineKind ?? null,
|
||||
);
|
||||
const resolvedIcon = resolveHostIcon({ appearance: host.appearance, detectedMachineKind });
|
||||
const [hovered, setHovered] = useState(false);
|
||||
const handlePointerEnter = useCallback(() => setHovered(true), []);
|
||||
const handlePointerLeave = useCallback(() => setHovered(false), []);
|
||||
const { theme } = useUnistyles();
|
||||
const handlePress = useCallback(() => onChooseHost(host.serverId), [host.serverId, onChooseHost]);
|
||||
const rowStyle = useCallback(
|
||||
({ pressed }: PressableStateCallbackType) => [
|
||||
({ hovered = false, pressed }: PressableStateCallbackType & { hovered?: boolean }) => [
|
||||
styles.row,
|
||||
(active || hovered || pressed) && styles.rowActive,
|
||||
],
|
||||
[active, hovered],
|
||||
[active],
|
||||
);
|
||||
|
||||
return (
|
||||
<View onPointerEnter={handlePointerEnter} onPointerLeave={handlePointerLeave}>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
onPress={handlePress}
|
||||
style={rowStyle}
|
||||
testID={`host-chooser-row-${host.serverId}`}
|
||||
>
|
||||
<View style={styles.rowIconSlot}>
|
||||
<HostStatusDot serverId={host.serverId} />
|
||||
</View>
|
||||
<View style={styles.rowText}>
|
||||
<View style={styles.rowHeader}>
|
||||
<HostIconGlyph
|
||||
icon={resolvedIcon}
|
||||
color={host.appearance.color}
|
||||
size={14}
|
||||
style={styles.rowGlyph}
|
||||
/>
|
||||
<Text style={styles.rowTitle} numberOfLines={1}>
|
||||
{host.label}
|
||||
</Text>
|
||||
</View>
|
||||
<HostConnectionLine serverId={host.serverId} />
|
||||
</View>
|
||||
<View style={styles.rowTrailing}>
|
||||
<HostLatencyLabel serverId={host.serverId} />
|
||||
</View>
|
||||
</Pressable>
|
||||
</View>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
onPress={handlePress}
|
||||
style={rowStyle}
|
||||
testID={`host-chooser-row-${host.serverId}`}
|
||||
>
|
||||
<View style={styles.rowIconSlot}>
|
||||
<HostStatusDotSlot serverId={host.serverId} />
|
||||
</View>
|
||||
<View style={styles.rowText}>
|
||||
<Text style={styles.rowTitle} numberOfLines={1}>
|
||||
{host.label}
|
||||
</Text>
|
||||
<Text style={styles.rowSubtitle} numberOfLines={1}>
|
||||
{host.serverId}
|
||||
</Text>
|
||||
</View>
|
||||
<Server size={theme.iconSize.sm} color={theme.colors.foregroundMuted} />
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -179,7 +161,6 @@ export function HostChooserModal() {
|
||||
|
||||
useEffect(() => {
|
||||
if (!request) return;
|
||||
getHostRuntimeStore().refreshActiveLatencies(request.serverIds);
|
||||
inputRef.current?.replaceText("");
|
||||
setQuery("");
|
||||
setActiveIndex(0);
|
||||
@@ -347,7 +328,7 @@ const styles = StyleSheet.create((theme) => ({
|
||||
},
|
||||
row: {
|
||||
flexDirection: "row",
|
||||
alignItems: "flex-start",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[3],
|
||||
minHeight: 56,
|
||||
paddingHorizontal: theme.spacing[4],
|
||||
@@ -356,39 +337,19 @@ const styles = StyleSheet.create((theme) => ({
|
||||
rowActive: {
|
||||
backgroundColor: theme.colors.surface1,
|
||||
},
|
||||
rowTrailing: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
height: 20,
|
||||
flexShrink: 0,
|
||||
},
|
||||
rowIconSlot: {
|
||||
width: 16,
|
||||
height: 20,
|
||||
width: 18,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
flexShrink: 0,
|
||||
},
|
||||
rowText: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
gap: theme.spacing[1],
|
||||
},
|
||||
rowHeader: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: 6,
|
||||
minWidth: 0,
|
||||
},
|
||||
rowGlyph: {
|
||||
flexShrink: 0,
|
||||
},
|
||||
rowTitle: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.base,
|
||||
lineHeight: 20,
|
||||
},
|
||||
rowSubtitle: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
|
||||
@@ -1,77 +0,0 @@
|
||||
import type { ReactElement } from "react";
|
||||
import type { StyleProp, ViewStyle } from "react-native";
|
||||
import {
|
||||
Cloud,
|
||||
Computer,
|
||||
Container,
|
||||
Cpu,
|
||||
Laptop,
|
||||
Monitor,
|
||||
PcCase,
|
||||
Server,
|
||||
Terminal,
|
||||
} from "lucide-react-native";
|
||||
import { withUnistyles } from "react-native-unistyles";
|
||||
import { DEFAULT_HOST_ICON, HOST_COLORS, type HostColor, type HostIcon } from "@/hosts/appearance";
|
||||
import { identityForeground } from "@/styles/identity-colors";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
|
||||
const ThemedServer = withUnistyles(Server);
|
||||
const ThemedLaptop = withUnistyles(Laptop);
|
||||
const ThemedMonitor = withUnistyles(Monitor);
|
||||
const ThemedComputer = withUnistyles(Computer);
|
||||
const ThemedPcCase = withUnistyles(PcCase);
|
||||
const ThemedCloud = withUnistyles(Cloud);
|
||||
const ThemedContainer = withUnistyles(Container);
|
||||
const ThemedCpu = withUnistyles(Cpu);
|
||||
const ThemedTerminal = withUnistyles(Terminal);
|
||||
|
||||
const mutedMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
|
||||
|
||||
// One stable uniProps mapping per host color for the life of the module — a fresh identity on
|
||||
// every render makes withUnistyles re-subscribe each pass. Reading `theme.colorScheme` inside the
|
||||
// mapping keeps theme switches off React's render path.
|
||||
const HOST_ICON_MAPPINGS: Record<HostColor, (theme: Theme) => { color: string }> = (() => {
|
||||
const byColor = {} as Record<HostColor, (theme: Theme) => { color: string }>;
|
||||
for (const color of HOST_COLORS) {
|
||||
byColor[color] =
|
||||
color === "none"
|
||||
? mutedMapping
|
||||
: (theme: Theme) => ({ color: identityForeground(color, theme.colorScheme) });
|
||||
}
|
||||
return byColor;
|
||||
})();
|
||||
|
||||
export function HostIconGlyph({
|
||||
icon = DEFAULT_HOST_ICON,
|
||||
color = "none",
|
||||
size = 16,
|
||||
style,
|
||||
}: {
|
||||
icon?: HostIcon;
|
||||
color?: HostColor;
|
||||
size?: number;
|
||||
style?: StyleProp<ViewStyle>;
|
||||
}): ReactElement {
|
||||
const uniProps = HOST_ICON_MAPPINGS[color];
|
||||
switch (icon) {
|
||||
case "laptop":
|
||||
return <ThemedLaptop size={size} style={style} uniProps={uniProps} />;
|
||||
case "desktop":
|
||||
return <ThemedMonitor size={size} style={style} uniProps={uniProps} />;
|
||||
case "mini":
|
||||
return <ThemedComputer size={size} style={style} uniProps={uniProps} />;
|
||||
case "workstation":
|
||||
return <ThemedPcCase size={size} style={style} uniProps={uniProps} />;
|
||||
case "cloud":
|
||||
return <ThemedCloud size={size} style={style} uniProps={uniProps} />;
|
||||
case "container":
|
||||
return <ThemedContainer size={size} style={style} uniProps={uniProps} />;
|
||||
case "board":
|
||||
return <ThemedCpu size={size} style={style} uniProps={uniProps} />;
|
||||
case "terminal":
|
||||
return <ThemedTerminal size={size} style={style} uniProps={uniProps} />;
|
||||
case "server":
|
||||
return <ThemedServer size={size} style={style} uniProps={uniProps} />;
|
||||
}
|
||||
}
|
||||
@@ -1,215 +0,0 @@
|
||||
import { useMemo, type ReactElement } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Text, View } from "react-native";
|
||||
import { Globe, Monitor, Network, Terminal, Waypoints } from "lucide-react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { TailscaleIcon } from "@/components/icons/tailscale-icon";
|
||||
import {
|
||||
describeActiveConnection,
|
||||
describeHostConnection,
|
||||
type HostConnectionKind,
|
||||
} from "@/hosts/connection-display";
|
||||
import { HostIconGlyph } from "@/hosts/host-icon-glyph";
|
||||
import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
|
||||
import { useHostRuntimeSnapshot, useHosts } from "@/runtime/host-runtime";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import type { HostProfile } from "@/types/host-connection";
|
||||
import { formatLatency } from "@/utils/latency";
|
||||
|
||||
export { HostIconGlyph };
|
||||
|
||||
const CONNECTION_GLYPH_SIZE = 11;
|
||||
|
||||
const ThemedMonitor = withUnistyles(Monitor);
|
||||
const ThemedTerminal = withUnistyles(Terminal);
|
||||
const ThemedGlobe = withUnistyles(Globe);
|
||||
const ThemedNetwork = withUnistyles(Network);
|
||||
const ThemedWaypoints = withUnistyles(Waypoints);
|
||||
const ThemedTailscale = withUnistyles(TailscaleIcon);
|
||||
|
||||
const extraMutedMapping = (theme: Theme) => ({ color: theme.colors.foregroundExtraMuted });
|
||||
|
||||
function ConnectionKindGlyph({ kind }: { kind: HostConnectionKind }): ReactElement {
|
||||
switch (kind) {
|
||||
case "local":
|
||||
return (
|
||||
<ThemedMonitor
|
||||
size={CONNECTION_GLYPH_SIZE}
|
||||
style={styles.linkIcon}
|
||||
uniProps={extraMutedMapping}
|
||||
/>
|
||||
);
|
||||
case "relay":
|
||||
return (
|
||||
<ThemedGlobe
|
||||
size={CONNECTION_GLYPH_SIZE}
|
||||
style={styles.linkIcon}
|
||||
uniProps={extraMutedMapping}
|
||||
/>
|
||||
);
|
||||
case "tailscale":
|
||||
return <ThemedTailscale size={CONNECTION_GLYPH_SIZE} uniProps={extraMutedMapping} />;
|
||||
case "ssh":
|
||||
return (
|
||||
<ThemedTerminal
|
||||
size={CONNECTION_GLYPH_SIZE}
|
||||
style={styles.linkIcon}
|
||||
uniProps={extraMutedMapping}
|
||||
/>
|
||||
);
|
||||
case "routed":
|
||||
return (
|
||||
<ThemedWaypoints
|
||||
size={CONNECTION_GLYPH_SIZE}
|
||||
style={styles.linkIcon}
|
||||
uniProps={extraMutedMapping}
|
||||
/>
|
||||
);
|
||||
case "direct":
|
||||
return (
|
||||
<ThemedNetwork
|
||||
size={CONNECTION_GLYPH_SIZE}
|
||||
style={styles.linkIcon}
|
||||
uniProps={extraMutedMapping}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function resolvePreferredConnection(host: HostProfile | undefined) {
|
||||
if (!host || host.connections.length === 0) return null;
|
||||
if (host.preferredConnectionId) {
|
||||
const preferred = host.connections.find(
|
||||
(connection) => connection.id === host.preferredConnectionId,
|
||||
);
|
||||
if (preferred) return preferred;
|
||||
}
|
||||
return host.connections[0] ?? null;
|
||||
}
|
||||
|
||||
export function HostConnectionLine({ serverId }: { serverId: string }): ReactElement | null {
|
||||
const { t } = useTranslation();
|
||||
const snapshot = useHostRuntimeSnapshot(serverId);
|
||||
const localServerId = useLocalDaemonServerId();
|
||||
const hosts = useHosts();
|
||||
const activeConnection = snapshot?.activeConnection ?? null;
|
||||
const hostProfile = useMemo(
|
||||
() => hosts.find((candidate) => candidate.serverId === serverId),
|
||||
[hosts, serverId],
|
||||
);
|
||||
const fallbackConnection = useMemo(
|
||||
() => (activeConnection ? null : resolvePreferredConnection(hostProfile)),
|
||||
[activeConnection, hostProfile],
|
||||
);
|
||||
|
||||
const described = useMemo(() => {
|
||||
const options = { isLocalHost: serverId === localServerId };
|
||||
if (activeConnection) {
|
||||
return describeActiveConnection(activeConnection, options);
|
||||
}
|
||||
if (fallbackConnection) {
|
||||
return describeHostConnection(fallbackConnection, options);
|
||||
}
|
||||
return null;
|
||||
}, [activeConnection, fallbackConnection, localServerId, serverId]);
|
||||
|
||||
if (!described) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const endpoint =
|
||||
described.kind === "routed" && described.endpoint
|
||||
? (hosts.find((host) => host.serverId === described.endpoint)?.label ?? described.endpoint)
|
||||
: described.endpoint;
|
||||
|
||||
return (
|
||||
<View style={styles.connectionRow}>
|
||||
<View style={styles.linkIconSlot}>
|
||||
<ConnectionKindGlyph kind={described.kind} />
|
||||
</View>
|
||||
<Text style={styles.connectionKind} numberOfLines={1}>
|
||||
{t(`settings.host.connectionKinds.${described.kind}`)}
|
||||
</Text>
|
||||
{endpoint ? (
|
||||
<Text style={styles.connectionEndpoint} numberOfLines={1}>
|
||||
{endpoint}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export function HostLatencyLabel({ serverId }: { serverId: string }): ReactElement | null {
|
||||
const { t } = useTranslation();
|
||||
const snapshot = useHostRuntimeSnapshot(serverId);
|
||||
const status = snapshot?.connectionStatus;
|
||||
const activeConnectionId = snapshot?.activeConnectionId;
|
||||
const activeProbe = activeConnectionId
|
||||
? snapshot?.probeByConnectionId.get(activeConnectionId)
|
||||
: undefined;
|
||||
const latencyMs =
|
||||
status === "online" && activeProbe?.status === "available" ? activeProbe.latencyMs : null;
|
||||
|
||||
if (latencyMs !== null) {
|
||||
return (
|
||||
<Text style={styles.latency} numberOfLines={1}>
|
||||
{formatLatency(latencyMs)}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
if (status === "offline" || status === "error") {
|
||||
return (
|
||||
<Text style={styles.statusText} numberOfLines={1}>
|
||||
{t("common.connectionStatus.offline")}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
connectionRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: 6,
|
||||
minWidth: 0,
|
||||
},
|
||||
// Matches the 14px host icon width on the row above so connection text aligns on the same rail.
|
||||
linkIconSlot: {
|
||||
width: 14,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
flexShrink: 0,
|
||||
},
|
||||
linkIcon: {
|
||||
flexShrink: 0,
|
||||
},
|
||||
connectionKind: {
|
||||
fontSize: theme.fontSize.sm,
|
||||
lineHeight: 16,
|
||||
color: theme.colors.foregroundMuted,
|
||||
flexShrink: 0,
|
||||
},
|
||||
connectionEndpoint: {
|
||||
fontSize: theme.fontSize.sm,
|
||||
lineHeight: 16,
|
||||
color: theme.colors.foregroundExtraMuted,
|
||||
flexShrink: 1,
|
||||
minWidth: 0,
|
||||
},
|
||||
latency: {
|
||||
fontSize: theme.fontSize.sm,
|
||||
lineHeight: 16,
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontVariant: ["tabular-nums"],
|
||||
flexShrink: 0,
|
||||
},
|
||||
statusText: {
|
||||
fontSize: theme.fontSize.sm,
|
||||
lineHeight: 16,
|
||||
color: theme.colors.foregroundExtraMuted,
|
||||
flexShrink: 0,
|
||||
},
|
||||
}));
|
||||
@@ -1,13 +1,11 @@
|
||||
import { useMemo } from "react";
|
||||
import { useShallow } from "zustand/react/shallow";
|
||||
import { useHosts } from "@/runtime/host-runtime";
|
||||
import { useLocalDaemonServerId, useLocalDaemonServerIdState } from "@/hooks/use-is-local-daemon";
|
||||
import { selectHostBadges, type HostBadgeModel } from "@/hosts/appearance";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
|
||||
/**
|
||||
* Every host's badge, resolved from the host registry, local-host detection, daemon-reported
|
||||
* machine kind, and each host's own appearance. `enabled` is the caller's own "off" — a surface
|
||||
* Every host's badge, resolved from the three things that decide one: the host registry, which
|
||||
* host is local, and each host's own appearance. `enabled` is the caller's own "off" — a surface
|
||||
* that has its own reason to hide badges passes false rather than filtering the result, so the
|
||||
* per-host setting stays the only thing that decides name vs icon vs hidden.
|
||||
*/
|
||||
@@ -19,25 +17,14 @@ export function useHostBadges({
|
||||
const hosts = useHosts();
|
||||
const localServerId = useLocalDaemonServerId();
|
||||
const localDaemon = useLocalDaemonServerIdState();
|
||||
const detectedMachineKinds = useSessionStore(
|
||||
useShallow((state) => {
|
||||
const result: Record<string, string | null> = {};
|
||||
for (const host of hosts) {
|
||||
result[host.serverId] = state.sessions[host.serverId]?.serverInfo?.machineKind ?? null;
|
||||
}
|
||||
return result;
|
||||
}),
|
||||
return useMemo(
|
||||
() =>
|
||||
selectHostBadges({
|
||||
hosts,
|
||||
localServerId,
|
||||
localHostResolutionPending: localDaemon.status !== "resolved",
|
||||
enabled,
|
||||
}),
|
||||
[hosts, localDaemon.status, localServerId, enabled],
|
||||
);
|
||||
return useMemo(() => {
|
||||
const detectedMachineKindByServerId = new Map<string, string | null>(
|
||||
Object.entries(detectedMachineKinds),
|
||||
);
|
||||
return selectHostBadges({
|
||||
hosts,
|
||||
localServerId,
|
||||
localHostResolutionPending: localDaemon.status !== "resolved",
|
||||
detectedMachineKindByServerId,
|
||||
enabled,
|
||||
});
|
||||
}, [hosts, localDaemon.status, localServerId, detectedMachineKinds, enabled]);
|
||||
}
|
||||
|
||||
@@ -345,7 +345,6 @@ export const ar: TranslationResources = {
|
||||
viewDiagram: "عرض المخطط",
|
||||
},
|
||||
actions: {
|
||||
copyQuote: "نسخ الاقتباس",
|
||||
copyCode: "نسخ الرمز",
|
||||
copyTurn: "نسخ بدوره",
|
||||
copyMessage: "انسخ الرسالة",
|
||||
@@ -739,6 +738,8 @@ export const ar: TranslationResources = {
|
||||
resumeCommandUnavailable: "أمر الاستئناف غير متوفر",
|
||||
reloadingAgent: "وكيل إعادة التحميل...",
|
||||
reloadedAgent: "وكيل إعادة تحميل",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"تمت إعادة تحميل الوكيل، لكن سجل المزوّد لا يطابق هذه المحادثة، لذا لم تتم مزامنته",
|
||||
failedToReloadAgent: "فشل في إعادة تحميل الوكيل",
|
||||
failedToCloseAgent: "فشل في إغلاق الوكيل",
|
||||
},
|
||||
@@ -1539,8 +1540,6 @@ export const ar: TranslationResources = {
|
||||
status: {
|
||||
checking: "جارٍ التحقق من وجود تحديثات للتطبيق...",
|
||||
installing: "جارٍ تثبيت تحديث التطبيق...",
|
||||
downloadingVersionProgress: "جارٍ تنزيل {{version}}... {{percent}}%",
|
||||
downloadingProgress: "جارٍ تنزيل تحديث التطبيق... {{percent}}%",
|
||||
upToDate: "التطبيق محدث.",
|
||||
upToDateWithLastChecked: "Up to date. Last checked at {{time}}.",
|
||||
pending: "سنخبرك عندما يصبح التحديث جاهزًا.",
|
||||
@@ -1548,14 +1547,6 @@ export const ar: TranslationResources = {
|
||||
pendingWithVersion: "تم العثور على تحديث: {{version}}. جارٍ التنزيل...",
|
||||
pendingWithVersionAndLastChecked:
|
||||
"تم العثور على تحديث: {{version}}. جارٍ التنزيل... آخر فحص في {{time}}.",
|
||||
pendingWithVersionProgress: "تم العثور على تحديث: {{version}}. جارٍ التنزيل... {{percent}}%",
|
||||
pendingWithVersionProgressAndLastChecked:
|
||||
"تم العثور على تحديث: {{version}}. جارٍ التنزيل... {{percent}}% آخر فحص في {{time}}.",
|
||||
downloadAvailableWithVersion: "التحديث متاح: {{version}}",
|
||||
downloadAvailableWithVersionAndLastChecked:
|
||||
"التحديث متاح: {{version}}. آخر فحص في {{time}}.",
|
||||
downloadAvailable: "يتوفر تحديث للتطبيق.",
|
||||
downloadAvailableWithLastChecked: "يتوفر تحديث للتطبيق. آخر فحص في {{time}}.",
|
||||
availableWithVersion: "التحديث جاهز:{{version}}",
|
||||
availableWithVersionAndLastChecked: "التحديث جاهز:{{version}}. آخر فحص في {{time}}.",
|
||||
available: "تحديث التطبيق جاهز للتثبيت.",
|
||||
@@ -1566,21 +1557,14 @@ export const ar: TranslationResources = {
|
||||
},
|
||||
installError: "غير قادر على تثبيت تحديث تطبيق سطح المكتب.",
|
||||
callout: {
|
||||
downloadingTitle: "جارٍ تنزيل التحديث",
|
||||
installingTitle: "تثبيت التحديث",
|
||||
failedTitle: "فشل التحديث",
|
||||
availableTitle: "التحديث متاح",
|
||||
genericError: "حدث خطأ ما.",
|
||||
whatsNew: "ما هو الجديد",
|
||||
downloadingAction: "جارٍ التنزيل...",
|
||||
installingAction: "جارٍ التثبيت...",
|
||||
downloadAndRestart: "تنزيل",
|
||||
installAndRestart: "التثبيت وإعادة التشغيل",
|
||||
downloadingVersionDescription: "جارٍ تنزيل {{version}}... {{percent}}%",
|
||||
downloadingDescription: "جارٍ تنزيل التحديث... {{percent}}%",
|
||||
installingDescription: "التثبيت وإعادة التشغيل...",
|
||||
versionAvailable: "{{version}} متاح للتنزيل.",
|
||||
newVersionAvailable: "يتوفر إصدار جديد للتنزيل.",
|
||||
versionReady: "{{version}}جاهز للتثبيت.",
|
||||
newVersionReady: "إصدار جديد جاهز للتثبيت.",
|
||||
restartWarning: "ستؤدي ترقية التطبيق إلى إيقاف تشغيل الوكلاء وإغلاق الجلسات الطرفية.",
|
||||
@@ -2657,28 +2641,9 @@ export const ar: TranslationResources = {
|
||||
stable: "Stable",
|
||||
beta: "Beta",
|
||||
},
|
||||
autoUpdate: {
|
||||
label: "التحديثات التلقائية",
|
||||
options: {
|
||||
automatic: "تلقائي",
|
||||
notify: "إشعار",
|
||||
off: "إيقاف",
|
||||
},
|
||||
descriptions: {
|
||||
automatic: "التحقق من التحديثات وتنزيلها في الخلفية",
|
||||
notify: "التحقق من التحديثات وتنزيلها فقط عند اختيارك",
|
||||
off: "عدم التحقق تلقائيًا. يتم التحقق فقط عند النقر على فحص",
|
||||
},
|
||||
},
|
||||
updates: {
|
||||
label: "تحديثات التطبيق",
|
||||
readyToInstall: "جاهز للتثبيت:{{version}}",
|
||||
downloadTitle: "تنزيل تحديث سطح المكتب",
|
||||
downloadMessage: "سيؤدي هذا إلى تنزيل تحديث Paseo وتثبيته على هذا الكمبيوتر",
|
||||
downloadConfirm: "تنزيل وتثبيت",
|
||||
download: "تنزيل",
|
||||
downloadTo: "تنزيل {{version}}",
|
||||
downloading: "جارٍ التنزيل...",
|
||||
installTitle: "تثبيت تحديث سطح المكتب",
|
||||
installMessage: "يؤدي هذا إلى تحديث Paseo على هذا الكمبيوتر",
|
||||
installConfirm: "تثبيت التحديث",
|
||||
@@ -2878,23 +2843,6 @@ export const ar: TranslationResources = {
|
||||
name: {
|
||||
label: "الاسم",
|
||||
},
|
||||
icon: {
|
||||
label: "الأيقونة",
|
||||
accessibilityLabel: "الأيقونة، {{value}}",
|
||||
auto: "تلقائي",
|
||||
autoDetected: "تلقائي ({{icon}})",
|
||||
options: {
|
||||
server: "خادم",
|
||||
laptop: "حاسوب محمول",
|
||||
desktop: "حاسوب مكتبي",
|
||||
mini: "حاسوب مصغّر",
|
||||
workstation: "محطة عمل",
|
||||
cloud: "سحابي",
|
||||
container: "حاوية",
|
||||
board: "حاسوب أحادي اللوحة",
|
||||
terminal: "طرفية",
|
||||
},
|
||||
},
|
||||
color: {
|
||||
label: "اللون",
|
||||
accessibilityLabel: "اللون، {{value}}",
|
||||
@@ -2931,14 +2879,6 @@ export const ar: TranslationResources = {
|
||||
local: "محلي",
|
||||
remoteSsh: "SSH عن بُعد",
|
||||
},
|
||||
connectionKinds: {
|
||||
local: "محلي",
|
||||
relay: "تتابع",
|
||||
tailscale: "Tailscale",
|
||||
ssh: "SSH",
|
||||
direct: "مباشر",
|
||||
routed: "عبر",
|
||||
},
|
||||
connections: {
|
||||
title: "اتصالات",
|
||||
removeTitle: "إزالة الاتصال",
|
||||
|
||||
@@ -344,7 +344,6 @@ export const en = {
|
||||
viewDiagram: "View diagram",
|
||||
},
|
||||
actions: {
|
||||
copyQuote: "Copy quote",
|
||||
copyCode: "Copy code",
|
||||
copyTurn: "Copy turn",
|
||||
copyMessage: "Copy message",
|
||||
@@ -738,6 +737,8 @@ export const en = {
|
||||
resumeCommandUnavailable: "Resume command not available",
|
||||
reloadingAgent: "Reloading agent...",
|
||||
reloadedAgent: "Reloaded agent",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"Reloaded agent, but the provider's history doesn't match this chat, so it wasn't synced",
|
||||
failedToReloadAgent: "Failed to reload agent",
|
||||
failedToCloseAgent: "Failed to close agent",
|
||||
},
|
||||
@@ -1566,8 +1567,6 @@ export const en = {
|
||||
status: {
|
||||
checking: "Checking for app updates...",
|
||||
installing: "Installing app update...",
|
||||
downloadingVersionProgress: "Downloading {{version}}... {{percent}}%",
|
||||
downloadingProgress: "Downloading app update... {{percent}}%",
|
||||
upToDate: "App is up to date.",
|
||||
upToDateWithLastChecked: "Up to date. Last checked at {{time}}.",
|
||||
pending: "We'll let you know when the update is ready.",
|
||||
@@ -1576,14 +1575,6 @@ export const en = {
|
||||
pendingWithVersion: "Update found: {{version}}. Downloading...",
|
||||
pendingWithVersionAndLastChecked:
|
||||
"Update found: {{version}}. Downloading... Last checked at {{time}}.",
|
||||
pendingWithVersionProgress: "Update found: {{version}}. Downloading... {{percent}}%",
|
||||
pendingWithVersionProgressAndLastChecked:
|
||||
"Update found: {{version}}. Downloading... {{percent}}% Last checked at {{time}}.",
|
||||
downloadAvailableWithVersion: "Update available: {{version}}",
|
||||
downloadAvailableWithVersionAndLastChecked:
|
||||
"Update available: {{version}}. Last checked at {{time}}.",
|
||||
downloadAvailable: "An app update is available.",
|
||||
downloadAvailableWithLastChecked: "An app update is available. Last checked at {{time}}.",
|
||||
availableWithVersion: "Update ready: {{version}}",
|
||||
availableWithVersionAndLastChecked: "Update ready: {{version}}. Last checked at {{time}}.",
|
||||
available: "An app update is ready to install.",
|
||||
@@ -1594,21 +1585,14 @@ export const en = {
|
||||
},
|
||||
installError: "Unable to install the desktop app update.",
|
||||
callout: {
|
||||
downloadingTitle: "Downloading update",
|
||||
installingTitle: "Installing update",
|
||||
failedTitle: "Update failed",
|
||||
availableTitle: "Update available",
|
||||
genericError: "Something went wrong.",
|
||||
whatsNew: "What's new",
|
||||
downloadingAction: "Downloading...",
|
||||
installingAction: "Installing...",
|
||||
downloadAndRestart: "Download",
|
||||
installAndRestart: "Install & restart",
|
||||
downloadingVersionDescription: "Downloading {{version}}... {{percent}}%",
|
||||
downloadingDescription: "Downloading update... {{percent}}%",
|
||||
installingDescription: "Installing and restarting...",
|
||||
versionAvailable: "{{version}} is available to download.",
|
||||
newVersionAvailable: "A new version is available to download.",
|
||||
versionReady: "{{version}} is ready to install.",
|
||||
newVersionReady: "A new version is ready to install.",
|
||||
restartWarning: "Upgrading the app will stop running agents and close terminal sessions.",
|
||||
@@ -2753,28 +2737,9 @@ export const en = {
|
||||
stable: "Stable",
|
||||
beta: "Beta",
|
||||
},
|
||||
autoUpdate: {
|
||||
label: "Automatic updates",
|
||||
options: {
|
||||
automatic: "Auto",
|
||||
notify: "Notify",
|
||||
off: "Off",
|
||||
},
|
||||
descriptions: {
|
||||
automatic: "Check and download updates in the background",
|
||||
notify: "Check for updates, but only download when you choose",
|
||||
off: "Never check automatically. Only check when you click Check",
|
||||
},
|
||||
},
|
||||
updates: {
|
||||
label: "App updates",
|
||||
readyToInstall: "Ready to install: {{version}}",
|
||||
downloadTitle: "Download desktop update",
|
||||
downloadMessage: "This downloads and installs the Paseo update on this computer",
|
||||
downloadConfirm: "Download & install",
|
||||
download: "Download",
|
||||
downloadTo: "Download {{version}}",
|
||||
downloading: "Downloading...",
|
||||
installTitle: "Install desktop update",
|
||||
installMessage: "This updates Paseo on this computer",
|
||||
installConfirm: "Install update",
|
||||
@@ -2973,23 +2938,6 @@ export const en = {
|
||||
name: {
|
||||
label: "Name",
|
||||
},
|
||||
icon: {
|
||||
label: "Icon",
|
||||
accessibilityLabel: "Icon, {{value}}",
|
||||
auto: "Auto",
|
||||
autoDetected: "Auto ({{icon}})",
|
||||
options: {
|
||||
server: "Server",
|
||||
laptop: "Laptop",
|
||||
desktop: "Desktop",
|
||||
mini: "Mini",
|
||||
workstation: "Workstation",
|
||||
cloud: "Cloud",
|
||||
container: "Container",
|
||||
board: "Single-board PC",
|
||||
terminal: "Terminal",
|
||||
},
|
||||
},
|
||||
color: {
|
||||
label: "Color",
|
||||
accessibilityLabel: "Color, {{value}}",
|
||||
@@ -3026,14 +2974,6 @@ export const en = {
|
||||
local: "Local",
|
||||
remoteSsh: "Remote SSH",
|
||||
},
|
||||
connectionKinds: {
|
||||
local: "Local",
|
||||
relay: "Relay",
|
||||
tailscale: "Tailscale",
|
||||
ssh: "SSH",
|
||||
direct: "Direct",
|
||||
routed: "Via",
|
||||
},
|
||||
connections: {
|
||||
title: "Connections",
|
||||
removeTitle: "Remove connection",
|
||||
|
||||
@@ -350,7 +350,6 @@ export const es: TranslationResources = {
|
||||
viewDiagram: "Ver diagrama",
|
||||
},
|
||||
actions: {
|
||||
copyQuote: "Copiar cita",
|
||||
copyCode: "Copiar código",
|
||||
copyTurn: "Copiar turno",
|
||||
copyMessage: "Copiar mensaje",
|
||||
@@ -746,6 +745,8 @@ export const es: TranslationResources = {
|
||||
resumeCommandUnavailable: "Comando de reanudación no disponible",
|
||||
reloadingAgent: "Agente de recarga...",
|
||||
reloadedAgent: "Agente recargado",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"Agente recargado, pero el historial del proveedor no coincide con este chat, así que no se sincronizó",
|
||||
failedToReloadAgent: "No se pudo recargar el agente",
|
||||
failedToCloseAgent: "No se pudo cerrar el agente",
|
||||
},
|
||||
@@ -1576,8 +1577,6 @@ export const es: TranslationResources = {
|
||||
status: {
|
||||
checking: "Buscando actualizaciones de la aplicación...",
|
||||
installing: "Instalando actualización de la aplicación...",
|
||||
downloadingVersionProgress: "Descargando {{version}}... {{percent}}%",
|
||||
downloadingProgress: "Descargando actualización de la aplicación... {{percent}}%",
|
||||
upToDate: "La aplicación está actualizada.",
|
||||
upToDateWithLastChecked: "Up to date. Last checked at {{time}}.",
|
||||
pending: "Le avisaremos cuando la actualización esté lista.",
|
||||
@@ -1586,16 +1585,6 @@ export const es: TranslationResources = {
|
||||
pendingWithVersion: "Actualización encontrada: {{version}}. Descargando...",
|
||||
pendingWithVersionAndLastChecked:
|
||||
"Actualización encontrada: {{version}}. Descargando... Última comprobación a las {{time}}.",
|
||||
pendingWithVersionProgress:
|
||||
"Actualización encontrada: {{version}}. Descargando... {{percent}}%",
|
||||
pendingWithVersionProgressAndLastChecked:
|
||||
"Actualización encontrada: {{version}}. Descargando... {{percent}}% Última comprobación a las {{time}}.",
|
||||
downloadAvailableWithVersion: "Actualización disponible: {{version}}",
|
||||
downloadAvailableWithVersionAndLastChecked:
|
||||
"Actualización disponible: {{version}}. Última comprobación a las {{time}}.",
|
||||
downloadAvailable: "Hay una actualización de la aplicación disponible.",
|
||||
downloadAvailableWithLastChecked:
|
||||
"Hay una actualización de la aplicación disponible. Última comprobación a las {{time}}.",
|
||||
availableWithVersion: "Actualización lista:{{version}}",
|
||||
availableWithVersionAndLastChecked:
|
||||
"Actualización lista:{{version}}. Última comprobación a las {{time}}.",
|
||||
@@ -1608,21 +1597,14 @@ export const es: TranslationResources = {
|
||||
},
|
||||
installError: "No se puede instalar la actualización de la aplicación de escritorio.",
|
||||
callout: {
|
||||
downloadingTitle: "Descargando actualización",
|
||||
installingTitle: "Instalando actualización",
|
||||
failedTitle: "La actualización falló",
|
||||
availableTitle: "Actualización disponible",
|
||||
genericError: "Algo salió mal.",
|
||||
whatsNew: "Qué hay de nuevo",
|
||||
downloadingAction: "Descargando...",
|
||||
installingAction: "Instalando...",
|
||||
downloadAndRestart: "Descargar",
|
||||
installAndRestart: "Instalar y reiniciar",
|
||||
downloadingVersionDescription: "Descargando {{version}}... {{percent}}%",
|
||||
downloadingDescription: "Descargando actualización... {{percent}}%",
|
||||
installingDescription: "Instalando y reiniciando...",
|
||||
versionAvailable: "{{version}} está disponible para descargar.",
|
||||
newVersionAvailable: "Una nueva versión está disponible para descargar.",
|
||||
versionReady: "{{version}}está listo para instalar.",
|
||||
newVersionReady: "Una nueva versión está lista para instalar.",
|
||||
restartWarning:
|
||||
@@ -2680,28 +2662,9 @@ export const es: TranslationResources = {
|
||||
stable: "Stable",
|
||||
beta: "Beta",
|
||||
},
|
||||
autoUpdate: {
|
||||
label: "Actualizaciones automáticas",
|
||||
options: {
|
||||
automatic: "Auto",
|
||||
notify: "Notificar",
|
||||
off: "Desactivado",
|
||||
},
|
||||
descriptions: {
|
||||
automatic: "Buscar y descargar actualizaciones en segundo plano",
|
||||
notify: "Buscar actualizaciones, pero descargar solo cuando lo elijas",
|
||||
off: "No buscar automáticamente. Solo buscar al hacer clic en Comprobar",
|
||||
},
|
||||
},
|
||||
updates: {
|
||||
label: "Actualizaciones de aplicaciones",
|
||||
readyToInstall: "Listo para instalar:{{version}}",
|
||||
downloadTitle: "Descargar actualización de escritorio",
|
||||
downloadMessage: "Esto descarga e instala la actualización de Paseo en esta computadora.",
|
||||
downloadConfirm: "Descargar e instalar",
|
||||
download: "Descargar",
|
||||
downloadTo: "Descargar {{version}}",
|
||||
downloading: "Descargando...",
|
||||
installTitle: "Instalar actualización de escritorio",
|
||||
installMessage: "Esto actualizaPaseoen esta computadora.",
|
||||
installConfirm: "Instalar actualización",
|
||||
@@ -2904,23 +2867,6 @@ export const es: TranslationResources = {
|
||||
name: {
|
||||
label: "Nombre",
|
||||
},
|
||||
icon: {
|
||||
label: "Icono",
|
||||
accessibilityLabel: "Icono, {{value}}",
|
||||
auto: "Automático",
|
||||
autoDetected: "Automático ({{icon}})",
|
||||
options: {
|
||||
server: "Servidor",
|
||||
laptop: "Portátil",
|
||||
desktop: "Escritorio",
|
||||
mini: "Mini",
|
||||
workstation: "Estación de trabajo",
|
||||
cloud: "Nube",
|
||||
container: "Contenedor",
|
||||
board: "PC de placa única",
|
||||
terminal: "Terminal",
|
||||
},
|
||||
},
|
||||
color: {
|
||||
label: "Color",
|
||||
accessibilityLabel: "Color, {{value}}",
|
||||
@@ -2957,14 +2903,6 @@ export const es: TranslationResources = {
|
||||
local: "Local",
|
||||
remoteSsh: "SSH remoto",
|
||||
},
|
||||
connectionKinds: {
|
||||
local: "Local",
|
||||
relay: "Relé",
|
||||
tailscale: "Tailscale",
|
||||
ssh: "SSH",
|
||||
direct: "Directo",
|
||||
routed: "Vía",
|
||||
},
|
||||
connections: {
|
||||
title: "Conexiones",
|
||||
removeTitle: "Quitar conexión",
|
||||
|
||||
@@ -350,7 +350,6 @@ export const fr: TranslationResources = {
|
||||
viewDiagram: "Afficher le diagramme",
|
||||
},
|
||||
actions: {
|
||||
copyQuote: "Copier la citation",
|
||||
copyCode: "Copier le code",
|
||||
copyTurn: "Copier l’échange",
|
||||
copyMessage: "Copier le message",
|
||||
@@ -746,6 +745,8 @@ export const fr: TranslationResources = {
|
||||
resumeCommandUnavailable: "Commande de reprise indisponible",
|
||||
reloadingAgent: "Rechargement de l’agent…",
|
||||
reloadedAgent: "Agent rechargé",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"Agent rechargé, mais l’historique du fournisseur ne correspond pas à cette conversation, il n’a donc pas été synchronisé",
|
||||
failedToReloadAgent: "Impossible de recharger l’agent",
|
||||
failedToCloseAgent: "Impossible de fermer l’agent",
|
||||
},
|
||||
@@ -1569,8 +1570,6 @@ export const fr: TranslationResources = {
|
||||
status: {
|
||||
checking: "Recherche de mises à jour de l’application…",
|
||||
installing: "Installation de la mise à jour de l’application…",
|
||||
downloadingVersionProgress: "Téléchargement de {{version}}… {{percent}} %",
|
||||
downloadingProgress: "Téléchargement de la mise à jour… {{percent}} %",
|
||||
upToDate: "L’application est à jour.",
|
||||
upToDateWithLastChecked: "À jour. Dernière vérification à {{time}}.",
|
||||
pending: "Nous vous préviendrons quand la mise à jour sera prête.",
|
||||
@@ -1579,16 +1578,6 @@ export const fr: TranslationResources = {
|
||||
pendingWithVersion: "Mise à jour trouvée : {{version}}. Téléchargement…",
|
||||
pendingWithVersionAndLastChecked:
|
||||
"Mise à jour trouvée : {{version}}. Téléchargement… Dernière vérification à {{time}}.",
|
||||
pendingWithVersionProgress:
|
||||
"Mise à jour trouvée : {{version}}. Téléchargement… {{percent}} %",
|
||||
pendingWithVersionProgressAndLastChecked:
|
||||
"Mise à jour trouvée : {{version}}. Téléchargement… {{percent}} % Dernière vérification à {{time}}.",
|
||||
downloadAvailableWithVersion: "Mise à jour disponible : {{version}}",
|
||||
downloadAvailableWithVersionAndLastChecked:
|
||||
"Mise à jour disponible : {{version}}. Dernière vérification à {{time}}.",
|
||||
downloadAvailable: "Une mise à jour de l’application est disponible.",
|
||||
downloadAvailableWithLastChecked:
|
||||
"Une mise à jour de l’application est disponible. Dernière vérification à {{time}}.",
|
||||
availableWithVersion: "Mise à jour prête : {{version}}",
|
||||
availableWithVersionAndLastChecked:
|
||||
"Mise à jour prête : {{version}}. Dernière vérification à {{time}}.",
|
||||
@@ -1601,21 +1590,14 @@ export const fr: TranslationResources = {
|
||||
},
|
||||
installError: "Impossible d’installer la mise à jour de l’application de bureau.",
|
||||
callout: {
|
||||
downloadingTitle: "Téléchargement de la mise à jour",
|
||||
installingTitle: "Installation de la mise à jour",
|
||||
failedTitle: "Échec de la mise à jour",
|
||||
availableTitle: "Mise à jour disponible",
|
||||
genericError: "Une erreur s’est produite.",
|
||||
whatsNew: "Nouveautés",
|
||||
downloadingAction: "Téléchargement…",
|
||||
installingAction: "Installation…",
|
||||
downloadAndRestart: "Télécharger",
|
||||
installAndRestart: "Installer et redémarrer",
|
||||
downloadingVersionDescription: "Téléchargement de {{version}}… {{percent}} %",
|
||||
downloadingDescription: "Téléchargement de la mise à jour… {{percent}} %",
|
||||
installingDescription: "Installation et redémarrage…",
|
||||
versionAvailable: "La version {{version}} est disponible au téléchargement.",
|
||||
newVersionAvailable: "Une nouvelle version est disponible au téléchargement.",
|
||||
versionReady: "La version {{version}} est prête à être installée.",
|
||||
newVersionReady: "Une nouvelle version est prête à être installée.",
|
||||
restartWarning:
|
||||
@@ -2680,28 +2662,9 @@ export const fr: TranslationResources = {
|
||||
stable: "Stable",
|
||||
beta: "Bêta",
|
||||
},
|
||||
autoUpdate: {
|
||||
label: "Mises à jour automatiques",
|
||||
options: {
|
||||
automatic: "Auto",
|
||||
notify: "Notifier",
|
||||
off: "Désactivé",
|
||||
},
|
||||
descriptions: {
|
||||
automatic: "Vérifier et télécharger les mises à jour en arrière-plan",
|
||||
notify: "Vérifier les mises à jour, mais ne télécharger que lorsque vous choisissez",
|
||||
off: "Ne jamais vérifier automatiquement. Vérifier uniquement sur clic sur Vérifier",
|
||||
},
|
||||
},
|
||||
updates: {
|
||||
label: "Mises à jour de l’application",
|
||||
readyToInstall: "Prête à installer : {{version}}",
|
||||
downloadTitle: "Télécharger la mise à jour de l’app de bureau",
|
||||
downloadMessage: "La mise à jour de Paseo sera téléchargée et installée sur cet ordinateur",
|
||||
downloadConfirm: "Télécharger et installer",
|
||||
download: "Télécharger",
|
||||
downloadTo: "Télécharger {{version}}",
|
||||
downloading: "Téléchargement…",
|
||||
installTitle: "Installer la mise à jour de l’app de bureau",
|
||||
installMessage: "Paseo sera mis à jour sur cet ordinateur",
|
||||
installConfirm: "Installer la mise à jour",
|
||||
@@ -2906,23 +2869,6 @@ export const fr: TranslationResources = {
|
||||
name: {
|
||||
label: "Nom",
|
||||
},
|
||||
icon: {
|
||||
label: "Icône",
|
||||
accessibilityLabel: "Icône, {{value}}",
|
||||
auto: "Auto",
|
||||
autoDetected: "Auto ({{icon}})",
|
||||
options: {
|
||||
server: "Serveur",
|
||||
laptop: "Portable",
|
||||
desktop: "Bureau",
|
||||
mini: "Mini",
|
||||
workstation: "Station de travail",
|
||||
cloud: "Cloud",
|
||||
container: "Conteneur",
|
||||
board: "Ordinateur monocarte",
|
||||
terminal: "Terminal",
|
||||
},
|
||||
},
|
||||
color: {
|
||||
label: "Couleur",
|
||||
accessibilityLabel: "Couleur, {{value}}",
|
||||
@@ -2959,14 +2905,6 @@ export const fr: TranslationResources = {
|
||||
local: "Local",
|
||||
remoteSsh: "SSH distant",
|
||||
},
|
||||
connectionKinds: {
|
||||
local: "Local",
|
||||
relay: "Relais",
|
||||
tailscale: "Tailscale",
|
||||
ssh: "SSH",
|
||||
direct: "Direct",
|
||||
routed: "Via",
|
||||
},
|
||||
connections: {
|
||||
title: "Connexions",
|
||||
removeTitle: "Supprimer la connexion",
|
||||
|
||||
@@ -350,7 +350,6 @@ export const ja: TranslationResources = {
|
||||
viewDiagram: "図を表示",
|
||||
},
|
||||
actions: {
|
||||
copyQuote: "引用をコピー",
|
||||
copyCode: "コードをコピー",
|
||||
copyTurn: "ターンをコピー",
|
||||
copyMessage: "メッセージをコピー",
|
||||
@@ -746,6 +745,8 @@ export const ja: TranslationResources = {
|
||||
resumeCommandUnavailable: "再開コマンドが利用できません",
|
||||
reloadingAgent: "エージェントを再読み込み中...",
|
||||
reloadedAgent: "エージェントを再読み込みしました",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"エージェントを再読み込みしましたが、プロバイダーの履歴がこのチャットと一致しないため同期しませんでした",
|
||||
failedToReloadAgent: "エージェントの再読み込みに失敗しました",
|
||||
failedToCloseAgent: "エージェントを閉じられませんでした",
|
||||
},
|
||||
@@ -1554,8 +1555,6 @@ export const ja: TranslationResources = {
|
||||
status: {
|
||||
checking: "アプリの更新を確認中...",
|
||||
installing: "アプリの更新をインストール中...",
|
||||
downloadingVersionProgress: "{{version}} をダウンロード中... {{percent}}%",
|
||||
downloadingProgress: "アプリの更新をダウンロード中... {{percent}}%",
|
||||
upToDate: "アプリは最新です。",
|
||||
upToDateWithLastChecked: "最新の状態です。最終確認: {{time}}。",
|
||||
pending: "更新の準備ができたらお知らせします。",
|
||||
@@ -1563,15 +1562,6 @@ export const ja: TranslationResources = {
|
||||
pendingWithVersion: "更新が見つかりました: {{version}}。ダウンロード中...",
|
||||
pendingWithVersionAndLastChecked:
|
||||
"更新が見つかりました: {{version}}。ダウンロード中... 最終確認: {{time}}。",
|
||||
pendingWithVersionProgress:
|
||||
"更新が見つかりました: {{version}}。ダウンロード中... {{percent}}%",
|
||||
pendingWithVersionProgressAndLastChecked:
|
||||
"更新が見つかりました: {{version}}。ダウンロード中... {{percent}}% 最終確認: {{time}}。",
|
||||
downloadAvailableWithVersion: "利用可能な更新: {{version}}",
|
||||
downloadAvailableWithVersionAndLastChecked:
|
||||
"利用可能な更新: {{version}}。最終確認: {{time}}。",
|
||||
downloadAvailable: "アプリの更新が利用可能です。",
|
||||
downloadAvailableWithLastChecked: "アプリの更新が利用可能です。最終確認: {{time}}。",
|
||||
availableWithVersion: "更新の準備ができました: {{version}}",
|
||||
availableWithVersionAndLastChecked:
|
||||
"更新の準備ができました: {{version}}。最終確認: {{time}}。",
|
||||
@@ -1583,21 +1573,14 @@ export const ja: TranslationResources = {
|
||||
},
|
||||
installError: "デスクトップアプリの更新をインストールできません。",
|
||||
callout: {
|
||||
downloadingTitle: "更新をダウンロード中",
|
||||
installingTitle: "更新をインストール中",
|
||||
failedTitle: "更新に失敗しました",
|
||||
availableTitle: "更新が利用可能",
|
||||
genericError: "問題が発生しました。",
|
||||
whatsNew: "新機能",
|
||||
downloadingAction: "ダウンロード中...",
|
||||
installingAction: "インストール中...",
|
||||
downloadAndRestart: "ダウンロード",
|
||||
installAndRestart: "インストールして再起動",
|
||||
downloadingVersionDescription: "{{version}} をダウンロード中... {{percent}}%",
|
||||
downloadingDescription: "更新をダウンロード中... {{percent}}%",
|
||||
installingDescription: "インストールして再起動中...",
|
||||
versionAvailable: "{{version}} をダウンロードできます。",
|
||||
newVersionAvailable: "新しいバージョンをダウンロードできます。",
|
||||
versionReady: "{{version}}のインストール準備ができました。",
|
||||
newVersionReady: "新しいバージョンのインストール準備ができました。",
|
||||
restartWarning:
|
||||
@@ -2646,28 +2629,9 @@ export const ja: TranslationResources = {
|
||||
stable: "安定版",
|
||||
beta: "ベータ",
|
||||
},
|
||||
autoUpdate: {
|
||||
label: "自動更新",
|
||||
options: {
|
||||
automatic: "自動",
|
||||
notify: "通知のみ",
|
||||
off: "オフ",
|
||||
},
|
||||
descriptions: {
|
||||
automatic: "バックグラウンドで更新を確認してダウンロードします",
|
||||
notify: "更新を確認しますが、選択したときだけダウンロードします",
|
||||
off: "自動で更新を確認しません。「確認」をクリックしたときだけ確認します",
|
||||
},
|
||||
},
|
||||
updates: {
|
||||
label: "アプリの更新",
|
||||
readyToInstall: "インストール準備完了: {{version}}",
|
||||
downloadTitle: "デスクトップの更新をダウンロード",
|
||||
downloadMessage: "このコンピューターにPaseoの更新をダウンロードしてインストールします",
|
||||
downloadConfirm: "ダウンロードしてインストール",
|
||||
download: "ダウンロード",
|
||||
downloadTo: "{{version}}をダウンロード",
|
||||
downloading: "ダウンロード中...",
|
||||
installTitle: "デスクトップの更新をインストール",
|
||||
installMessage: "このコンピューターのPaseoを更新します",
|
||||
installConfirm: "更新をインストール",
|
||||
@@ -2871,23 +2835,6 @@ export const ja: TranslationResources = {
|
||||
name: {
|
||||
label: "名前",
|
||||
},
|
||||
icon: {
|
||||
label: "アイコン",
|
||||
accessibilityLabel: "アイコン、{{value}}",
|
||||
auto: "自動",
|
||||
autoDetected: "自動 ({{icon}})",
|
||||
options: {
|
||||
server: "サーバー",
|
||||
laptop: "ノート PC",
|
||||
desktop: "デスクトップ",
|
||||
mini: "ミニ PC",
|
||||
workstation: "ワークステーション",
|
||||
cloud: "クラウド",
|
||||
container: "コンテナ",
|
||||
board: "シングルボード PC",
|
||||
terminal: "ターミナル",
|
||||
},
|
||||
},
|
||||
color: {
|
||||
label: "色",
|
||||
accessibilityLabel: "色、{{value}}",
|
||||
@@ -2924,14 +2871,6 @@ export const ja: TranslationResources = {
|
||||
local: "ローカル",
|
||||
remoteSsh: "リモート SSH",
|
||||
},
|
||||
connectionKinds: {
|
||||
local: "ローカル",
|
||||
relay: "リレー",
|
||||
tailscale: "Tailscale",
|
||||
ssh: "SSH",
|
||||
direct: "ダイレクト",
|
||||
routed: "経由",
|
||||
},
|
||||
connections: {
|
||||
title: "接続",
|
||||
removeTitle: "接続を削除",
|
||||
|
||||
@@ -346,7 +346,6 @@ export const ko: TranslationResources = {
|
||||
viewDiagram: "다이어그램 보기",
|
||||
},
|
||||
actions: {
|
||||
copyQuote: "인용문 복사",
|
||||
copyCode: "코드 복사",
|
||||
copyTurn: "턴 복사",
|
||||
copyMessage: "메시지 복사",
|
||||
@@ -741,6 +740,8 @@ export const ko: TranslationResources = {
|
||||
resumeCommandUnavailable: "재개 명령을 사용할 수 없습니다",
|
||||
reloadingAgent: "에이전트 다시 로드 중...",
|
||||
reloadedAgent: "에이전트를 다시 로드했습니다",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"에이전트를 다시 로드했지만 제공자 기록이 이 채팅과 일치하지 않아 동기화하지 않았습니다",
|
||||
failedToReloadAgent: "에이전트를 다시 로드하지 못했습니다",
|
||||
failedToCloseAgent: "에이전트를 닫지 못했습니다",
|
||||
},
|
||||
@@ -1545,8 +1546,6 @@ export const ko: TranslationResources = {
|
||||
status: {
|
||||
checking: "앱 업데이트 확인 중...",
|
||||
installing: "앱 업데이트 설치 중...",
|
||||
downloadingVersionProgress: "{{version}} 다운로드 중... {{percent}}%",
|
||||
downloadingProgress: "앱 업데이트 다운로드 중... {{percent}}%",
|
||||
upToDate: "앱이 최신 상태입니다.",
|
||||
upToDateWithLastChecked: "최신 상태입니다. 마지막 확인: {{time}}.",
|
||||
pending: "업데이트가 준비되면 알려드리겠습니다.",
|
||||
@@ -1555,15 +1554,6 @@ export const ko: TranslationResources = {
|
||||
pendingWithVersion: "업데이트 발견: {{version}}. 다운로드 중...",
|
||||
pendingWithVersionAndLastChecked:
|
||||
"업데이트 발견: {{version}}. 다운로드 중... {{time}}에서 마지막으로 확인했습니다.",
|
||||
pendingWithVersionProgress: "업데이트 발견: {{version}}. 다운로드 중... {{percent}}%",
|
||||
pendingWithVersionProgressAndLastChecked:
|
||||
"업데이트 발견: {{version}}. 다운로드 중... {{percent}}% {{time}}에서 마지막으로 확인했습니다.",
|
||||
downloadAvailableWithVersion: "사용 가능한 업데이트: {{version}}",
|
||||
downloadAvailableWithVersionAndLastChecked:
|
||||
"사용 가능한 업데이트: {{version}}. {{time}}에서 마지막으로 확인했습니다.",
|
||||
downloadAvailable: "사용 가능한 앱 업데이트가 있습니다.",
|
||||
downloadAvailableWithLastChecked:
|
||||
"사용 가능한 앱 업데이트가 있습니다. {{time}}에서 마지막으로 확인했습니다.",
|
||||
availableWithVersion: "업데이트 준비됨: {{version}}",
|
||||
availableWithVersionAndLastChecked:
|
||||
"업데이트 준비됨: {{version}}. {{time}}에서 마지막으로 확인했습니다.",
|
||||
@@ -1576,21 +1566,14 @@ export const ko: TranslationResources = {
|
||||
},
|
||||
installError: "데스크톱 앱 업데이트를 설치할 수 없습니다.",
|
||||
callout: {
|
||||
downloadingTitle: "업데이트 다운로드 중",
|
||||
installingTitle: "업데이트 설치 중",
|
||||
failedTitle: "업데이트 실패",
|
||||
availableTitle: "업데이트 사용 가능",
|
||||
genericError: "문제가 발생했습니다.",
|
||||
whatsNew: "새로운 기능",
|
||||
downloadingAction: "다운로드 중...",
|
||||
installingAction: "설치 중...",
|
||||
downloadAndRestart: "다운로드",
|
||||
installAndRestart: "설치 후 재시작",
|
||||
downloadingVersionDescription: "{{version}} 다운로드 중... {{percent}}%",
|
||||
downloadingDescription: "업데이트 다운로드 중... {{percent}}%",
|
||||
installingDescription: "설치 후 재시작 중...",
|
||||
versionAvailable: "{{version}} 버전을 다운로드할 수 있습니다.",
|
||||
newVersionAvailable: "새 버전을 다운로드할 수 있습니다.",
|
||||
versionReady: "{{version}} 설치가 준비되었습니다.",
|
||||
newVersionReady: "새 버전 설치가 준비되었습니다.",
|
||||
restartWarning: "앱을 업그레이드하면 실행 중인 에이전트가 중지되고 터미널 세션이 닫힙니다.",
|
||||
@@ -2636,28 +2619,9 @@ export const ko: TranslationResources = {
|
||||
stable: "안정",
|
||||
beta: "베타",
|
||||
},
|
||||
autoUpdate: {
|
||||
label: "자동 업데이트",
|
||||
options: {
|
||||
automatic: "자동",
|
||||
notify: "알림만",
|
||||
off: "끄기",
|
||||
},
|
||||
descriptions: {
|
||||
automatic: "백그라운드에서 업데이트를 확인하고 다운로드합니다",
|
||||
notify: "업데이트를 확인하지만 선택할 때만 다운로드합니다",
|
||||
off: "자동으로 확인하지 않습니다. 확인 버튼을 누를 때만 확인합니다",
|
||||
},
|
||||
},
|
||||
updates: {
|
||||
label: "앱 업데이트",
|
||||
readyToInstall: "설치 준비됨: {{version}}",
|
||||
downloadTitle: "데스크톱 업데이트 다운로드",
|
||||
downloadMessage: "이 컴퓨터에 Paseo 업데이트를 다운로드하고 설치합니다",
|
||||
downloadConfirm: "다운로드 및 설치",
|
||||
download: "다운로드",
|
||||
downloadTo: "{{version}} 다운로드",
|
||||
downloading: "다운로드 중...",
|
||||
installTitle: "데스크톱 업데이트 설치",
|
||||
installMessage: "이 컴퓨터의 Paseo를 업데이트합니다",
|
||||
installConfirm: "업데이트 설치",
|
||||
@@ -2857,23 +2821,6 @@ export const ko: TranslationResources = {
|
||||
name: {
|
||||
label: "이름",
|
||||
},
|
||||
icon: {
|
||||
label: "아이콘",
|
||||
accessibilityLabel: "아이콘, {{value}}",
|
||||
auto: "자동",
|
||||
autoDetected: "자동 ({{icon}})",
|
||||
options: {
|
||||
server: "서버",
|
||||
laptop: "노트북",
|
||||
desktop: "데스크톱",
|
||||
mini: "미니",
|
||||
workstation: "워크스테이션",
|
||||
cloud: "클라우드",
|
||||
container: "컨테이너",
|
||||
board: "싱글보드 PC",
|
||||
terminal: "터미널",
|
||||
},
|
||||
},
|
||||
color: {
|
||||
label: "색상",
|
||||
accessibilityLabel: "색상, {{value}}",
|
||||
@@ -2910,14 +2857,6 @@ export const ko: TranslationResources = {
|
||||
local: "로컬",
|
||||
remoteSsh: "원격 SSH",
|
||||
},
|
||||
connectionKinds: {
|
||||
local: "로컬",
|
||||
relay: "릴레이",
|
||||
tailscale: "Tailscale",
|
||||
ssh: "SSH",
|
||||
direct: "직접 연결",
|
||||
routed: "경유",
|
||||
},
|
||||
connections: {
|
||||
title: "연결",
|
||||
removeTitle: "연결 제거",
|
||||
|
||||
@@ -349,7 +349,6 @@ export const ptBR: TranslationResources = {
|
||||
viewDiagram: "Ver diagrama",
|
||||
},
|
||||
actions: {
|
||||
copyQuote: "Copiar citação",
|
||||
copyCode: "Copiar código",
|
||||
copyTurn: "Copiar turno",
|
||||
copyMessage: "Copiar mensagem",
|
||||
@@ -744,6 +743,8 @@ export const ptBR: TranslationResources = {
|
||||
resumeCommandUnavailable: "Comando de retomada indisponível",
|
||||
reloadingAgent: "Recarregando agente...",
|
||||
reloadedAgent: "Agente recarregado",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"Agente recarregado, mas o histórico do provedor não corresponde a este chat, então não foi sincronizado",
|
||||
failedToReloadAgent: "Falha ao recarregar agente",
|
||||
failedToCloseAgent: "Falha ao fechar agente",
|
||||
},
|
||||
@@ -1566,8 +1567,6 @@ export const ptBR: TranslationResources = {
|
||||
status: {
|
||||
checking: "Verificando atualizações do app...",
|
||||
installing: "Instalando atualização do app...",
|
||||
downloadingVersionProgress: "Baixando {{version}}... {{percent}}%",
|
||||
downloadingProgress: "Baixando atualização do app... {{percent}}%",
|
||||
upToDate: "O app está atualizado.",
|
||||
upToDateWithLastChecked: "Atualizado. Última verificação às {{time}}.",
|
||||
pending: "Avisaremos quando a atualização estiver pronta.",
|
||||
@@ -1576,15 +1575,6 @@ export const ptBR: TranslationResources = {
|
||||
pendingWithVersion: "Atualização encontrada: {{version}}. Baixando...",
|
||||
pendingWithVersionAndLastChecked:
|
||||
"Atualização encontrada: {{version}}. Baixando... Última verificação às {{time}}.",
|
||||
pendingWithVersionProgress: "Atualização encontrada: {{version}}. Baixando... {{percent}}%",
|
||||
pendingWithVersionProgressAndLastChecked:
|
||||
"Atualização encontrada: {{version}}. Baixando... {{percent}}% Última verificação às {{time}}.",
|
||||
downloadAvailableWithVersion: "Atualização disponível: {{version}}",
|
||||
downloadAvailableWithVersionAndLastChecked:
|
||||
"Atualização disponível: {{version}}. Última verificação às {{time}}.",
|
||||
downloadAvailable: "Há uma atualização do app disponível.",
|
||||
downloadAvailableWithLastChecked:
|
||||
"Há uma atualização do app disponível. Última verificação às {{time}}.",
|
||||
availableWithVersion: "Atualização pronta: {{version}}",
|
||||
availableWithVersionAndLastChecked:
|
||||
"Atualização pronta: {{version}}. Última verificação às {{time}}.",
|
||||
@@ -1597,21 +1587,14 @@ export const ptBR: TranslationResources = {
|
||||
},
|
||||
installError: "Não foi possível instalar a atualização do app desktop.",
|
||||
callout: {
|
||||
downloadingTitle: "Baixando atualização",
|
||||
installingTitle: "Instalando atualização",
|
||||
failedTitle: "Falha na atualização",
|
||||
availableTitle: "Atualização disponível",
|
||||
genericError: "Algo deu errado.",
|
||||
whatsNew: "Novidades",
|
||||
downloadingAction: "Baixando...",
|
||||
installingAction: "Instalando...",
|
||||
downloadAndRestart: "Baixar",
|
||||
installAndRestart: "Instalar e reiniciar",
|
||||
downloadingVersionDescription: "Baixando {{version}}... {{percent}}%",
|
||||
downloadingDescription: "Baixando atualização... {{percent}}%",
|
||||
installingDescription: "Instalando e reiniciando...",
|
||||
versionAvailable: "{{version}} está disponível para download.",
|
||||
newVersionAvailable: "Uma nova versão está disponível para download.",
|
||||
versionReady: "{{version}} está pronta para instalar.",
|
||||
newVersionReady: "Uma nova versão está pronta para instalar.",
|
||||
restartWarning:
|
||||
@@ -2661,28 +2644,9 @@ export const ptBR: TranslationResources = {
|
||||
stable: "Stable",
|
||||
beta: "Beta",
|
||||
},
|
||||
autoUpdate: {
|
||||
label: "Atualizações automáticas",
|
||||
options: {
|
||||
automatic: "Auto",
|
||||
notify: "Notificar",
|
||||
off: "Desativado",
|
||||
},
|
||||
descriptions: {
|
||||
automatic: "Verificar e baixar atualizações em segundo plano",
|
||||
notify: "Verificar atualizações, mas baixar apenas quando você escolher",
|
||||
off: "Nunca verificar automaticamente. Verificar apenas ao clicar em Verificar",
|
||||
},
|
||||
},
|
||||
updates: {
|
||||
label: "Atualizações do app",
|
||||
readyToInstall: "Pronta para instalar: {{version}}",
|
||||
downloadTitle: "Baixar atualização desktop",
|
||||
downloadMessage: "Isso baixa e instala a atualização do Paseo neste computador",
|
||||
downloadConfirm: "Baixar e instalar",
|
||||
download: "Baixar",
|
||||
downloadTo: "Baixar {{version}}",
|
||||
downloading: "Baixando...",
|
||||
installTitle: "Instalar atualização desktop",
|
||||
installMessage: "Isso atualiza o Paseo neste computador",
|
||||
installConfirm: "Instalar atualização",
|
||||
@@ -2884,23 +2848,6 @@ export const ptBR: TranslationResources = {
|
||||
name: {
|
||||
label: "Nome",
|
||||
},
|
||||
icon: {
|
||||
label: "Ícone",
|
||||
accessibilityLabel: "Ícone, {{value}}",
|
||||
auto: "Automático",
|
||||
autoDetected: "Automático ({{icon}})",
|
||||
options: {
|
||||
server: "Servidor",
|
||||
laptop: "Notebook",
|
||||
desktop: "Desktop",
|
||||
mini: "Mini",
|
||||
workstation: "Estação de trabalho",
|
||||
cloud: "Nuvem",
|
||||
container: "Contêiner",
|
||||
board: "PC de placa única",
|
||||
terminal: "Terminal",
|
||||
},
|
||||
},
|
||||
color: {
|
||||
label: "Cor",
|
||||
accessibilityLabel: "Cor, {{value}}",
|
||||
@@ -2937,14 +2884,6 @@ export const ptBR: TranslationResources = {
|
||||
local: "Local",
|
||||
remoteSsh: "SSH remoto",
|
||||
},
|
||||
connectionKinds: {
|
||||
local: "Local",
|
||||
relay: "Relay",
|
||||
tailscale: "Tailscale",
|
||||
ssh: "SSH",
|
||||
direct: "Direto",
|
||||
routed: "Via",
|
||||
},
|
||||
connections: {
|
||||
title: "Conexões",
|
||||
removeTitle: "Remover conexão",
|
||||
|
||||
@@ -349,7 +349,6 @@ export const ru: TranslationResources = {
|
||||
viewDiagram: "Показать диаграмму",
|
||||
},
|
||||
actions: {
|
||||
copyQuote: "Копировать цитату",
|
||||
copyCode: "Скопировать код",
|
||||
copyTurn: "Скопировать ответ",
|
||||
copyMessage: "Копировать сообщение",
|
||||
@@ -747,6 +746,8 @@ export const ru: TranslationResources = {
|
||||
resumeCommandUnavailable: "Команда возобновления недоступна",
|
||||
reloadingAgent: "Перезагрузка агента...",
|
||||
reloadedAgent: "Агент перезагружен",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"Агент перезагружен, но история провайдера не совпадает с этим чатом, поэтому она не синхронизирована",
|
||||
failedToReloadAgent: "Не удалось перезагрузить агента",
|
||||
failedToCloseAgent: "Не удалось закрыть агента",
|
||||
},
|
||||
@@ -1560,8 +1561,6 @@ export const ru: TranslationResources = {
|
||||
status: {
|
||||
checking: "Проверка обновлений приложения...",
|
||||
installing: "Установка обновления приложения...",
|
||||
downloadingVersionProgress: "Загрузка {{version}}... {{percent}}%",
|
||||
downloadingProgress: "Загрузка обновления приложения... {{percent}}%",
|
||||
upToDate: "Установлена последняя версия приложения.",
|
||||
upToDateWithLastChecked:
|
||||
"Установлена последняя версия приложения. Последняя проверка: {{time}}.",
|
||||
@@ -1571,15 +1570,6 @@ export const ru: TranslationResources = {
|
||||
pendingWithVersion: "Найдено обновление: {{version}}. Загрузка...",
|
||||
pendingWithVersionAndLastChecked:
|
||||
"Найдено обновление: {{version}}. Загрузка... Последняя проверка в {{time}}.",
|
||||
pendingWithVersionProgress: "Найдено обновление: {{version}}. Загрузка... {{percent}}%",
|
||||
pendingWithVersionProgressAndLastChecked:
|
||||
"Найдено обновление: {{version}}. Загрузка... {{percent}}% Последняя проверка в {{time}}.",
|
||||
downloadAvailableWithVersion: "Доступно обновление: {{version}}",
|
||||
downloadAvailableWithVersionAndLastChecked:
|
||||
"Доступно обновление: {{version}}. Последняя проверка: {{time}}.",
|
||||
downloadAvailable: "Доступно обновление приложения.",
|
||||
downloadAvailableWithLastChecked:
|
||||
"Доступно обновление приложения. Последняя проверка: {{time}}.",
|
||||
availableWithVersion: "Обновление готово: {{version}}",
|
||||
availableWithVersionAndLastChecked:
|
||||
"Обновление готово: {{version}}. Последняя проверка: {{time}}.",
|
||||
@@ -1592,21 +1582,14 @@ export const ru: TranslationResources = {
|
||||
},
|
||||
installError: "Не удалось установить обновление настольного приложения.",
|
||||
callout: {
|
||||
downloadingTitle: "Загрузка обновления",
|
||||
installingTitle: "Установка обновления",
|
||||
failedTitle: "Обновление не выполнено",
|
||||
availableTitle: "Доступно обновление",
|
||||
genericError: "Что-то пошло не так.",
|
||||
whatsNew: "Что нового",
|
||||
downloadingAction: "Загрузка...",
|
||||
installingAction: "Установка...",
|
||||
downloadAndRestart: "Скачать",
|
||||
installAndRestart: "Установить и перезапустить",
|
||||
downloadingVersionDescription: "Загрузка {{version}}... {{percent}}%",
|
||||
downloadingDescription: "Загрузка обновления... {{percent}}%",
|
||||
installingDescription: "Установка и перезапуск...",
|
||||
versionAvailable: "Версия {{version}} доступна для загрузки.",
|
||||
newVersionAvailable: "Новая версия доступна для загрузки.",
|
||||
versionReady: "Версия {{version}} готова к установке.",
|
||||
newVersionReady: "Новая версия готова к установке.",
|
||||
restartWarning:
|
||||
@@ -2668,28 +2651,9 @@ export const ru: TranslationResources = {
|
||||
stable: "Стабильный",
|
||||
beta: "Бета",
|
||||
},
|
||||
autoUpdate: {
|
||||
label: "Автообновления",
|
||||
options: {
|
||||
automatic: "Авто",
|
||||
notify: "Уведомлять",
|
||||
off: "Выкл.",
|
||||
},
|
||||
descriptions: {
|
||||
automatic: "Проверять и загружать обновления в фоновом режиме",
|
||||
notify: "Проверять обновления, но загружать только по вашему выбору",
|
||||
off: "Не проверять автоматически. Проверять только по нажатию кнопки Проверить",
|
||||
},
|
||||
},
|
||||
updates: {
|
||||
label: "Обновления приложения",
|
||||
readyToInstall: "Версия {{version}} готова к установке",
|
||||
downloadTitle: "Загрузить обновление настольного приложения",
|
||||
downloadMessage: "Это загрузит и установит обновление Paseo на этом компьютере.",
|
||||
downloadConfirm: "Загрузить и установить",
|
||||
download: "Загрузить",
|
||||
downloadTo: "Загрузить {{version}}",
|
||||
downloading: "Загрузка...",
|
||||
installTitle: "Установить обновление настольного приложения",
|
||||
installMessage: "Это обновит Paseo на этом компьютере.",
|
||||
installConfirm: "Установить обновление",
|
||||
@@ -2892,23 +2856,6 @@ export const ru: TranslationResources = {
|
||||
name: {
|
||||
label: "Имя",
|
||||
},
|
||||
icon: {
|
||||
label: "Значок",
|
||||
accessibilityLabel: "Значок, {{value}}",
|
||||
auto: "Авто",
|
||||
autoDetected: "Авто ({{icon}})",
|
||||
options: {
|
||||
server: "Сервер",
|
||||
laptop: "Ноутбук",
|
||||
desktop: "Компьютер",
|
||||
mini: "Мини-ПК",
|
||||
workstation: "Рабочая станция",
|
||||
cloud: "Облако",
|
||||
container: "Контейнер",
|
||||
board: "Одноплатный ПК",
|
||||
terminal: "Терминал",
|
||||
},
|
||||
},
|
||||
color: {
|
||||
label: "Цвет",
|
||||
accessibilityLabel: "Цвет, {{value}}",
|
||||
@@ -2945,14 +2892,6 @@ export const ru: TranslationResources = {
|
||||
local: "Локальный",
|
||||
remoteSsh: "Удалённый SSH",
|
||||
},
|
||||
connectionKinds: {
|
||||
local: "Локальный",
|
||||
relay: "Ретранслятор",
|
||||
tailscale: "Tailscale",
|
||||
ssh: "SSH",
|
||||
direct: "Прямой",
|
||||
routed: "Через",
|
||||
},
|
||||
connections: {
|
||||
title: "Подключения",
|
||||
removeTitle: "Удалить подключение",
|
||||
|
||||
@@ -345,7 +345,6 @@ export const zhCN: TranslationResources = {
|
||||
viewDiagram: "查看图表",
|
||||
},
|
||||
actions: {
|
||||
copyQuote: "复制引用",
|
||||
copyCode: "复制代码",
|
||||
copyTurn: "复制回合",
|
||||
copyMessage: "复制消息",
|
||||
@@ -739,6 +738,8 @@ export const zhCN: TranslationResources = {
|
||||
resumeCommandUnavailable: "恢复命令不可用",
|
||||
reloadingAgent: "正在重新加载 Agent...",
|
||||
reloadedAgent: "已重新加载 Agent",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"已重新加载 Agent,但提供方的历史记录与此对话不一致,因此未同步",
|
||||
failedToReloadAgent: "重新加载 Agent 失败",
|
||||
failedToCloseAgent: "关闭 Agent 失败",
|
||||
},
|
||||
@@ -1526,8 +1527,6 @@ export const zhCN: TranslationResources = {
|
||||
status: {
|
||||
checking: "正在检查 app 更新...",
|
||||
installing: "正在安装 app 更新...",
|
||||
downloadingVersionProgress: "正在下载 {{version}}... {{percent}}%",
|
||||
downloadingProgress: "正在下载 app 更新... {{percent}}%",
|
||||
upToDate: "App 已是最新版本。",
|
||||
upToDateWithLastChecked: "已是最新版本。上次检查时间:{{time}}。",
|
||||
pending: "更新准备好后会通知你。",
|
||||
@@ -1535,14 +1534,6 @@ export const zhCN: TranslationResources = {
|
||||
pendingWithVersion: "发现更新:{{version}}。正在下载...",
|
||||
pendingWithVersionAndLastChecked:
|
||||
"发现更新:{{version}}。正在下载... 上次检查时间:{{time}}。",
|
||||
pendingWithVersionProgress: "发现更新:{{version}}。正在下载... {{percent}}%",
|
||||
pendingWithVersionProgressAndLastChecked:
|
||||
"发现更新:{{version}}。正在下载... {{percent}}% 上次检查时间:{{time}}。",
|
||||
downloadAvailableWithVersion: "有可用更新:{{version}}",
|
||||
downloadAvailableWithVersionAndLastChecked:
|
||||
"有可用更新:{{version}}。上次检查时间:{{time}}。",
|
||||
downloadAvailable: "有 app 更新可用。",
|
||||
downloadAvailableWithLastChecked: "有 app 更新可用。上次检查时间:{{time}}。",
|
||||
availableWithVersion: "更新已就绪:{{version}}",
|
||||
availableWithVersionAndLastChecked: "更新已就绪:{{version}}。上次检查时间:{{time}}。",
|
||||
available: "有 app 更新可安装。",
|
||||
@@ -1553,21 +1544,14 @@ export const zhCN: TranslationResources = {
|
||||
},
|
||||
installError: "无法安装 desktop app 更新。",
|
||||
callout: {
|
||||
downloadingTitle: "正在下载更新",
|
||||
installingTitle: "正在安装更新",
|
||||
failedTitle: "更新失败",
|
||||
availableTitle: "有可用更新",
|
||||
genericError: "出了点问题。",
|
||||
whatsNew: "更新内容",
|
||||
downloadingAction: "正在下载...",
|
||||
installingAction: "正在安装...",
|
||||
downloadAndRestart: "下载",
|
||||
installAndRestart: "安装并重启",
|
||||
downloadingVersionDescription: "正在下载 {{version}}... {{percent}}%",
|
||||
downloadingDescription: "正在下载更新... {{percent}}%",
|
||||
installingDescription: "正在安装并重启...",
|
||||
versionAvailable: "{{version}} 可供下载。",
|
||||
newVersionAvailable: "有新版本可供下载。",
|
||||
versionReady: "{{version}} 已准备好安装。",
|
||||
newVersionReady: "新版本已准备好安装。",
|
||||
restartWarning: "升级 app 会停止正在运行的 agents,并关闭 terminal 会话。",
|
||||
@@ -2594,28 +2578,9 @@ export const zhCN: TranslationResources = {
|
||||
stable: "Stable",
|
||||
beta: "Beta",
|
||||
},
|
||||
autoUpdate: {
|
||||
label: "自动更新",
|
||||
options: {
|
||||
automatic: "自动",
|
||||
notify: "仅通知",
|
||||
off: "关闭",
|
||||
},
|
||||
descriptions: {
|
||||
automatic: "在后台检查并下载更新",
|
||||
notify: "检查更新,但仅在你选择时才下载",
|
||||
off: "从不自动检查,仅在点击检查时检查更新",
|
||||
},
|
||||
},
|
||||
updates: {
|
||||
label: "应用更新",
|
||||
readyToInstall: "可安装:{{version}}",
|
||||
downloadTitle: "下载桌面版更新",
|
||||
downloadMessage: "这会在此电脑上下载并安装 Paseo 更新",
|
||||
downloadConfirm: "下载并安装",
|
||||
download: "下载",
|
||||
downloadTo: "下载 {{version}}",
|
||||
downloading: "正在下载...",
|
||||
installTitle: "安装桌面版更新",
|
||||
installMessage: "这会更新此电脑上的 Paseo",
|
||||
installConfirm: "安装更新",
|
||||
@@ -2812,23 +2777,6 @@ export const zhCN: TranslationResources = {
|
||||
name: {
|
||||
label: "名称",
|
||||
},
|
||||
icon: {
|
||||
label: "图标",
|
||||
accessibilityLabel: "图标,{{value}}",
|
||||
auto: "自动",
|
||||
autoDetected: "自动 ({{icon}})",
|
||||
options: {
|
||||
server: "服务器",
|
||||
laptop: "笔记本电脑",
|
||||
desktop: "台式机",
|
||||
mini: "迷你主机",
|
||||
workstation: "工作站",
|
||||
cloud: "云端",
|
||||
container: "容器",
|
||||
board: "单板机",
|
||||
terminal: "终端",
|
||||
},
|
||||
},
|
||||
color: {
|
||||
label: "颜色",
|
||||
accessibilityLabel: "颜色,{{value}}",
|
||||
@@ -2865,14 +2813,6 @@ export const zhCN: TranslationResources = {
|
||||
local: "本地",
|
||||
remoteSsh: "远程 SSH",
|
||||
},
|
||||
connectionKinds: {
|
||||
local: "本地",
|
||||
relay: "中继",
|
||||
tailscale: "Tailscale",
|
||||
ssh: "SSH",
|
||||
direct: "直连",
|
||||
routed: "经由",
|
||||
},
|
||||
connections: {
|
||||
title: "连接",
|
||||
removeTitle: "移除连接",
|
||||
|
||||
@@ -91,7 +91,7 @@ describe("AgentDirectoryReplica", () => {
|
||||
id: "reply",
|
||||
text: "server history",
|
||||
timestamp: new Date(),
|
||||
timelineCursor: { epoch: "e", seq: 1 },
|
||||
timelineCursor: { epoch: "e", seq: 1, anchorSeq: 1 },
|
||||
},
|
||||
],
|
||||
head: [],
|
||||
|
||||
@@ -1114,106 +1114,6 @@ describe("HostRuntimeController", () => {
|
||||
expect(activeClient.latencyMeasurements()).toEqual([]);
|
||||
});
|
||||
|
||||
it("measures active latency on demand when an online host has no sample yet", async () => {
|
||||
useHostRuntimeClock();
|
||||
const initialClient = new FakeDaemonClient();
|
||||
initialClient.setConnectionState({ status: "connected" });
|
||||
initialClient.ping = async () => ({ rttMs: 14 });
|
||||
const controller = new HostRuntimeController({
|
||||
host: makeHost({
|
||||
connections: [{ id: "direct:lan:6767", type: "directTcp", endpoint: "lan:6767" }],
|
||||
preferredConnectionId: "direct:lan:6767",
|
||||
}),
|
||||
deps: makeDeps({ "direct:lan:6767": 14 }, []),
|
||||
});
|
||||
|
||||
await controller.start({
|
||||
autoProbe: false,
|
||||
initialConnection: {
|
||||
connectionId: "direct:lan:6767",
|
||||
existingClient: initialClient as unknown as DaemonClient,
|
||||
},
|
||||
});
|
||||
expect(controller.getSnapshot().probeByConnectionId.get("direct:lan:6767")).toEqual({
|
||||
status: "pending",
|
||||
latencyMs: null,
|
||||
});
|
||||
|
||||
await controller.refreshActiveLatency();
|
||||
|
||||
expect(controller.getSnapshot().probeByConnectionId.get("direct:lan:6767")).toEqual({
|
||||
status: "available",
|
||||
latencyMs: 14,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps an on-demand active latency sample when a slower probe on another connection finishes", async () => {
|
||||
useHostRuntimeClock();
|
||||
const initialClient = new FakeDaemonClient();
|
||||
initialClient.setConnectionState({ status: "connected" });
|
||||
initialClient.ping = async () => ({ rttMs: 14 });
|
||||
const relayProbeStarted = createDeferred<void>();
|
||||
const slowRelayProbe = createDeferred<{
|
||||
client: DaemonClient;
|
||||
serverId: string;
|
||||
hostname: string | null;
|
||||
}>();
|
||||
const relayClient = new FakeDaemonClient();
|
||||
relayClient.setConnectionState({ status: "connected" });
|
||||
relayClient.ping = async () => ({ rttMs: 90 });
|
||||
|
||||
const controller = new HostRuntimeController({
|
||||
host: makeHost(),
|
||||
deps: {
|
||||
...makeDeps({}, []),
|
||||
connectToDaemon: async ({ host, connection }) => {
|
||||
if (connection.id === "relay:relay.paseo.sh:443") {
|
||||
relayProbeStarted.resolve();
|
||||
return slowRelayProbe.promise;
|
||||
}
|
||||
return {
|
||||
client: initialClient as unknown as DaemonClient,
|
||||
serverId: host.serverId,
|
||||
hostname: null,
|
||||
};
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Startup runs the first probe cycle immediately; wait until the slower relay probe is in
|
||||
// flight, then measure active latency on demand before the relay probe resolves.
|
||||
const startPromise = controller.start({
|
||||
autoProbe: false,
|
||||
initialConnection: {
|
||||
connectionId: "direct:lan:6767",
|
||||
existingClient: initialClient as unknown as DaemonClient,
|
||||
},
|
||||
});
|
||||
await relayProbeStarted.promise;
|
||||
|
||||
await controller.refreshActiveLatency();
|
||||
expect(controller.getSnapshot().probeByConnectionId.get("direct:lan:6767")).toEqual({
|
||||
status: "available",
|
||||
latencyMs: 14,
|
||||
});
|
||||
|
||||
slowRelayProbe.resolve({
|
||||
client: relayClient as unknown as DaemonClient,
|
||||
serverId: "srv_test",
|
||||
hostname: null,
|
||||
});
|
||||
await startPromise;
|
||||
|
||||
expect(controller.getSnapshot().probeByConnectionId.get("direct:lan:6767")).toEqual({
|
||||
status: "available",
|
||||
latencyMs: 14,
|
||||
});
|
||||
expect(controller.getSnapshot().probeByConnectionId.get("relay:relay.paseo.sh:443")).toEqual({
|
||||
status: "available",
|
||||
latencyMs: 90,
|
||||
});
|
||||
});
|
||||
|
||||
it.each([12, null])(
|
||||
"falls back to relay when the direct client disconnects with heartbeat RTT %s",
|
||||
async (heartbeatRtt) => {
|
||||
@@ -3466,11 +3366,7 @@ describe("HostRuntimeStore", () => {
|
||||
store.boot();
|
||||
await registryLoaded;
|
||||
|
||||
expect(store.getHosts()[0]?.appearance).toEqual({
|
||||
color: "none",
|
||||
badgeDisplay: null,
|
||||
});
|
||||
expect("icon" in (store.getHosts()[0]?.appearance ?? {})).toBe(false);
|
||||
expect(store.getHosts()[0]?.appearance).toEqual({ color: "none", badgeDisplay: null });
|
||||
|
||||
store.syncHosts([]);
|
||||
});
|
||||
@@ -3495,7 +3391,6 @@ describe("HostRuntimeStore", () => {
|
||||
|
||||
const updated = store.getHosts()[0];
|
||||
expect(updated?.appearance).toEqual({ color: "teal", badgeDisplay: null });
|
||||
expect("icon" in (updated?.appearance ?? {})).toBe(false);
|
||||
expect(updated?.updatedAt).not.toBe(host.updatedAt);
|
||||
|
||||
const persisted = await storage.getItem("@paseo:daemon-registry");
|
||||
@@ -3507,60 +3402,10 @@ describe("HostRuntimeStore", () => {
|
||||
store.syncHosts([]);
|
||||
});
|
||||
|
||||
it("records a chosen host icon and resets to auto without disturbing color or badge display", async () => {
|
||||
const host = makeHost({
|
||||
serverId: "srv_appearance",
|
||||
appearance: { color: "violet", badgeDisplay: "icon" },
|
||||
});
|
||||
const storage = createMemoryHostRuntimeStorage();
|
||||
await storage.setItem("@paseo:daemon-registry", JSON.stringify([host]));
|
||||
await storage.setItem("@paseo:e2e", "1");
|
||||
const store = createAppearanceStore(storage);
|
||||
|
||||
const registryLoaded = onceHostListMatches(store, () => store.isHostRegistryLoaded());
|
||||
store.boot();
|
||||
await registryLoaded;
|
||||
|
||||
const hostListChanged = onceHostListMatches(
|
||||
store,
|
||||
() => store.getHosts()[0]?.appearance.icon === "laptop",
|
||||
);
|
||||
await store.setHostIcon("srv_appearance", "laptop");
|
||||
await hostListChanged;
|
||||
|
||||
expect(store.getHosts()[0]?.appearance).toEqual({
|
||||
color: "violet",
|
||||
icon: "laptop",
|
||||
badgeDisplay: "icon",
|
||||
});
|
||||
|
||||
const persisted = await storage.getItem("@paseo:daemon-registry");
|
||||
expect(JSON.parse(persisted ?? "[]")[0].appearance).toEqual({
|
||||
color: "violet",
|
||||
icon: "laptop",
|
||||
badgeDisplay: "icon",
|
||||
});
|
||||
|
||||
const resetToAuto = onceHostListMatches(
|
||||
store,
|
||||
() => store.getHosts()[0]?.appearance.icon === undefined,
|
||||
);
|
||||
await store.setHostIcon("srv_appearance", null);
|
||||
await resetToAuto;
|
||||
|
||||
expect(store.getHosts()[0]?.appearance).toEqual({
|
||||
color: "violet",
|
||||
badgeDisplay: "icon",
|
||||
});
|
||||
expect("icon" in (store.getHosts()[0]?.appearance ?? {})).toBe(false);
|
||||
|
||||
store.syncHosts([]);
|
||||
});
|
||||
|
||||
it("records a chosen badge display without disturbing the color", async () => {
|
||||
const host = makeHost({
|
||||
serverId: "srv_appearance",
|
||||
appearance: { color: "amber", icon: "server", badgeDisplay: null },
|
||||
appearance: { color: "amber", badgeDisplay: null },
|
||||
});
|
||||
const storage = createMemoryHostRuntimeStorage();
|
||||
await storage.setItem("@paseo:daemon-registry", JSON.stringify([host]));
|
||||
@@ -3578,16 +3423,11 @@ describe("HostRuntimeStore", () => {
|
||||
await store.setHostBadgeDisplay("srv_appearance", "icon");
|
||||
await hostListChanged;
|
||||
|
||||
expect(store.getHosts()[0]?.appearance).toEqual({
|
||||
color: "amber",
|
||||
icon: "server",
|
||||
badgeDisplay: "icon",
|
||||
});
|
||||
expect(store.getHosts()[0]?.appearance).toEqual({ color: "amber", badgeDisplay: "icon" });
|
||||
|
||||
const persisted = await storage.getItem("@paseo:daemon-registry");
|
||||
expect(JSON.parse(persisted ?? "[]")[0].appearance).toEqual({
|
||||
color: "amber",
|
||||
icon: "server",
|
||||
badgeDisplay: "icon",
|
||||
});
|
||||
|
||||
@@ -3636,25 +3476,16 @@ describe("HostRuntimeStore", () => {
|
||||
};
|
||||
|
||||
const color = store.setHostColor("srv_appearance", "teal");
|
||||
const icon = store.setHostIcon("srv_appearance", "mini");
|
||||
const display = store.setHostBadgeDisplay("srv_appearance", "icon");
|
||||
await Promise.resolve();
|
||||
expect(writeCount).toBe(1);
|
||||
|
||||
firstWrite.resolve();
|
||||
await Promise.all([color, icon, display]);
|
||||
await Promise.all([color, display]);
|
||||
|
||||
expect(store.getHosts()[0]?.appearance).toEqual({
|
||||
color: "teal",
|
||||
icon: "mini",
|
||||
badgeDisplay: "icon",
|
||||
});
|
||||
expect(store.getHosts()[0]?.appearance).toEqual({ color: "teal", badgeDisplay: "icon" });
|
||||
const persistedHosts = JSON.parse((await storage.getItem("@paseo:daemon-registry")) ?? "[]");
|
||||
expect(persistedHosts[0]?.appearance).toEqual({
|
||||
color: "teal",
|
||||
icon: "mini",
|
||||
badgeDisplay: "icon",
|
||||
});
|
||||
expect(persistedHosts[0]?.appearance).toEqual({ color: "teal", badgeDisplay: "icon" });
|
||||
store.syncHosts([]);
|
||||
});
|
||||
|
||||
|
||||
@@ -28,12 +28,7 @@ import {
|
||||
type HostProfile,
|
||||
type UnreadableHostEntries,
|
||||
} from "@/types/host-connection";
|
||||
import {
|
||||
defaultHostAppearance,
|
||||
type HostBadgeDisplay,
|
||||
type HostColor,
|
||||
type HostIcon,
|
||||
} from "@/hosts/appearance";
|
||||
import { defaultHostAppearance, type HostBadgeDisplay, type HostColor } from "@/hosts/appearance";
|
||||
import {
|
||||
buildDaemonWebSocketUrl,
|
||||
buildRelayWebSocketUrl,
|
||||
@@ -255,6 +250,7 @@ const PROBE_INACTIVE_WHILE_ONLINE_MAX_MS = 30 * 60_000;
|
||||
const ACTIVE_RTT_WINDOW_MS = 60_000;
|
||||
const ADAPTIVE_SWITCH_THRESHOLD_MS = 40;
|
||||
const ADAPTIVE_SWITCH_MIN_IMPROVEMENT_RATIO = 0.35;
|
||||
const MAX_STALE_TIMELINE_PAGE_ATTEMPTS = 3;
|
||||
const ADAPTIVE_SWITCH_CONSECUTIVE_PROBES = 3;
|
||||
const CONFIGURED_OVERRIDE_BOOTSTRAP_RETRY_MS = 1_000;
|
||||
|
||||
@@ -950,56 +946,6 @@ export class HostRuntimeController {
|
||||
await this.switchToConnection(input);
|
||||
}
|
||||
|
||||
/**
|
||||
* Measures the active connection's round-trip time when the host is online and no sample has
|
||||
* landed yet (for example right after connecting, before the first heartbeat interval fires).
|
||||
*/
|
||||
async refreshActiveLatency(): Promise<void> {
|
||||
const activeConnectionId = this.snapshot.activeConnectionId;
|
||||
const activeClient = this.snapshot.client;
|
||||
if (
|
||||
this.snapshot.connectionStatus !== "online" ||
|
||||
!activeConnectionId ||
|
||||
!activeClient ||
|
||||
activeClient.getConnectionState().status !== "connected"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const existing = this.snapshot.probeByConnectionId.get(activeConnectionId);
|
||||
if (existing?.status === "available") {
|
||||
return;
|
||||
}
|
||||
const existingRtt = activeClient.getLastLivenessRttMs();
|
||||
if (existingRtt !== null) {
|
||||
this.recordActiveLatencySample(activeConnectionId, existingRtt);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const rttMs = await activeClient.measureLatency({ timeoutMs: 3_000 });
|
||||
if (
|
||||
this.snapshot.activeConnectionId !== activeConnectionId ||
|
||||
this.snapshot.client !== activeClient ||
|
||||
this.snapshot.connectionStatus !== "online"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
this.recordActiveLatencySample(activeConnectionId, rttMs);
|
||||
} catch {
|
||||
// A latency probe never drives teardown; the heartbeat owns liveness.
|
||||
}
|
||||
}
|
||||
|
||||
private setConnectionProbe(connectionId: string, probe: ConnectionProbeState): void {
|
||||
const probeByConnectionId = new Map(this.snapshot.probeByConnectionId);
|
||||
probeByConnectionId.set(connectionId, probe);
|
||||
this.updateSnapshot({ probeByConnectionId });
|
||||
}
|
||||
|
||||
private recordActiveLatencySample(connectionId: string, rttMs: number): void {
|
||||
this.recordActiveRttSample(rttMs, performance.now());
|
||||
this.setConnectionProbe(connectionId, { status: "available", latencyMs: rttMs });
|
||||
}
|
||||
|
||||
async runProbeCycleNow(): Promise<void> {
|
||||
if (this.probeCycleInFlight) {
|
||||
return this.probeCycleInFlight;
|
||||
@@ -1056,32 +1002,30 @@ export class HostRuntimeController {
|
||||
return;
|
||||
}
|
||||
|
||||
const initialProbes = new Map(this.snapshot.probeByConnectionId);
|
||||
const probeByConnectionId = new Map(this.snapshot.probeByConnectionId);
|
||||
for (const connection of connectionsToProbe) {
|
||||
this.connectionLastProbedAt.set(connection.id, performance.now());
|
||||
const existingProbe = initialProbes.get(connection.id);
|
||||
const existingProbe = probeByConnectionId.get(connection.id);
|
||||
const shouldPreserveActiveLatency =
|
||||
isOnline && connection.id === activeConnectionId && existingProbe?.status === "available";
|
||||
if (!shouldPreserveActiveLatency) {
|
||||
initialProbes.set(connection.id, {
|
||||
probeByConnectionId.set(connection.id, {
|
||||
status: "pending",
|
||||
latencyMs: null,
|
||||
});
|
||||
}
|
||||
}
|
||||
this.updateSnapshot({ probeByConnectionId: initialProbes });
|
||||
this.updateSnapshot({ probeByConnectionId: new Map(probeByConnectionId) });
|
||||
|
||||
let remaining = connectionsToProbe.length;
|
||||
let probeAuthFailure: "password_required" | "incorrect_password" | null = null;
|
||||
let activationLock: Promise<void> | null = null;
|
||||
|
||||
// Merge each connection result into the live snapshot map so a slow probe on another
|
||||
// connection cannot overwrite a fresher sample (e.g. from refreshActiveLatency) on the active one.
|
||||
const publishConnectionProbe = (connectionId: string, probe: ConnectionProbeState): void => {
|
||||
const publishProbeState = (): void => {
|
||||
if (!this.isCurrentProbeRequest(requestVersion)) {
|
||||
return;
|
||||
}
|
||||
this.setConnectionProbe(connectionId, probe);
|
||||
this.updateSnapshot({ probeByConnectionId: new Map(probeByConnectionId) });
|
||||
};
|
||||
|
||||
const maybeActivateFirstAvailable = async (
|
||||
@@ -1110,7 +1054,6 @@ export class HostRuntimeController {
|
||||
return;
|
||||
}
|
||||
|
||||
const probeByConnectionId = new Map(this.snapshot.probeByConnectionId);
|
||||
const currentActiveConnectionId = this.snapshot.activeConnectionId;
|
||||
if (currentActiveConnectionId) {
|
||||
this.reconcileActiveProbeWithClient(currentActiveConnectionId, probeByConnectionId);
|
||||
@@ -1266,10 +1209,11 @@ export class HostRuntimeController {
|
||||
|
||||
if (activeClient) {
|
||||
if (activeClient.getConnectionState().status !== "connected") {
|
||||
publishConnectionProbe(connection.id, {
|
||||
probeByConnectionId.set(connection.id, {
|
||||
status: "unavailable",
|
||||
latencyMs: null,
|
||||
});
|
||||
publishProbeState();
|
||||
return;
|
||||
}
|
||||
const rttMs = activeClient.getLastLivenessRttMs();
|
||||
@@ -1278,10 +1222,11 @@ export class HostRuntimeController {
|
||||
}
|
||||
if (rttMs !== null) {
|
||||
this.recordActiveRttSample(rttMs, performance.now());
|
||||
publishConnectionProbe(connection.id, {
|
||||
probeByConnectionId.set(connection.id, {
|
||||
status: "available",
|
||||
latencyMs: rttMs,
|
||||
});
|
||||
publishProbeState();
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -1291,10 +1236,11 @@ export class HostRuntimeController {
|
||||
return;
|
||||
}
|
||||
|
||||
publishConnectionProbe(connection.id, {
|
||||
probeByConnectionId.set(connection.id, {
|
||||
status: "available",
|
||||
latencyMs: rttMs,
|
||||
});
|
||||
publishProbeState();
|
||||
} catch (error) {
|
||||
if (this.isCurrentProbeRequest(requestVersion)) {
|
||||
const authFailure = getConnectionAuthFailureReason(error);
|
||||
@@ -1302,10 +1248,11 @@ export class HostRuntimeController {
|
||||
this.authRejectedConnectionIds.add(connection.id);
|
||||
probeAuthFailure = authFailure;
|
||||
}
|
||||
publishConnectionProbe(connection.id, {
|
||||
probeByConnectionId.set(connection.id, {
|
||||
status: "unavailable",
|
||||
latencyMs: null,
|
||||
});
|
||||
publishProbeState();
|
||||
}
|
||||
} finally {
|
||||
if (connectedClient && shouldCloseClient) {
|
||||
@@ -2490,16 +2437,6 @@ export class HostRuntimeStore {
|
||||
}));
|
||||
}
|
||||
|
||||
async setHostIcon(serverId: string, icon: HostIcon | null): Promise<void> {
|
||||
await this.updateHostAppearance(serverId, (host) => {
|
||||
const { icon: _previousIcon, ...rest } = host.appearance;
|
||||
return {
|
||||
...host,
|
||||
appearance: icon ? { ...rest, icon } : rest,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async setHostBadgeDisplay(serverId: string, badgeDisplay: HostBadgeDisplay): Promise<void> {
|
||||
await this.updateHostAppearance(serverId, (host) => ({
|
||||
...host,
|
||||
@@ -2507,16 +2444,6 @@ export class HostRuntimeStore {
|
||||
}));
|
||||
}
|
||||
|
||||
refreshActiveLatencies(serverIds?: readonly string[]): void {
|
||||
const targets = serverIds ?? this.hosts.map((host) => host.serverId);
|
||||
for (const serverId of targets) {
|
||||
const controller = this.controllers.get(serverId);
|
||||
if (controller) {
|
||||
void controller.refreshActiveLatency();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private updateHostAppearance(
|
||||
serverId: string,
|
||||
apply: (host: HostProfile) => HostProfile,
|
||||
@@ -3128,12 +3055,19 @@ export class HostRuntimeStore {
|
||||
const directory = this.directorySyncByServer.get(serverId);
|
||||
if (!directory) throw new Error(`Unknown host runtime for serverId ${serverId}`);
|
||||
const owner = useSessionStore.getState().sessions[serverId]?.viewedTimelineSync;
|
||||
const page = await directory.fetchTimeline(agentId, request);
|
||||
if (owner && useSessionStore.getState().sessions[serverId]?.viewedTimelineSync === owner) {
|
||||
// A page served before a rewind this client applied is asked for again. Seqs only grow within
|
||||
// an epoch, so the next page includes the rewind unless another one landed meanwhile.
|
||||
for (let attempt = 1; ; attempt += 1) {
|
||||
const page = await directory.fetchTimeline(agentId, request);
|
||||
if (!owner || useSessionStore.getState().sessions[serverId]?.viewedTimelineSync !== owner) {
|
||||
return page;
|
||||
}
|
||||
owner.flushStreamAgent(agentId);
|
||||
owner.applyTimelineResponse(page);
|
||||
if (owner.applyTimelineResponse(page) === "applied") return page;
|
||||
if (attempt === MAX_STALE_TIMELINE_PAGE_ATTEMPTS) {
|
||||
throw new Error(`Timeline page for ${agentId} stayed behind a rewind`);
|
||||
}
|
||||
}
|
||||
return page;
|
||||
}
|
||||
|
||||
createViewedTimelineOwner(
|
||||
@@ -3370,7 +3304,6 @@ export interface HostMutations {
|
||||
beginLinkPairing: () => LinkPairing;
|
||||
renameHost: (serverId: string, label: string) => Promise<void>;
|
||||
setHostColor: (serverId: string, color: HostColor) => Promise<void>;
|
||||
setHostIcon: (serverId: string, icon: HostIcon | null) => Promise<void>;
|
||||
setHostBadgeDisplay: (serverId: string, badgeDisplay: HostBadgeDisplay) => Promise<void>;
|
||||
removeHost: (serverId: string) => Promise<void>;
|
||||
removeConnection: (serverId: string, connectionId: string) => Promise<void>;
|
||||
@@ -3386,7 +3319,6 @@ export function useHostMutations(): HostMutations {
|
||||
beginLinkPairing: () => store.beginLinkPairing(),
|
||||
renameHost: (serverId, label) => store.renameHost(serverId, label),
|
||||
setHostColor: (serverId, color) => store.setHostColor(serverId, color),
|
||||
setHostIcon: (serverId, icon) => store.setHostIcon(serverId, icon),
|
||||
setHostBadgeDisplay: (serverId, badgeDisplay) =>
|
||||
store.setHostBadgeDisplay(serverId, badgeDisplay),
|
||||
removeHost: (serverId) => store.removeHost(serverId),
|
||||
|
||||
@@ -189,7 +189,7 @@ function timelineItem(text = "Cached"): StreamItem {
|
||||
id: "message-1",
|
||||
text,
|
||||
timestamp: new Date("2026-07-18T08:02:00.000Z"),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 12 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 12, anchorSeq: 12 },
|
||||
};
|
||||
}
|
||||
|
||||
@@ -840,7 +840,7 @@ describe("ReplicaCache", () => {
|
||||
version: 1,
|
||||
data: { passed: 4, failed: 0 },
|
||||
timestamp: new Date("2026-07-18T08:02:00.000Z"),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 12 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 12, anchorSeq: 12 },
|
||||
};
|
||||
writer.commitTimeline(SERVER_ID, "agent-1", {
|
||||
agentId: "agent-1",
|
||||
@@ -885,6 +885,32 @@ describe("ReplicaCache", () => {
|
||||
expect(await createCache(storage).readTimeline(SERVER_ID, "agent-1")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("keeps where each cached row started, and refetches a timeline cached without it", async () => {
|
||||
const storage = new MemoryStorage();
|
||||
const writer = createCache(storage);
|
||||
const updatedAfterItStarted: StreamItem = {
|
||||
...timelineItem(),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 12, anchorSeq: 9 },
|
||||
};
|
||||
writer.commitTimeline(SERVER_ID, "agent-1", { ...timeline(), items: [updatedAfterItStarted] });
|
||||
await writer.flush();
|
||||
expect((await createCache(storage).readTimeline(SERVER_ID, "agent-1"))?.items).toEqual([
|
||||
updatedAfterItStarted,
|
||||
]);
|
||||
|
||||
const row = requireTimelineRow(storage);
|
||||
const payload = JSON.parse(row.payload) as {
|
||||
items: Array<{ timelineCursor?: Record<string, unknown> }>;
|
||||
};
|
||||
delete payload.items[0]?.timelineCursor?.anchorSeq;
|
||||
storage.rows.set(`${row.serverId}:${row.kind}:${row.id}`, {
|
||||
...row,
|
||||
payload: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
expect(await createCache(storage).readTimeline(SERVER_ID, "agent-1")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("refetches old cached Markdown fragments instead of offering them as whole messages", async () => {
|
||||
const storage = new MemoryStorage();
|
||||
const writer = createCache(storage);
|
||||
@@ -1355,7 +1381,7 @@ it("retains semantic agent messages across disk-cache reconstruction", async ()
|
||||
kind: "tool_call",
|
||||
id: "delivery",
|
||||
timestamp: new Date(1),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 12 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 12, anchorSeq: 12 },
|
||||
payload: {
|
||||
source: "agent",
|
||||
data: {
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
isUnreconciledLocalUserMessage,
|
||||
type AgentToolCallData,
|
||||
type StreamItem,
|
||||
type TimelinePosition,
|
||||
} from "@/types/stream";
|
||||
import type { UnsettledTurn } from "@/timeline/turn-liveness";
|
||||
import { normalizeAgentSnapshot } from "@/utils/agent-snapshots";
|
||||
@@ -82,7 +83,15 @@ const IsoDateSchema = z.iso.datetime();
|
||||
const TimelinePositionSchema = z.strictObject({
|
||||
epoch: z.string(),
|
||||
seq: z.number().int().nonnegative(),
|
||||
// COMPAT(timelineRewindOperations): absent on caches written before rows were anchored, added in
|
||||
// v0.14.1, remove after 2027-05-10. Such a cache is not restored; the chat loads its tail instead.
|
||||
anchorSeq: z.number().int().nonnegative().optional(),
|
||||
});
|
||||
type StoredTimelinePosition = z.infer<typeof TimelinePositionSchema>;
|
||||
|
||||
function isAnchored(position: StoredTimelinePosition | undefined): boolean {
|
||||
return position === undefined || position.anchorSeq !== undefined;
|
||||
}
|
||||
const PluginTimelineDataSchema: z.ZodType<PluginTimelineData> = z.lazy(() =>
|
||||
z.union([
|
||||
z.null(),
|
||||
@@ -423,6 +432,10 @@ function deserializeTimeline(stored: StoredTimeline | null): CachedTimeline | nu
|
||||
if (!stored) {
|
||||
return null;
|
||||
}
|
||||
// A rewind retires rows by anchor, so an unanchored row could not be retired.
|
||||
if (!stored.items.every((item) => isAnchored(item.timelineCursor))) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
agentId: stored.agentId,
|
||||
items: stored.items.map(deserializeTimelineItem),
|
||||
@@ -539,11 +552,20 @@ function serializeTimelineItem(item: StreamItem): StoredTimelineItem | null {
|
||||
}
|
||||
}
|
||||
|
||||
function anchoredPosition(position: StoredTimelinePosition | undefined): {
|
||||
timelineCursor?: TimelinePosition;
|
||||
} {
|
||||
if (!position || position.anchorSeq === undefined) return {};
|
||||
return {
|
||||
timelineCursor: { epoch: position.epoch, seq: position.seq, anchorSeq: position.anchorSeq },
|
||||
};
|
||||
}
|
||||
|
||||
function deserializeTimelineItem(item: StoredTimelineItem): StreamItem {
|
||||
if (item.kind === "plugin") {
|
||||
return {
|
||||
id: item.id,
|
||||
...(item.timelineCursor ? { timelineCursor: item.timelineCursor } : {}),
|
||||
...anchoredPosition(item.timelineCursor),
|
||||
...(item.turnId ? { turnId: item.turnId } : {}),
|
||||
timestamp: new Date(item.timestamp),
|
||||
kind: item.kind,
|
||||
@@ -562,7 +584,7 @@ function deserializeBuiltinTimelineItem(
|
||||
): StreamItem {
|
||||
const base = {
|
||||
id: item.id,
|
||||
...(item.timelineCursor ? { timelineCursor: item.timelineCursor } : {}),
|
||||
...anchoredPosition(item.timelineCursor),
|
||||
...(item.turnId ? { turnId: item.turnId } : {}),
|
||||
timestamp: new Date(item.timestamp),
|
||||
};
|
||||
|
||||
@@ -438,7 +438,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
|
||||
searchable={false}
|
||||
title={t("newWorkspace.fields.host")}
|
||||
desktopPlacement="bottom-start"
|
||||
desktopMinWidth={320}
|
||||
desktopMinWidth={200}
|
||||
hostOptionTestID={hostOptionTestID}
|
||||
>
|
||||
<FieldTrigger
|
||||
|
||||
@@ -83,7 +83,6 @@ import { DesktopNotificationsSection } from "@/desktop/components/desktop-notifi
|
||||
import { BrowserDataSection } from "@/desktop/browser/settings/browser-data-section";
|
||||
import { IntegrationsSection } from "@/desktop/components/integrations-section";
|
||||
import { isElectronRuntime } from "@/desktop/host";
|
||||
import { useDesktopSettings, type DesktopUpdateMode } from "@/desktop/settings/desktop-settings";
|
||||
import { useDesktopAppUpdater } from "@/desktop/updates/use-desktop-app-updater";
|
||||
import { formatVersionWithPrefix } from "@/desktop/updates/desktop-updates";
|
||||
import { resolveAppVersion } from "@/utils/app-version";
|
||||
@@ -610,92 +609,25 @@ function HostVersionRow({
|
||||
|
||||
function getUpdateButtonLabel(
|
||||
t: TFunction,
|
||||
input: {
|
||||
isInstalling: boolean;
|
||||
isDownloading: boolean;
|
||||
isActionable: boolean;
|
||||
readyToInstall: boolean;
|
||||
latestVersion: string | null | undefined;
|
||||
},
|
||||
isInstalling: boolean,
|
||||
latestVersion: string | null | undefined,
|
||||
): string {
|
||||
if (input.isInstalling) {
|
||||
return input.isDownloading
|
||||
? t("settings.about.updates.downloading")
|
||||
: t("settings.about.updates.installing");
|
||||
}
|
||||
if (input.isActionable && !input.readyToInstall) {
|
||||
if (input.latestVersion) {
|
||||
return t("settings.about.updates.downloadTo", {
|
||||
version: formatVersionWithPrefix(input.latestVersion),
|
||||
});
|
||||
}
|
||||
return t("settings.about.updates.download");
|
||||
}
|
||||
if (input.latestVersion) {
|
||||
if (isInstalling) return t("settings.about.updates.installing");
|
||||
if (latestVersion) {
|
||||
return t("settings.about.updates.updateTo", {
|
||||
version: formatVersionWithPrefix(input.latestVersion),
|
||||
version: formatVersionWithPrefix(latestVersion),
|
||||
});
|
||||
}
|
||||
return t("settings.about.updates.update");
|
||||
}
|
||||
|
||||
function getUpdateModeDescription(t: TFunction, mode: DesktopUpdateMode): string {
|
||||
if (mode === "off") return t("settings.about.autoUpdate.descriptions.off");
|
||||
if (mode === "notify") return t("settings.about.autoUpdate.descriptions.notify");
|
||||
return t("settings.about.autoUpdate.descriptions.automatic");
|
||||
}
|
||||
|
||||
function getUpdateConfirmDialogCopy(t: TFunction, isUpdateReady: boolean) {
|
||||
if (isUpdateReady) {
|
||||
return {
|
||||
title: t("settings.about.updates.installTitle"),
|
||||
message: t("settings.about.updates.installMessage"),
|
||||
confirmLabel: t("settings.about.updates.installConfirm"),
|
||||
cancelLabel: t("common.actions.cancel"),
|
||||
};
|
||||
}
|
||||
return {
|
||||
title: t("settings.about.updates.downloadTitle"),
|
||||
message: t("settings.about.updates.downloadMessage"),
|
||||
confirmLabel: t("settings.about.updates.downloadConfirm"),
|
||||
cancelLabel: t("common.actions.cancel"),
|
||||
};
|
||||
}
|
||||
|
||||
function DesktopUpdateProgressBar({ percent }: { percent: number }) {
|
||||
const accessibilityValue = useMemo(() => ({ min: 0, max: 100, now: percent }), [percent]);
|
||||
const fillStyle = useMemo(
|
||||
() => [styles.aboutUpdateProgressFill, { width: `${percent}%` as const }],
|
||||
[percent],
|
||||
);
|
||||
|
||||
return (
|
||||
<View
|
||||
style={styles.aboutUpdateProgressTrack}
|
||||
accessibilityRole="progressbar"
|
||||
accessibilityValue={accessibilityValue}
|
||||
testID="settings-about-update-progress"
|
||||
>
|
||||
<View style={fillStyle} />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function DesktopAppUpdateRow() {
|
||||
const { t } = useTranslation();
|
||||
const { settings, updateSettings } = useSettings();
|
||||
const {
|
||||
settings: desktopSettings,
|
||||
isLoading: isLoadingDesktopSettings,
|
||||
updateSettings: updateDesktopSettings,
|
||||
} = useDesktopSettings();
|
||||
const updateMode = desktopSettings.updates.mode;
|
||||
const {
|
||||
isDesktopApp,
|
||||
status,
|
||||
statusText,
|
||||
availableUpdate,
|
||||
downloadProgress,
|
||||
errorMessage,
|
||||
isChecking,
|
||||
isInstalling,
|
||||
@@ -705,12 +637,12 @@ function DesktopAppUpdateRow() {
|
||||
|
||||
useFocusEffect(
|
||||
useCallback(() => {
|
||||
if (!isDesktopApp || isLoadingDesktopSettings || updateMode === "off") {
|
||||
if (!isDesktopApp) {
|
||||
return undefined;
|
||||
}
|
||||
void checkForUpdates({ intent: "automatic", silent: true });
|
||||
return undefined;
|
||||
}, [checkForUpdates, isDesktopApp, isLoadingDesktopSettings, updateMode]),
|
||||
}, [checkForUpdates, isDesktopApp]),
|
||||
);
|
||||
|
||||
const handleCheckForUpdates = useCallback(() => {
|
||||
@@ -734,36 +666,17 @@ function DesktopAppUpdateRow() {
|
||||
[t],
|
||||
);
|
||||
|
||||
const handleUpdateModeChange = useCallback(
|
||||
(mode: DesktopUpdateMode) => {
|
||||
void updateDesktopSettings({ updates: { mode } });
|
||||
},
|
||||
[updateDesktopSettings],
|
||||
);
|
||||
const updateModeOptions = useMemo(
|
||||
() => [
|
||||
{ value: "automatic" as const, label: t("settings.about.autoUpdate.options.automatic") },
|
||||
{ value: "notify" as const, label: t("settings.about.autoUpdate.options.notify") },
|
||||
{ value: "off" as const, label: t("settings.about.autoUpdate.options.off") },
|
||||
],
|
||||
[t],
|
||||
);
|
||||
|
||||
const isUpdateReady = availableUpdate?.readyToInstall === true;
|
||||
const isUpdateActionable = status === "available" && availableUpdate?.hasUpdate === true;
|
||||
const readyUpdateVersion = isUpdateReady ? availableUpdate?.latestVersion : null;
|
||||
const actionableVersion = isUpdateActionable ? availableUpdate?.latestVersion : null;
|
||||
const downloadPercent =
|
||||
(isInstalling || status === "pending") && downloadProgress
|
||||
? Math.max(0, Math.min(100, Math.round(downloadProgress.percent)))
|
||||
: null;
|
||||
|
||||
const handleInstallUpdate = useCallback(() => {
|
||||
if (!isDesktopApp) {
|
||||
return;
|
||||
}
|
||||
|
||||
void confirmDialog(getUpdateConfirmDialogCopy(t, isUpdateReady))
|
||||
void confirmDialog({
|
||||
title: t("settings.about.updates.installTitle"),
|
||||
message: t("settings.about.updates.installMessage"),
|
||||
confirmLabel: t("settings.about.updates.installConfirm"),
|
||||
cancelLabel: t("common.actions.cancel"),
|
||||
})
|
||||
.then((confirmed) => {
|
||||
if (!confirmed) {
|
||||
return;
|
||||
@@ -778,7 +691,10 @@ function DesktopAppUpdateRow() {
|
||||
t("settings.about.updates.alertMessage"),
|
||||
);
|
||||
});
|
||||
}, [installUpdate, isDesktopApp, isUpdateReady, t]);
|
||||
}, [installUpdate, isDesktopApp, t]);
|
||||
|
||||
const isUpdateReady = availableUpdate?.readyToInstall === true;
|
||||
const readyUpdateVersion = isUpdateReady ? availableUpdate?.latestVersion : null;
|
||||
|
||||
if (!isDesktopApp) {
|
||||
return null;
|
||||
@@ -799,18 +715,6 @@ function DesktopAppUpdateRow() {
|
||||
options={releaseChannelOptions}
|
||||
/>
|
||||
</View>
|
||||
<View style={[settingsStyles.row, settingsStyles.rowBorder]}>
|
||||
<View style={settingsStyles.rowContent}>
|
||||
<Text style={settingsStyles.rowTitle}>{t("settings.about.autoUpdate.label")}</Text>
|
||||
<Text style={settingsStyles.rowHint}>{getUpdateModeDescription(t, updateMode)}</Text>
|
||||
</View>
|
||||
<SegmentedControl
|
||||
value={updateMode}
|
||||
onValueChange={handleUpdateModeChange}
|
||||
options={updateModeOptions}
|
||||
testID="settings-about-update-mode"
|
||||
/>
|
||||
</View>
|
||||
<View style={[settingsStyles.row, settingsStyles.rowBorder]}>
|
||||
<View style={settingsStyles.rowContent}>
|
||||
<Text style={settingsStyles.rowTitle}>{t("settings.about.updates.label")}</Text>
|
||||
@@ -822,7 +726,6 @@ function DesktopAppUpdateRow() {
|
||||
})}
|
||||
</Text>
|
||||
) : null}
|
||||
{downloadPercent !== null ? <DesktopUpdateProgressBar percent={downloadPercent} /> : null}
|
||||
{errorMessage ? <Text style={styles.aboutErrorText}>{errorMessage}</Text> : null}
|
||||
</View>
|
||||
<View style={styles.aboutUpdateActions}>
|
||||
@@ -836,15 +739,9 @@ function DesktopAppUpdateRow() {
|
||||
<Button
|
||||
variant="default"
|
||||
onPress={handleInstallUpdate}
|
||||
disabled={isChecking || isInstalling || !isUpdateActionable}
|
||||
disabled={isChecking || isInstalling || !isUpdateReady}
|
||||
>
|
||||
{getUpdateButtonLabel(t, {
|
||||
isInstalling,
|
||||
isDownloading: isInstalling && downloadProgress != null,
|
||||
isActionable: isUpdateActionable,
|
||||
readyToInstall: isUpdateReady,
|
||||
latestVersion: actionableVersion,
|
||||
})}
|
||||
{getUpdateButtonLabel(t, isInstalling, readyUpdateVersion)}
|
||||
</Button>
|
||||
</View>
|
||||
</View>
|
||||
@@ -1010,7 +907,7 @@ function HostPicker({
|
||||
showActiveConnection
|
||||
searchable={false}
|
||||
title={t("settings.hostPicker.switchHost")}
|
||||
desktopMinWidth={328}
|
||||
desktopMinWidth={240}
|
||||
addHostTestID="settings-add-host"
|
||||
hostOptionTestID={hostOptionTestID}
|
||||
>
|
||||
@@ -1609,19 +1506,6 @@ const styles = StyleSheet.create((theme) => ({
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
aboutUpdateProgressTrack: {
|
||||
marginTop: theme.spacing[2],
|
||||
height: 4,
|
||||
maxWidth: 260,
|
||||
borderRadius: theme.borderRadius.full,
|
||||
backgroundColor: theme.colors.surface3,
|
||||
overflow: "hidden",
|
||||
},
|
||||
aboutUpdateProgressFill: {
|
||||
height: "100%",
|
||||
borderRadius: theme.borderRadius.full,
|
||||
backgroundColor: theme.colors.accent,
|
||||
},
|
||||
placeholder: {
|
||||
flex: 1,
|
||||
alignItems: "center",
|
||||
|
||||
@@ -4,12 +4,7 @@ import { useTranslation } from "react-i18next";
|
||||
import { Pressable, Text, View } from "react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { Pencil } from "lucide-react-native";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu";
|
||||
import { DropdownTrigger } from "@/components/ui/dropdown-trigger";
|
||||
import { AdaptiveRenameModal } from "@/components/rename-modal";
|
||||
import { WorkspaceMetaRow } from "@/components/sidebar/workspace-meta-row";
|
||||
@@ -18,18 +13,12 @@ import { SettingsSection } from "@/components/settings/headings/settings-section
|
||||
import {
|
||||
HOST_BADGE_DISPLAYS,
|
||||
HOST_COLORS,
|
||||
HOST_ICONS,
|
||||
normalizeDetectedHostIcon,
|
||||
resolveHostBadgeDisplay,
|
||||
resolveHostIcon,
|
||||
type HostBadgeDisplay,
|
||||
type HostColor,
|
||||
type HostIcon,
|
||||
} from "@/hosts/appearance";
|
||||
import { HostIconGlyph } from "@/hosts/host-icon-glyph";
|
||||
import { useLocalDaemonServerIdState } from "@/hooks/use-is-local-daemon";
|
||||
import { useHostMutations } from "@/runtime/host-runtime";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { identityColor } from "@/styles/identity-colors";
|
||||
import { settingsStyles } from "@/styles/settings";
|
||||
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||
@@ -87,112 +76,10 @@ function colorLabel(t: TFunction, color: HostColor): string {
|
||||
return t(`settings.host.appearance.color.options.${color}`);
|
||||
}
|
||||
|
||||
function iconLabel(t: TFunction, icon: HostIcon): string {
|
||||
return t(`settings.host.appearance.icon.options.${icon}`);
|
||||
}
|
||||
|
||||
function autoIconLabel(t: TFunction, detectedIcon: HostIcon | null): string {
|
||||
if (detectedIcon) {
|
||||
return t("settings.host.appearance.icon.autoDetected", {
|
||||
icon: iconLabel(t, detectedIcon),
|
||||
});
|
||||
}
|
||||
return t("settings.host.appearance.icon.auto");
|
||||
}
|
||||
|
||||
function badgeDisplayLabel(t: TFunction, display: HostBadgeDisplay): string {
|
||||
return t(`settings.host.appearance.badge.options.${display}`);
|
||||
}
|
||||
|
||||
function IconMenuItem({
|
||||
icon,
|
||||
color,
|
||||
selected,
|
||||
onChange,
|
||||
}: {
|
||||
icon: HostIcon;
|
||||
color: HostColor;
|
||||
selected: boolean;
|
||||
onChange: (icon: HostIcon | null) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const handleSelect = useCallback(() => onChange(icon), [icon, onChange]);
|
||||
const leading = useMemo(
|
||||
() => <HostIconGlyph icon={icon} color={color} size={ICON_SIZE.sm} />,
|
||||
[color, icon],
|
||||
);
|
||||
return (
|
||||
<DropdownMenuItem selected={selected} onSelect={handleSelect} leading={leading}>
|
||||
{iconLabel(t, icon)}
|
||||
</DropdownMenuItem>
|
||||
);
|
||||
}
|
||||
|
||||
function IconRow({
|
||||
icon,
|
||||
detectedIcon,
|
||||
resolvedIcon,
|
||||
color,
|
||||
onChange,
|
||||
}: {
|
||||
icon: HostIcon | null;
|
||||
detectedIcon: HostIcon | null;
|
||||
resolvedIcon: HostIcon;
|
||||
color: HostColor;
|
||||
onChange: (icon: HostIcon | null) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const autoLabel = autoIconLabel(t, detectedIcon);
|
||||
const selectedLabel = icon ? iconLabel(t, icon) : autoLabel;
|
||||
const handleSelectAuto = useCallback(() => onChange(null), [onChange]);
|
||||
const triggerLeading = useMemo(
|
||||
() => <HostIconGlyph icon={resolvedIcon} color={color} size={ICON_SIZE.sm} />,
|
||||
[color, resolvedIcon],
|
||||
);
|
||||
const autoLeading = useMemo(
|
||||
() => <HostIconGlyph icon={detectedIcon ?? "server"} color={color} size={ICON_SIZE.sm} />,
|
||||
[color, detectedIcon],
|
||||
);
|
||||
return (
|
||||
<View style={[settingsStyles.row, settingsStyles.rowBorder]}>
|
||||
<View style={settingsStyles.rowContent}>
|
||||
<Text style={settingsStyles.rowTitle}>{t("settings.host.appearance.icon.label")}</Text>
|
||||
</View>
|
||||
<DropdownMenu>
|
||||
<DropdownTrigger
|
||||
testID="host-appearance-icon"
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={t("settings.host.appearance.icon.accessibilityLabel", {
|
||||
value: selectedLabel,
|
||||
})}
|
||||
leading={triggerLeading}
|
||||
>
|
||||
{selectedLabel}
|
||||
</DropdownTrigger>
|
||||
<DropdownMenuContent side="bottom" align="end" width={220}>
|
||||
<DropdownMenuItem
|
||||
selected={icon === null}
|
||||
onSelect={handleSelectAuto}
|
||||
leading={autoLeading}
|
||||
>
|
||||
{autoLabel}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
{HOST_ICONS.map((option) => (
|
||||
<IconMenuItem
|
||||
key={option}
|
||||
icon={option}
|
||||
color={color}
|
||||
selected={option === icon}
|
||||
onChange={onChange}
|
||||
/>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function ColorSwatch({ color }: { color: HostColor }) {
|
||||
const swatchStyle = useMemo(
|
||||
() => [styles.swatch, color === "none" ? null : { backgroundColor: identityColor(color) }],
|
||||
@@ -318,11 +205,9 @@ function BadgeDisplayMenuItem({
|
||||
*/
|
||||
function BadgePreview({
|
||||
host,
|
||||
resolvedIcon,
|
||||
badgeDisplay,
|
||||
}: {
|
||||
host: HostProfile;
|
||||
resolvedIcon: HostIcon;
|
||||
badgeDisplay: HostBadgeDisplay;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
@@ -334,10 +219,9 @@ function BadgePreview({
|
||||
serverId: host.serverId,
|
||||
label: host.label,
|
||||
color: host.appearance.color,
|
||||
icon: resolvedIcon,
|
||||
showLabel: badgeDisplay === "name",
|
||||
},
|
||||
[badgeDisplay, host.serverId, host.label, host.appearance.color, resolvedIcon],
|
||||
[badgeDisplay, host.serverId, host.label, host.appearance.color],
|
||||
);
|
||||
// The real sidebar row, so the preview can't drift from what the setting actually does.
|
||||
return (
|
||||
@@ -360,14 +244,8 @@ function BadgePreview({
|
||||
export function HostAppearanceSection({ host }: { host: HostProfile }) {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const { setHostColor, setHostIcon, setHostBadgeDisplay } = useHostMutations();
|
||||
const { setHostColor, setHostBadgeDisplay } = useHostMutations();
|
||||
const localDaemon = useLocalDaemonServerIdState();
|
||||
const detectedMachineKind = useSessionStore(
|
||||
(state) => state.sessions[host.serverId]?.serverInfo?.machineKind ?? null,
|
||||
);
|
||||
const detectedIcon = normalizeDetectedHostIcon(detectedMachineKind);
|
||||
const selectedIcon = normalizeDetectedHostIcon(host.appearance.icon);
|
||||
const resolvedIcon = resolveHostIcon({ appearance: host.appearance, detectedMachineKind });
|
||||
const isLocalHost = localDaemon.status === "resolved" && localDaemon.serverId === host.serverId;
|
||||
const badgeDisplay = resolveHostBadgeDisplay({
|
||||
appearance: host.appearance,
|
||||
@@ -385,16 +263,6 @@ export function HostAppearanceSection({ host }: { host: HostProfile }) {
|
||||
},
|
||||
[host.serverId, setHostColor, t, toast],
|
||||
);
|
||||
const handleIconChange = useCallback(
|
||||
async (icon: HostIcon | null) => {
|
||||
try {
|
||||
await setHostIcon(host.serverId, icon);
|
||||
} catch {
|
||||
toast.error(t("errors.unableToSave"));
|
||||
}
|
||||
},
|
||||
[host.serverId, setHostIcon, t, toast],
|
||||
);
|
||||
const handleBadgeDisplayChange = useCallback(
|
||||
async (next: HostBadgeDisplay) => {
|
||||
try {
|
||||
@@ -420,18 +288,11 @@ export function HostAppearanceSection({ host }: { host: HostProfile }) {
|
||||
<HostRenameButton host={host} />
|
||||
</View>
|
||||
</View>
|
||||
<IconRow
|
||||
icon={selectedIcon}
|
||||
detectedIcon={detectedIcon}
|
||||
resolvedIcon={resolvedIcon}
|
||||
color={host.appearance.color}
|
||||
onChange={handleIconChange}
|
||||
/>
|
||||
<ColorRow color={host.appearance.color} onChange={handleColorChange} />
|
||||
{badgeDisplay === null ? null : (
|
||||
<>
|
||||
<BadgeDisplayRow badgeDisplay={badgeDisplay} onChange={handleBadgeDisplayChange} />
|
||||
<BadgePreview host={host} resolvedIcon={resolvedIcon} badgeDisplay={badgeDisplay} />
|
||||
<BadgePreview host={host} badgeDisplay={badgeDisplay} />
|
||||
</>
|
||||
)}
|
||||
</View>
|
||||
|
||||
@@ -2188,11 +2188,10 @@ function WorkspaceScreenContent({
|
||||
|
||||
toast.show(t("workspace.tabs.toasts.reloadingAgent"), { durationMs: null });
|
||||
try {
|
||||
await client.refreshAgent(agentId);
|
||||
// Send the existing cursor so the server detects the new epoch and
|
||||
// returns reset:true. Without a cursor, the server returns reset:false
|
||||
// and the client takes the incremental path, where new-epoch rows are
|
||||
// dropped against the stale cursor.
|
||||
const refreshed = await client.refreshAgent(agentId);
|
||||
// Send the existing cursor: Reload agent keeps the history, so the server
|
||||
// returns only the rows it added. When the history was imported again
|
||||
// under a new epoch, the cursor reads as stale and the server resets.
|
||||
const sessionState = useSessionStore.getState().sessions[normalizedServerId];
|
||||
const currentCursor = sessionState?.agentTimelineCursor.get(agentId);
|
||||
await getHostRuntimeStore().fetchAgentTimeline(normalizedServerId, agentId, {
|
||||
@@ -2201,7 +2200,13 @@ function WorkspaceScreenContent({
|
||||
? { cursor: { epoch: currentCursor.epoch, seq: currentCursor.endSeq } }
|
||||
: {}),
|
||||
});
|
||||
toast.show(t("workspace.tabs.toasts.reloadedAgent"), { variant: "success" });
|
||||
if (refreshed.historyDiverged) {
|
||||
toast.show(t("workspace.tabs.toasts.reloadedAgentHistoryDiverged"), {
|
||||
variant: "warning",
|
||||
});
|
||||
} else {
|
||||
toast.show(t("workspace.tabs.toasts.reloadedAgent"), { variant: "success" });
|
||||
}
|
||||
} catch (error) {
|
||||
toast.error(
|
||||
error instanceof Error ? error.message : t("workspace.tabs.toasts.failedToReloadAgent"),
|
||||
|
||||
@@ -293,7 +293,6 @@ export interface DaemonServerInfo {
|
||||
serverId: string;
|
||||
hostname: string | null;
|
||||
version: string | null;
|
||||
machineKind?: string | null;
|
||||
desktopManaged?: boolean;
|
||||
capabilities?: ServerCapabilities;
|
||||
features?: ServerInfoStatusPayload["features"];
|
||||
@@ -304,7 +303,6 @@ export function toDaemonServerInfo(serverInfo: ServerInfoStatusPayload): DaemonS
|
||||
serverId: serverInfo.serverId,
|
||||
hostname: serverInfo.hostname ?? null,
|
||||
version: serverInfo.version ?? null,
|
||||
...(serverInfo.machineKind !== undefined ? { machineKind: serverInfo.machineKind } : {}),
|
||||
...(serverInfo.desktopManaged !== undefined
|
||||
? { desktopManaged: serverInfo.desktopManaged }
|
||||
: {}),
|
||||
@@ -324,6 +322,12 @@ export interface AgentTimelineCursorState {
|
||||
}>;
|
||||
}
|
||||
|
||||
/** The latest conversation rewind applied to an agent's history, by its sequence number. */
|
||||
export interface AgentTimelineRewind {
|
||||
epoch: string;
|
||||
seq: number;
|
||||
}
|
||||
|
||||
export type AgentTimelineState =
|
||||
| { status: "cold" }
|
||||
| { status: "painted"; items: StreamItem[] }
|
||||
@@ -498,6 +502,7 @@ export interface SessionState {
|
||||
agentTimelineUnsettledTurn: Map<string, UnsettledTurn>;
|
||||
agentTimelineHasOlder: Map<string, boolean>;
|
||||
agentTimelineHasNewer: Map<string, boolean>;
|
||||
agentTimelineLatestRewind: Map<string, AgentTimelineRewind>;
|
||||
agentTimelineOlderFetchInFlight: Map<string, boolean>;
|
||||
historySyncGeneration: number;
|
||||
agentHistorySyncGeneration: Map<string, number>;
|
||||
@@ -617,6 +622,12 @@ interface SessionStoreActions {
|
||||
serverId: string,
|
||||
state: Map<string, boolean> | ((prev: Map<string, boolean>) => Map<string, boolean>),
|
||||
) => void;
|
||||
/** Records a rewind applied to the agent's history; an older one of the same history is ignored. */
|
||||
recordAgentTimelineRewind: (
|
||||
serverId: string,
|
||||
agentId: string,
|
||||
rewind: AgentTimelineRewind,
|
||||
) => void;
|
||||
setAgentTimelineOlderFetchInFlight: (
|
||||
serverId: string,
|
||||
state: Map<string, boolean> | ((prev: Map<string, boolean>) => Map<string, boolean>),
|
||||
@@ -753,6 +764,7 @@ function createInitialSessionState(
|
||||
agentTimelineUnsettledTurn: new Map(),
|
||||
agentTimelineHasOlder: new Map(),
|
||||
agentTimelineHasNewer: new Map(),
|
||||
agentTimelineLatestRewind: new Map(),
|
||||
agentTimelineOlderFetchInFlight: new Map(),
|
||||
historySyncGeneration: 0,
|
||||
agentHistorySyncGeneration: new Map(),
|
||||
@@ -788,7 +800,6 @@ function isSessionServerInfoUnchanged(input: {
|
||||
currentServerInfo: SessionState["serverInfo"] | undefined;
|
||||
nextHostname: string | null;
|
||||
nextVersion: string | null;
|
||||
nextMachineKind: string | null;
|
||||
nextDesktopManaged: boolean | undefined;
|
||||
nextCapabilities: ServerCapabilities | undefined;
|
||||
nextFeatures: ServerInfoStatusPayload["features"] | undefined;
|
||||
@@ -798,19 +809,16 @@ function isSessionServerInfoUnchanged(input: {
|
||||
currentServerInfo,
|
||||
nextHostname,
|
||||
nextVersion,
|
||||
nextMachineKind,
|
||||
nextDesktopManaged,
|
||||
nextCapabilities,
|
||||
nextFeatures,
|
||||
} = input;
|
||||
const prevHostname = currentServerInfo?.hostname?.trim() || null;
|
||||
const prevVersion = currentServerInfo?.version?.trim() || null;
|
||||
const prevMachineKind = currentServerInfo?.machineKind?.trim() || null;
|
||||
return (
|
||||
currentServerInfo?.serverId === input.nextServerId &&
|
||||
prevHostname === nextHostname &&
|
||||
prevVersion === nextVersion &&
|
||||
prevMachineKind === nextMachineKind &&
|
||||
currentServerInfo?.desktopManaged === nextDesktopManaged &&
|
||||
areServerCapabilitiesEqual(currentServerInfo?.capabilities, nextCapabilities) &&
|
||||
areServerInfoFeaturesEqual(currentServerInfo?.features, nextFeatures)
|
||||
@@ -948,7 +956,6 @@ export const useSessionStore = create<SessionStore>()(
|
||||
|
||||
const nextHostname = info.hostname?.trim() || null;
|
||||
const nextVersion = info.version?.trim() || null;
|
||||
const nextMachineKind = info.machineKind?.trim() || null;
|
||||
const nextDesktopManaged = info.desktopManaged;
|
||||
const nextCapabilities = info.capabilities;
|
||||
const nextFeatures = info.features;
|
||||
@@ -958,7 +965,6 @@ export const useSessionStore = create<SessionStore>()(
|
||||
currentServerInfo: session.serverInfo,
|
||||
nextHostname,
|
||||
nextVersion,
|
||||
nextMachineKind,
|
||||
nextDesktopManaged,
|
||||
nextCapabilities,
|
||||
nextFeatures,
|
||||
@@ -978,7 +984,6 @@ export const useSessionStore = create<SessionStore>()(
|
||||
serverId: info.serverId,
|
||||
hostname: nextHostname,
|
||||
version: nextVersion,
|
||||
...(nextMachineKind !== null ? { machineKind: nextMachineKind } : {}),
|
||||
...(nextDesktopManaged !== undefined
|
||||
? { desktopManaged: nextDesktopManaged }
|
||||
: {}),
|
||||
@@ -1401,6 +1406,24 @@ export const useSessionStore = create<SessionStore>()(
|
||||
});
|
||||
},
|
||||
|
||||
recordAgentTimelineRewind: (serverId, agentId, rewind) => {
|
||||
set((prev) => {
|
||||
const session = prev.sessions[serverId];
|
||||
if (!session) return prev;
|
||||
const current = session.agentTimelineLatestRewind.get(agentId);
|
||||
if (current && current.epoch === rewind.epoch && current.seq >= rewind.seq) return prev;
|
||||
const next = new Map(session.agentTimelineLatestRewind);
|
||||
next.set(agentId, rewind);
|
||||
return {
|
||||
...prev,
|
||||
sessions: {
|
||||
...prev.sessions,
|
||||
[serverId]: { ...session, agentTimelineLatestRewind: next },
|
||||
},
|
||||
};
|
||||
});
|
||||
},
|
||||
|
||||
setAgentTimelineOlderFetchInFlight: (serverId, state) => {
|
||||
set((prev) => {
|
||||
const session = prev.sessions[serverId];
|
||||
|
||||
@@ -39,7 +39,7 @@ function item(id: string, text: string, seq: number): StreamItem {
|
||||
id,
|
||||
text,
|
||||
timestamp: new Date("2026-08-26T10:00:00.000Z"),
|
||||
timelineCursor: { epoch: "epoch-1", seq },
|
||||
timelineCursor: { epoch: "epoch-1", seq, anchorSeq: seq },
|
||||
};
|
||||
}
|
||||
|
||||
@@ -579,6 +579,235 @@ describe("viewed timeline persistence", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("conversation rewind through the owner", () => {
|
||||
const page = {
|
||||
requestId: "page-1",
|
||||
agentId: AGENT_ID,
|
||||
agent: null,
|
||||
direction: "tail",
|
||||
projection: "projected",
|
||||
reset: false,
|
||||
epoch: "epoch-1",
|
||||
error: null,
|
||||
hasNewer: false,
|
||||
hasOlder: false,
|
||||
staleCursor: false,
|
||||
gap: false,
|
||||
} as const;
|
||||
|
||||
function entry(seq: number, type: "user_message" | "assistant_message", text: string) {
|
||||
return {
|
||||
seqStart: seq,
|
||||
seqEnd: seq,
|
||||
sourceSeqRanges: [{ startSeq: seq, endSeq: seq }],
|
||||
collapsed: [],
|
||||
provider: "codex",
|
||||
item: { type, text },
|
||||
timestamp: `2026-08-26T10:00:0${seq}.000Z`,
|
||||
};
|
||||
}
|
||||
|
||||
function texts(items: readonly StreamItem[]): string[] {
|
||||
return items.flatMap((row) =>
|
||||
row.kind === "user_message" || row.kind === "assistant_message" ? [row.text] : [],
|
||||
);
|
||||
}
|
||||
|
||||
function viewed(): string[] {
|
||||
const session = useSessionStore.getState().sessions[SERVER_ID];
|
||||
const timeline = selectAgentTimelineState(session, AGENT_ID);
|
||||
const tail = timeline.status === "cold" ? [] : timeline.items;
|
||||
return texts([...tail, ...(session?.agentStreamHead.get(AGENT_ID) ?? [])]);
|
||||
}
|
||||
|
||||
function latestRewind() {
|
||||
return useSessionStore.getState().sessions[SERVER_ID]?.agentTimelineLatestRewind.get(AGENT_ID);
|
||||
}
|
||||
|
||||
it("retires B from the viewed and persisted timeline without refetching", () => {
|
||||
useSessionStore.getState().initializeSession(SERVER_ID, null);
|
||||
const commits: CachedTimeline[] = [];
|
||||
const owner = createOwner({
|
||||
readTimeline: async () => undefined,
|
||||
commitTimeline: (_serverId, _agentId, timeline) => commits.push(timeline),
|
||||
});
|
||||
owner.applyTimelineResponse({
|
||||
...page,
|
||||
window: { minSeq: 1, maxSeq: 4, nextSeq: 5 },
|
||||
startCursor: { epoch: "epoch-1", seq: 1 },
|
||||
endCursor: { epoch: "epoch-1", seq: 4 },
|
||||
entries: [
|
||||
entry(1, "user_message", "A"),
|
||||
entry(2, "assistant_message", "reply A"),
|
||||
entry(3, "user_message", "B"),
|
||||
entry(4, "assistant_message", "reply B"),
|
||||
],
|
||||
});
|
||||
|
||||
owner.applyStreamEvent(AGENT_ID, {
|
||||
event: { type: "rewind", retireFromSeq: 3 },
|
||||
seq: 5,
|
||||
epoch: "epoch-1",
|
||||
timestamp: new Date("2026-08-26T10:00:05.000Z"),
|
||||
});
|
||||
owner.applyStreamEvent(AGENT_ID, {
|
||||
event: {
|
||||
type: "timeline",
|
||||
provider: "codex",
|
||||
item: { type: "user_message", text: "C", messageId: "c" },
|
||||
} as AgentStreamEventPayload,
|
||||
seq: 6,
|
||||
epoch: "epoch-1",
|
||||
timestamp: new Date("2026-08-26T10:00:06.000Z"),
|
||||
});
|
||||
owner.flushStreamAgent(AGENT_ID);
|
||||
|
||||
expect(viewed()).toEqual(["A", "reply A", "C"]);
|
||||
expect(texts(commits.at(-1)?.items ?? [])).toEqual(["A", "reply A", "C"]);
|
||||
expect(commits.at(-1)?.range).toMatchObject({ epoch: "epoch-1", endSeq: 6 });
|
||||
expect(latestRewind()).toEqual({ epoch: "epoch-1", seq: 5 });
|
||||
owner.dispose();
|
||||
});
|
||||
|
||||
it("brings a second client that loads after the rewind to the same conversation", () => {
|
||||
useSessionStore.getState().initializeSession(SERVER_ID, null);
|
||||
const owner = createOwner({ readTimeline: async () => undefined, commitTimeline: () => {} });
|
||||
|
||||
owner.applyTimelineResponse({
|
||||
...page,
|
||||
window: { minSeq: 1, maxSeq: 6, nextSeq: 7 },
|
||||
startCursor: { epoch: "epoch-1", seq: 1 },
|
||||
endCursor: { epoch: "epoch-1", seq: 6 },
|
||||
entries: [
|
||||
entry(1, "user_message", "A"),
|
||||
entry(2, "assistant_message", "reply A"),
|
||||
entry(6, "user_message", "C"),
|
||||
],
|
||||
retirements: [{ seq: 5, retireFromSeq: 3 }],
|
||||
});
|
||||
|
||||
expect(viewed()).toEqual(["A", "reply A", "C"]);
|
||||
expect(latestRewind()).toEqual({ epoch: "epoch-1", seq: 5 });
|
||||
owner.dispose();
|
||||
});
|
||||
|
||||
function liveRewindOfB(owner: ViewedTimelineOwner, retirement: { seq: number }): void {
|
||||
owner.applyStreamEvent(AGENT_ID, {
|
||||
event: { type: "rewind", retireFromSeq: 3 },
|
||||
seq: retirement.seq,
|
||||
epoch: "epoch-1",
|
||||
timestamp: new Date("2026-08-26T10:00:06.000Z"),
|
||||
});
|
||||
owner.applyStreamEvent(AGENT_ID, {
|
||||
event: {
|
||||
type: "timeline",
|
||||
provider: "codex",
|
||||
item: { type: "user_message", text: "C", messageId: "c" },
|
||||
} as AgentStreamEventPayload,
|
||||
seq: retirement.seq + 1,
|
||||
epoch: "epoch-1",
|
||||
timestamp: new Date("2026-08-26T10:00:07.000Z"),
|
||||
});
|
||||
owner.flushStreamAgent(AGENT_ID);
|
||||
}
|
||||
|
||||
/** A, reply A, B, reply B as a page served before B was rewound. */
|
||||
const pageServedBeforeTheRewind: Parameters<ViewedTimelineOwner["applyTimelineResponse"]>[0] = {
|
||||
...page,
|
||||
direction: "before",
|
||||
hasOlder: false,
|
||||
window: { minSeq: 1, maxSeq: 5, nextSeq: 6 },
|
||||
startCursor: { epoch: "epoch-1", seq: 1 },
|
||||
endCursor: { epoch: "epoch-1", seq: 4 },
|
||||
entries: [
|
||||
entry(1, "user_message", "A"),
|
||||
entry(2, "assistant_message", "reply A"),
|
||||
entry(3, "user_message", "B"),
|
||||
entry(4, "assistant_message", "reply B"),
|
||||
],
|
||||
};
|
||||
|
||||
function loadTheEndOfB(owner: ViewedTimelineOwner): void {
|
||||
owner.applyTimelineResponse({
|
||||
...page,
|
||||
hasOlder: true,
|
||||
window: { minSeq: 1, maxSeq: 5, nextSeq: 6 },
|
||||
startCursor: { epoch: "epoch-1", seq: 5 },
|
||||
endCursor: { epoch: "epoch-1", seq: 5 },
|
||||
entries: [entry(5, "assistant_message", "more of B")],
|
||||
});
|
||||
}
|
||||
|
||||
it("refuses an older page served before the rewind and takes the one served after it", () => {
|
||||
useSessionStore.getState().initializeSession(SERVER_ID, null);
|
||||
const owner = createOwner({ readTimeline: async () => undefined, commitTimeline: () => {} });
|
||||
loadTheEndOfB(owner);
|
||||
liveRewindOfB(owner, { seq: 6 });
|
||||
expect(viewed()).toEqual(["C"]);
|
||||
|
||||
const outcome = owner.applyTimelineResponse(pageServedBeforeTheRewind);
|
||||
expect(viewed()).toEqual(["C"]);
|
||||
expect(outcome).toBe("stale");
|
||||
|
||||
owner.applyTimelineResponse({
|
||||
...pageServedBeforeTheRewind,
|
||||
window: { minSeq: 1, maxSeq: 7, nextSeq: 8 },
|
||||
// Retired rows count as covered, so the page reaches the loaded start.
|
||||
endCursor: { epoch: "epoch-1", seq: 4 },
|
||||
entries: [entry(1, "user_message", "A"), entry(2, "assistant_message", "reply A")],
|
||||
});
|
||||
expect(viewed()).toEqual(["A", "reply A", "C"]);
|
||||
owner.dispose();
|
||||
});
|
||||
|
||||
it("refuses a prompt jump window served before the rewind", () => {
|
||||
useSessionStore.getState().initializeSession(SERVER_ID, null);
|
||||
const owner = createOwner({ readTimeline: async () => undefined, commitTimeline: () => {} });
|
||||
loadTheEndOfB(owner);
|
||||
liveRewindOfB(owner, { seq: 6 });
|
||||
|
||||
const outcome = owner.applyTimelineResponse({
|
||||
...pageServedBeforeTheRewind,
|
||||
mergeWindow: true,
|
||||
});
|
||||
expect(viewed()).toEqual(["C"]);
|
||||
expect(outcome).toBe("stale");
|
||||
owner.dispose();
|
||||
});
|
||||
|
||||
it("refuses a first page served before a rewind that reached the chat while it loaded", () => {
|
||||
useSessionStore.getState().initializeSession(SERVER_ID, null);
|
||||
const owner = createOwner({ readTimeline: async () => undefined, commitTimeline: () => {} });
|
||||
liveRewindOfB(owner, { seq: 5 });
|
||||
|
||||
const outcome = owner.applyTimelineResponse({
|
||||
...pageServedBeforeTheRewind,
|
||||
direction: "tail",
|
||||
window: { minSeq: 1, maxSeq: 4, nextSeq: 5 },
|
||||
});
|
||||
expect(viewed()).toEqual(["C"]);
|
||||
expect(outcome).toBe("stale");
|
||||
|
||||
owner.applyTimelineResponse({
|
||||
...page,
|
||||
window: { minSeq: 1, maxSeq: 6, nextSeq: 7 },
|
||||
startCursor: { epoch: "epoch-1", seq: 1 },
|
||||
endCursor: { epoch: "epoch-1", seq: 6 },
|
||||
entries: [
|
||||
entry(1, "user_message", "A"),
|
||||
entry(2, "assistant_message", "reply A"),
|
||||
{
|
||||
...entry(6, "user_message", "C"),
|
||||
item: { type: "user_message", text: "C", messageId: "c" },
|
||||
},
|
||||
],
|
||||
retirements: [{ seq: 5, retireFromSeq: 3 }],
|
||||
});
|
||||
expect(viewed()).toEqual(["A", "reply A", "C"]);
|
||||
owner.dispose();
|
||||
});
|
||||
});
|
||||
|
||||
describe("turn boundaries", () => {
|
||||
it("commits a turn's final reply before the turn stops running", () => {
|
||||
useSessionStore.getState().initializeSession(SERVER_ID, null);
|
||||
|
||||
@@ -398,7 +398,7 @@ describe("processTimelineResponse", () => {
|
||||
messageId: "provider-message",
|
||||
text: "local prompt",
|
||||
timestamp: new Date(1000),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
|
||||
turnId: "turn-1",
|
||||
});
|
||||
const hello = createUserMessage({
|
||||
@@ -406,7 +406,7 @@ describe("processTimelineResponse", () => {
|
||||
clientMessageId: "hello-client",
|
||||
text: "hello",
|
||||
timestamp: new Date(1500),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
|
||||
turnId: "turn-1",
|
||||
});
|
||||
const currentTail = [canonical, makeAssistantItem("existing tail", "existing-tail"), hello];
|
||||
@@ -456,7 +456,7 @@ describe("processTimelineResponse", () => {
|
||||
id: "stale-history",
|
||||
text: "stale history",
|
||||
timestamp: new Date(1040),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 40 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 40, anchorSeq: 40 },
|
||||
},
|
||||
],
|
||||
currentCursor: { epoch: "epoch-1", startSeq: 1, endSeq: 40 },
|
||||
@@ -484,11 +484,11 @@ describe("processTimelineResponse", () => {
|
||||
const unresolved = makeSubmittedUserMessage("unresolved prompt", "client-unresolved");
|
||||
const coveredLive: StreamItem = {
|
||||
...makeAssistantItem("covered live", "covered-live"),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 235 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 235, anchorSeq: 235 },
|
||||
};
|
||||
const newerLive: StreamItem = {
|
||||
...makeAssistantItem("newer live", "newer-live"),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 245 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 245, anchorSeq: 245 },
|
||||
};
|
||||
|
||||
const result = processTimelineResponse({
|
||||
@@ -573,7 +573,7 @@ describe("processTimelineResponse", () => {
|
||||
expect.objectContaining({
|
||||
kind: "assistant_message",
|
||||
text: "[System Error] failed",
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42 },
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 40 },
|
||||
}),
|
||||
]);
|
||||
});
|
||||
@@ -745,7 +745,7 @@ describe("processTimelineResponse", () => {
|
||||
}).item,
|
||||
} as AgentStreamEventPayload,
|
||||
timestamp: new Date(2000),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
|
||||
},
|
||||
],
|
||||
{ source: "canonical" },
|
||||
@@ -775,7 +775,7 @@ describe("processTimelineResponse", () => {
|
||||
|
||||
expect(getAgentToolCalls([...result.tail, ...result.head])).toEqual([
|
||||
expect.objectContaining({
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 1 },
|
||||
payload: expect.objectContaining({
|
||||
data: expect.objectContaining({ callId, status: "completed" }),
|
||||
}),
|
||||
@@ -796,7 +796,7 @@ describe("processTimelineResponse", () => {
|
||||
},
|
||||
} as AgentStreamEventPayload,
|
||||
timestamp: new Date(2000),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
|
||||
},
|
||||
],
|
||||
{ source: "canonical" },
|
||||
@@ -831,7 +831,7 @@ describe("processTimelineResponse", () => {
|
||||
|
||||
expect([...result.tail, ...result.head].filter((item) => item.kind === "todo_list")).toEqual([
|
||||
expect.objectContaining({
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 1 },
|
||||
items: [{ text: "Verify hydration", completed: true }],
|
||||
}),
|
||||
]);
|
||||
@@ -847,7 +847,7 @@ describe("processTimelineResponse", () => {
|
||||
item: { type: "compaction", status: "completed", trigger: "auto", preTokens: 1200 },
|
||||
} as AgentStreamEventPayload,
|
||||
timestamp: new Date(2000),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
|
||||
},
|
||||
],
|
||||
{ source: "canonical" },
|
||||
@@ -879,7 +879,7 @@ describe("processTimelineResponse", () => {
|
||||
|
||||
expect([...result.tail, ...result.head].filter((item) => item.kind === "compaction")).toEqual([
|
||||
expect.objectContaining({
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 1 },
|
||||
status: "completed",
|
||||
trigger: "auto",
|
||||
preTokens: 1200,
|
||||
@@ -918,7 +918,7 @@ describe("processTimelineResponse", () => {
|
||||
messageId: "assistant-live",
|
||||
text: " continuation",
|
||||
timestamp: new Date(2001),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 101 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 101, anchorSeq: 101 },
|
||||
},
|
||||
],
|
||||
isInitializing: true,
|
||||
@@ -946,7 +946,7 @@ describe("processTimelineResponse", () => {
|
||||
);
|
||||
expect(assistants).toHaveLength(1);
|
||||
expect(assistants[0]?.text).toBe("canonical prefix continuation");
|
||||
expect(assistants[0]?.timelineCursor).toEqual({ epoch: "epoch-1", seq: 101 });
|
||||
expect(assistants[0]?.timelineCursor).toEqual({ epoch: "epoch-1", seq: 101, anchorSeq: 100 });
|
||||
});
|
||||
|
||||
it("keeps assistant segments separate when a live tool sits between them", () => {
|
||||
@@ -963,12 +963,12 @@ describe("processTimelineResponse", () => {
|
||||
}).item,
|
||||
} as AgentStreamEventPayload,
|
||||
timestamp: new Date(2101),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 101 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 101, anchorSeq: 101 },
|
||||
},
|
||||
{
|
||||
event: makeAssistantTimelineEvent("after tool", messageId),
|
||||
timestamp: new Date(2102),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 102 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 102, anchorSeq: 102 },
|
||||
},
|
||||
],
|
||||
{ source: "canonical" },
|
||||
@@ -1019,7 +1019,7 @@ describe("processTimelineResponse", () => {
|
||||
id: "assistant-live",
|
||||
text: "canonical prefix continuation",
|
||||
timestamp: new Date(2001),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 101 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 101, anchorSeq: 101 },
|
||||
},
|
||||
],
|
||||
isInitializing: true,
|
||||
@@ -1038,7 +1038,7 @@ describe("processTimelineResponse", () => {
|
||||
);
|
||||
expect(assistants).toHaveLength(1);
|
||||
expect(assistants[0]?.text).toBe("canonical prefix continuation");
|
||||
expect(assistants[0]?.timelineCursor).toEqual({ epoch: "epoch-1", seq: 101 });
|
||||
expect(assistants[0]?.timelineCursor).toEqual({ epoch: "epoch-1", seq: 101, anchorSeq: 100 });
|
||||
});
|
||||
|
||||
it("keeps a canonical live user row newer than the bootstrap page", () => {
|
||||
@@ -1060,7 +1060,7 @@ describe("processTimelineResponse", () => {
|
||||
});
|
||||
expect(live.head[0]).toMatchObject({
|
||||
kind: "user_message",
|
||||
timelineCursor: { epoch: "epoch-1", seq: 101 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 101, anchorSeq: 101 },
|
||||
});
|
||||
|
||||
const result = processTimelineResponse({
|
||||
@@ -1123,7 +1123,7 @@ describe("processTimelineResponse", () => {
|
||||
kind: "user_message",
|
||||
clientMessageId: "client-message-1",
|
||||
messageId: "provider-message-1",
|
||||
timelineCursor: { epoch: "epoch-1", seq: 51 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 51, anchorSeq: 51 },
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2808,7 +2808,7 @@ describe("processTimelineResponse", () => {
|
||||
id: "newest",
|
||||
text: "newest",
|
||||
timestamp: new Date(1000),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 100 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 100, anchorSeq: 100 },
|
||||
},
|
||||
makeSubmittedUserMessage("pending submission", "pending-submission"),
|
||||
],
|
||||
@@ -2886,14 +2886,14 @@ describe("processTimelineResponse", () => {
|
||||
id: "oldest",
|
||||
text: "oldest",
|
||||
timestamp: new Date(1000),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
|
||||
},
|
||||
{
|
||||
kind: "user_message",
|
||||
id: "newest",
|
||||
text: "newest",
|
||||
timestamp: new Date(100_000),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 100 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 100, anchorSeq: 100 },
|
||||
},
|
||||
];
|
||||
|
||||
@@ -2935,7 +2935,7 @@ describe("processTimelineResponse", () => {
|
||||
id: "newest",
|
||||
text: "newest",
|
||||
timestamp: new Date(100_000),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 100 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 100, anchorSeq: 100 },
|
||||
},
|
||||
...(lane === "tail" ? [pending] : []),
|
||||
],
|
||||
@@ -2976,9 +2976,13 @@ describe("processTimelineResponse", () => {
|
||||
{
|
||||
text: "local pending prompt",
|
||||
messageId: "canonical-message",
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
|
||||
},
|
||||
{
|
||||
text: "newest",
|
||||
messageId: undefined,
|
||||
timelineCursor: { epoch: "epoch-1", seq: 100, anchorSeq: 100 },
|
||||
},
|
||||
{ text: "newest", messageId: undefined, timelineCursor: { epoch: "epoch-1", seq: 100 } },
|
||||
],
|
||||
head: [],
|
||||
acknowledgedClientMessageIds: [clientMessageId],
|
||||
@@ -2992,7 +2996,7 @@ describe("processTimelineResponse", () => {
|
||||
{
|
||||
event: makeToolCallTimelineEvent("call-1"),
|
||||
timestamp: new Date(500),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 500 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 500, anchorSeq: 500 },
|
||||
},
|
||||
],
|
||||
{ source: "canonical" },
|
||||
@@ -3038,7 +3042,7 @@ describe("processTimelineResponse", () => {
|
||||
{
|
||||
callId: "call-1",
|
||||
status: "completed",
|
||||
timelineCursor: { epoch: "epoch-1", seq: 500 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 500, anchorSeq: 1 },
|
||||
},
|
||||
]);
|
||||
});
|
||||
@@ -3050,7 +3054,7 @@ describe("processTimelineResponse", () => {
|
||||
...makeAssistantItem("projected response", "loaded-assistant"),
|
||||
messageId: "assistant-message",
|
||||
timestamp,
|
||||
timelineCursor: { epoch: "epoch-1", seq: 500 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 500, anchorSeq: 500 },
|
||||
},
|
||||
];
|
||||
const result = processTimelineResponse({
|
||||
@@ -3100,7 +3104,7 @@ describe("processTimelineResponse", () => {
|
||||
id: "loaded-assistant",
|
||||
text: "projected response",
|
||||
messageId: "assistant-message",
|
||||
timelineCursor: { epoch: "epoch-1", seq: 500 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 500, anchorSeq: 1 },
|
||||
},
|
||||
]);
|
||||
});
|
||||
@@ -3112,7 +3116,7 @@ describe("processTimelineResponse", () => {
|
||||
id: "current-200",
|
||||
text: "current-200",
|
||||
timestamp: new Date(3200),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 200 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 200, anchorSeq: 200 },
|
||||
},
|
||||
];
|
||||
const existingCursor: TimelineCursor = {
|
||||
@@ -3219,7 +3223,7 @@ describe("processTimelineResponse", () => {
|
||||
const currentTail = [
|
||||
{
|
||||
...makeAssistantItem("newer chunk", "assistant-newer"),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 3 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 3, anchorSeq: 3 },
|
||||
},
|
||||
];
|
||||
const existingCursor: TimelineCursor = {
|
||||
@@ -3246,7 +3250,7 @@ describe("processTimelineResponse", () => {
|
||||
expect(result.tail[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
id: "assistant-newer",
|
||||
timelineCursor: { epoch: "epoch-1", seq: 3 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 3, anchorSeq: 3 },
|
||||
}),
|
||||
);
|
||||
expect(result.cursor).toEqual({
|
||||
@@ -3686,7 +3690,7 @@ describe("processAgentStreamEvent", () => {
|
||||
expect.objectContaining({
|
||||
kind: "assistant_message",
|
||||
text: "[System Error] failed",
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42 },
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
|
||||
}),
|
||||
]);
|
||||
});
|
||||
@@ -3933,7 +3937,7 @@ describe("processAgentStreamEvent", () => {
|
||||
expect(getUserTexts(result.head)).toEqual(["live before bootstrap"]);
|
||||
expect(result.head[0]).toMatchObject({
|
||||
kind: "user_message",
|
||||
timelineCursor: { epoch: "epoch-1", seq: 51 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 51, anchorSeq: 51 },
|
||||
});
|
||||
expect(result.cursorChanged).toBe(false);
|
||||
expect(result.cursor).toBeNull();
|
||||
@@ -3968,7 +3972,7 @@ describe("processAgentStreamEvent", () => {
|
||||
clientMessageId: "client-message-1",
|
||||
messageId: "provider-message-1",
|
||||
text: "submitted before bootstrap",
|
||||
timelineCursor: { epoch: "epoch-1", seq: 51 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 51, anchorSeq: 51 },
|
||||
}),
|
||||
]);
|
||||
});
|
||||
@@ -4559,6 +4563,279 @@ describe("createAgentStreamReducerQueue", () => {
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Conversation rewind: A, B, rewind B, C
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("conversation rewind", () => {
|
||||
const rewindB = { seq: 5, retireFromSeq: 3 };
|
||||
|
||||
function loadAB(): { tail: StreamItem[]; head: StreamItem[]; cursor: TimelineCursor } {
|
||||
const result = processTimelineResponse({
|
||||
...baseTimelineInput,
|
||||
isInitializing: true,
|
||||
hasActiveInitDeferred: true,
|
||||
payload: {
|
||||
...baseTimelineInput.payload,
|
||||
direction: "tail",
|
||||
window: { minSeq: 1, maxSeq: 4, nextSeq: 5 },
|
||||
startCursor: { seq: 1 },
|
||||
endCursor: { seq: 4 },
|
||||
entries: [
|
||||
makeTimelineEntry(1, "A", "user_message"),
|
||||
makeTimelineEntry(2, "reply A"),
|
||||
makeTimelineEntry(3, "B", "user_message"),
|
||||
makeTimelineEntry(4, "reply B"),
|
||||
],
|
||||
},
|
||||
});
|
||||
if (!result.cursor) throw new Error("expected a loaded range");
|
||||
return { tail: result.tail, head: result.head, cursor: result.cursor };
|
||||
}
|
||||
|
||||
function live(
|
||||
state: { tail: StreamItem[]; head: StreamItem[]; cursor: TimelineCursor },
|
||||
events: AgentStreamReducerEvent[],
|
||||
) {
|
||||
const result = processAgentStreamEvents({
|
||||
events,
|
||||
currentTail: state.tail,
|
||||
currentHead: state.head,
|
||||
currentCursor: state.cursor,
|
||||
hasAuthoritativeBaseline: true,
|
||||
});
|
||||
return {
|
||||
tail: result.tail,
|
||||
head: result.head,
|
||||
cursor: result.cursor ?? state.cursor,
|
||||
sideEffects: result.sideEffects,
|
||||
};
|
||||
}
|
||||
|
||||
function rewindEvent(retirement: { seq: number; retireFromSeq: number }) {
|
||||
return {
|
||||
event: { type: "rewind" as const, retireFromSeq: retirement.retireFromSeq },
|
||||
seq: retirement.seq,
|
||||
epoch: "epoch-1",
|
||||
timestamp: new Date(1000 + retirement.seq),
|
||||
};
|
||||
}
|
||||
|
||||
const promptC = [
|
||||
makeStreamReducerEvent(makeTimelineEvent("C", "user_message"), 6),
|
||||
makeStreamReducerEvent(makeTimelineEvent("reply C"), 7),
|
||||
];
|
||||
|
||||
function conversation(state: { tail: StreamItem[]; head: StreamItem[] }) {
|
||||
return [...state.tail, ...state.head].map((item) =>
|
||||
item.kind === "user_message" || item.kind === "assistant_message" ? item.text : item.kind,
|
||||
);
|
||||
}
|
||||
|
||||
it("retires B in place, keeps A mounted, and shows C once", () => {
|
||||
const loaded = loadAB();
|
||||
const [promptA, replyA] = loaded.tail;
|
||||
|
||||
const rewound = live(loaded, [rewindEvent(rewindB), ...promptC]);
|
||||
|
||||
expect(conversation(rewound)).toEqual(["A", "reply A", "C", "reply C"]);
|
||||
expect(rewound.tail[0]).toBe(promptA);
|
||||
expect(rewound.tail[1]).toBe(replyA);
|
||||
expect(rewound.cursor).toMatchObject({ epoch: "epoch-1", startSeq: 1, endSeq: 7 });
|
||||
expect(rewound.sideEffects).toEqual([]);
|
||||
});
|
||||
|
||||
it("ignores a duplicate rewind so C is not retired", () => {
|
||||
const rewound = live(loadAB(), [rewindEvent(rewindB), ...promptC]);
|
||||
|
||||
const replayed = live(rewound, [rewindEvent(rewindB)]);
|
||||
|
||||
expect(conversation(replayed)).toEqual(["A", "reply A", "C", "reply C"]);
|
||||
expect(replayed.cursor.endSeq).toBe(7);
|
||||
});
|
||||
|
||||
it("does not let an old page resurrect B after the rewind applied", () => {
|
||||
const rewound = live(loadAB(), [rewindEvent(rewindB), ...promptC]);
|
||||
|
||||
const stale = processTimelineResponse({
|
||||
...baseTimelineInput,
|
||||
currentTail: rewound.tail,
|
||||
currentHead: rewound.head,
|
||||
currentCursor: rewound.cursor,
|
||||
payload: {
|
||||
...baseTimelineInput.payload,
|
||||
direction: "after",
|
||||
window: { minSeq: 1, maxSeq: 4, nextSeq: 5 },
|
||||
startCursor: { seq: 3 },
|
||||
endCursor: { seq: 4 },
|
||||
entries: [makeTimelineEntry(3, "B", "user_message"), makeTimelineEntry(4, "reply B")],
|
||||
},
|
||||
});
|
||||
|
||||
expect(conversation(stale)).toEqual(["A", "reply A", "C", "reply C"]);
|
||||
expect(stale.cursorChanged).toBe(false);
|
||||
});
|
||||
|
||||
it("drops a late live delivery for the retired range", () => {
|
||||
const rewound = live(loadAB(), [rewindEvent(rewindB)]);
|
||||
|
||||
const late = live(rewound, [makeStreamReducerEvent(makeTimelineEvent("late B"), 4)]);
|
||||
|
||||
expect(conversation(late)).toEqual(["A", "reply A"]);
|
||||
});
|
||||
|
||||
it("catches up through a page that only carries the retirement", () => {
|
||||
const loaded = loadAB();
|
||||
|
||||
const caughtUp = processTimelineResponse({
|
||||
...baseTimelineInput,
|
||||
currentTail: loaded.tail,
|
||||
currentHead: loaded.head,
|
||||
currentCursor: loaded.cursor,
|
||||
payload: {
|
||||
...baseTimelineInput.payload,
|
||||
direction: "after",
|
||||
window: { minSeq: 1, maxSeq: 5, nextSeq: 6 },
|
||||
startCursor: { seq: 5 },
|
||||
endCursor: { seq: 5 },
|
||||
entries: [],
|
||||
retirements: [rewindB],
|
||||
},
|
||||
});
|
||||
if (!caughtUp.cursor) throw new Error("expected a loaded range");
|
||||
|
||||
expect(conversation(caughtUp)).toEqual(["A", "reply A"]);
|
||||
expect(caughtUp.cursor.endSeq).toBe(5);
|
||||
expect(caughtUp.sideEffects).not.toContainEqual(expect.objectContaining({ type: "catch_up" }));
|
||||
|
||||
const continued = live({ ...caughtUp, cursor: caughtUp.cursor }, promptC);
|
||||
expect(conversation(continued)).toEqual(["A", "reply A", "C", "reply C"]);
|
||||
});
|
||||
|
||||
it("converges after reconnect from a resume page that crosses the rewind", () => {
|
||||
const loaded = loadAB();
|
||||
|
||||
const resumed = processTimelineResponse({
|
||||
...baseTimelineInput,
|
||||
currentTail: loaded.tail,
|
||||
currentHead: loaded.head,
|
||||
currentCursor: loaded.cursor,
|
||||
payload: {
|
||||
...baseTimelineInput.payload,
|
||||
direction: "tail",
|
||||
window: { minSeq: 1, maxSeq: 7, nextSeq: 8 },
|
||||
startCursor: { seq: 1 },
|
||||
endCursor: { seq: 7 },
|
||||
entries: [
|
||||
makeTimelineEntry(1, "A", "user_message"),
|
||||
makeTimelineEntry(2, "reply A"),
|
||||
makeTimelineEntry(6, "C", "user_message"),
|
||||
makeTimelineEntry(7, "reply C"),
|
||||
],
|
||||
retirements: [rewindB],
|
||||
},
|
||||
});
|
||||
|
||||
expect(conversation(resumed)).toEqual(["A", "reply A", "C", "reply C"]);
|
||||
expect(resumed.tail[0]).toBe(loaded.tail[0]);
|
||||
expect(resumed.cursor).toMatchObject({ endSeq: 7 });
|
||||
});
|
||||
|
||||
it("recovers a rewind that skips past the loaded end", () => {
|
||||
const loaded = loadAB();
|
||||
|
||||
const gapped = live(loaded, [rewindEvent({ seq: 9, retireFromSeq: 3 })]);
|
||||
|
||||
expect(conversation(gapped)).toEqual(["A", "reply A", "B", "reply B"]);
|
||||
expect(gapped.sideEffects).toEqual([
|
||||
{ type: "catch_up", cursor: { epoch: "epoch-1", endSeq: 4 } },
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps an A row whose late update carries a seq inside B's range", () => {
|
||||
const loaded = loadAB();
|
||||
const [promptA, replyA, ...rest] = loaded.tail;
|
||||
const lateTool = hydrateStreamState(
|
||||
[
|
||||
{
|
||||
event: makeToolCallTimelineEvent("call-a"),
|
||||
timestamp: new Date(1002),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 4, anchorSeq: 2 },
|
||||
},
|
||||
],
|
||||
{ source: "canonical" },
|
||||
);
|
||||
const state = { ...loaded, tail: [promptA, replyA, ...lateTool, ...rest] };
|
||||
|
||||
const rewound = live(state, [rewindEvent(rewindB)]);
|
||||
|
||||
expect(conversation(rewound)).toEqual(["A", "reply A", "tool_call"]);
|
||||
});
|
||||
|
||||
it("keeps a tool that started before B when B's prompt is not loaded and the tool updated after B", () => {
|
||||
const toolA = {
|
||||
...makeToolCallTimelineEntry(2, "call-a", "completed", {
|
||||
type: "read",
|
||||
filePath: "/tmp/a.ts",
|
||||
}),
|
||||
seqEnd: 6,
|
||||
sourceSeqRanges: [
|
||||
{ startSeq: 2, endSeq: 2 },
|
||||
{ startSeq: 6, endSeq: 6 },
|
||||
],
|
||||
};
|
||||
const loaded = processTimelineResponse({
|
||||
...baseTimelineInput,
|
||||
isInitializing: true,
|
||||
hasActiveInitDeferred: true,
|
||||
payload: {
|
||||
...baseTimelineInput.payload,
|
||||
direction: "tail",
|
||||
window: { minSeq: 1, maxSeq: 6, nextSeq: 7 },
|
||||
startCursor: { seq: 1 },
|
||||
endCursor: { seq: 6 },
|
||||
entries: [makeTimelineEntry(1, "A", "user_message"), toolA],
|
||||
},
|
||||
});
|
||||
if (!loaded.cursor) throw new Error("expected a loaded range");
|
||||
|
||||
const rewound = live({ tail: loaded.tail, head: loaded.head, cursor: loaded.cursor }, [
|
||||
rewindEvent({ seq: 7, retireFromSeq: 3 }),
|
||||
]);
|
||||
|
||||
expect(conversation(rewound)).toEqual(["A", "tool_call"]);
|
||||
});
|
||||
|
||||
it("keeps C from the live overlay when the first page brings the retirement C followed", () => {
|
||||
const overlay = processAgentStreamEvents({
|
||||
events: [rewindEvent(rewindB), ...promptC],
|
||||
currentTail: [],
|
||||
currentHead: [],
|
||||
currentCursor: undefined,
|
||||
hasAuthoritativeBaseline: false,
|
||||
});
|
||||
|
||||
const initialized = processTimelineResponse({
|
||||
...baseTimelineInput,
|
||||
isInitializing: true,
|
||||
hasActiveInitDeferred: true,
|
||||
currentTail: overlay.tail,
|
||||
currentHead: overlay.head,
|
||||
payload: {
|
||||
...baseTimelineInput.payload,
|
||||
direction: "tail",
|
||||
window: { minSeq: 1, maxSeq: 5, nextSeq: 6 },
|
||||
startCursor: { seq: 1 },
|
||||
endCursor: { seq: 5 },
|
||||
entries: [makeTimelineEntry(1, "A", "user_message"), makeTimelineEntry(2, "reply A")],
|
||||
retirements: [rewindB],
|
||||
},
|
||||
});
|
||||
|
||||
expect(conversation(initialized)).toEqual(["A", "reply A", "C", "reply C"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("turn metrics", () => {
|
||||
const metrics = [
|
||||
{ label: "Model", value: "opus" },
|
||||
@@ -4816,4 +5093,30 @@ describe("turn metrics", () => {
|
||||
|
||||
expect(repeated.tail).toBe(first.tail);
|
||||
});
|
||||
|
||||
it("stamps turn metrics carried on a live timeline event appended by reload", () => {
|
||||
const result = processAgentStreamEvents({
|
||||
events: [
|
||||
makeStreamReducerEvent(makeTimelineEvent("question", "user_message"), 1),
|
||||
makeStreamReducerEvent(
|
||||
{
|
||||
type: "timeline",
|
||||
provider: "claude",
|
||||
item: { type: "assistant_message", text: "Appended reply." },
|
||||
turnMetrics: metrics,
|
||||
},
|
||||
2,
|
||||
),
|
||||
],
|
||||
currentTail: [],
|
||||
currentHead: [],
|
||||
currentCursor: { epoch: "epoch-1", startSeq: 0, endSeq: 0 },
|
||||
hasAuthoritativeBaseline: true,
|
||||
});
|
||||
|
||||
expect(metricsByKind([...result.tail, ...result.head])).toEqual([
|
||||
{ kind: "user_message", turnMetrics: undefined },
|
||||
{ kind: "assistant_message", turnMetrics: metrics },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
import type { AgentMetric, AgentTimelineItem } from "@getpaseo/protocol/agent-types";
|
||||
import type { AgentStreamEventPayload } from "@getpaseo/protocol/messages";
|
||||
import { selectAgentTimelineState, useSessionStore } from "@/stores/session-store";
|
||||
import type { AssistantMessageItem, StreamItem, TodoEntry } from "@/types/stream";
|
||||
import {
|
||||
advanceTimelinePosition,
|
||||
type AssistantMessageItem,
|
||||
type StreamItem,
|
||||
type TimelinePosition,
|
||||
type TodoEntry,
|
||||
} from "@/types/stream";
|
||||
import type { TurnLivenessTransition } from "@/timeline/turn-liveness";
|
||||
import { stampTimelineTurnMetrics } from "@/timeline/turn-metrics";
|
||||
import {
|
||||
@@ -72,6 +78,64 @@ interface TimelineSeqRange {
|
||||
endSeq: number;
|
||||
}
|
||||
|
||||
/** A conversation rewind took the rows anchored in `[retireFromSeq, seq)` out of the conversation. */
|
||||
export interface TimelineRetirement {
|
||||
seq: number;
|
||||
retireFromSeq: number;
|
||||
}
|
||||
|
||||
/** The live form of a retirement; it is sequenced with the stream events around it. */
|
||||
export interface TimelineRewindEvent {
|
||||
type: "rewind";
|
||||
retireFromSeq: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Drops the rows a retirement took out of the conversation: those anchored in
|
||||
* `[retireFromSeq, seq)`. Anchors do not move on update, so an earlier row updated after the
|
||||
* rewound prompt stays, and a row that started after the retirement stays. Items without a
|
||||
* timeline position are local sends the daemon has not echoed and stay.
|
||||
*/
|
||||
function retireRewoundStreamItems(input: {
|
||||
tail: StreamItem[];
|
||||
head: StreamItem[];
|
||||
epoch: string;
|
||||
retirement: TimelineRetirement;
|
||||
}): { tail: StreamItem[]; head: StreamItem[] } {
|
||||
const { tail, head, epoch, retirement } = input;
|
||||
const isRetired = (item: StreamItem) => {
|
||||
const position = item.timelineCursor;
|
||||
return (
|
||||
position?.epoch === epoch &&
|
||||
position.anchorSeq >= retirement.retireFromSeq &&
|
||||
position.anchorSeq < retirement.seq
|
||||
);
|
||||
};
|
||||
const nextTail = tail.filter((item) => !isRetired(item));
|
||||
const nextHead = head.filter((item) => !isRetired(item));
|
||||
return {
|
||||
tail: nextTail.length === tail.length ? tail : nextTail,
|
||||
head: nextHead.length === head.length ? head : nextHead,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a page's retirements to what this client holds. The page's own entries are already
|
||||
* active. Applying a retirement twice changes nothing, since its range is bounded.
|
||||
*/
|
||||
function retireForPage(input: {
|
||||
payload: ProcessTimelineResponseInput["payload"];
|
||||
tail: StreamItem[];
|
||||
head: StreamItem[];
|
||||
}): { tail: StreamItem[]; head: StreamItem[] } {
|
||||
const { payload } = input;
|
||||
let held = { tail: input.tail, head: input.head };
|
||||
for (const retirement of payload.retirements ?? []) {
|
||||
held = retireRewoundStreamItems({ ...held, epoch: payload.epoch, retirement });
|
||||
}
|
||||
return held;
|
||||
}
|
||||
|
||||
function mergeTimelineCoverage(
|
||||
current: TimelineCursor,
|
||||
added: TimelineLoadedRange,
|
||||
@@ -152,6 +216,7 @@ export interface ProcessTimelineResponseInput {
|
||||
hasNewer: boolean;
|
||||
hasOlder: boolean;
|
||||
mergeWindow?: boolean;
|
||||
retirements?: TimelineRetirement[];
|
||||
};
|
||||
currentTail: StreamItem[];
|
||||
currentHead: StreamItem[];
|
||||
@@ -396,7 +461,7 @@ function mergeTimelineWindow(args: {
|
||||
toHydratedEvents: (units: TimelineUnit[]) => Array<{
|
||||
event: AgentStreamEventPayload;
|
||||
timestamp: Date;
|
||||
timelineCursor: { epoch: string; seq: number };
|
||||
timelineCursor: TimelinePosition;
|
||||
}>;
|
||||
}): TimelinePathResult {
|
||||
const { timelineUnits, payload, currentTail, currentHead, currentCursor, toHydratedEvents } =
|
||||
@@ -760,7 +825,7 @@ function replaceLiveAssistantWithProjectedText(params: {
|
||||
head: StreamItem[];
|
||||
event: AgentStreamEventPayload;
|
||||
timestamp: Date;
|
||||
timelineCursor: { epoch: string; seq: number };
|
||||
timelineCursor: TimelinePosition;
|
||||
}): StreamItem[] | null {
|
||||
const { head, event, timestamp, timelineCursor } = params;
|
||||
if (event.type !== "timeline" || event.item.type !== "assistant_message") {
|
||||
@@ -779,7 +844,7 @@ function replaceLiveAssistantWithProjectedText(params: {
|
||||
...current,
|
||||
text: event.item.text,
|
||||
timestamp,
|
||||
timelineCursor,
|
||||
...advanceTimelinePosition(current.timelineCursor, timelineCursor),
|
||||
};
|
||||
return next;
|
||||
}
|
||||
@@ -829,7 +894,7 @@ function reconcileOverlappingProjectedAssistant(params: {
|
||||
...(messageId !== undefined ? { messageId } : {}),
|
||||
text: projectedText,
|
||||
timestamp: unit.timestamp,
|
||||
timelineCursor: { epoch: params.epoch, seq: unit.seqEnd },
|
||||
timelineCursor: { epoch: params.epoch, seq: unit.seqEnd, anchorSeq: unit.seq },
|
||||
};
|
||||
const replaceMatch = (items: StreamItem[], index: number) => {
|
||||
const next = [...items];
|
||||
@@ -946,8 +1011,8 @@ function applyCanonicalForwardUnit(params: {
|
||||
unit: TimelineUnit;
|
||||
epoch: string;
|
||||
}): { tail: StreamItem[]; head: StreamItem[]; acknowledgedClientMessageIds: string[] } {
|
||||
const { event, timestamp, seqEnd } = params.unit;
|
||||
const timelineCursor = { epoch: params.epoch, seq: seqEnd };
|
||||
const { event, timestamp, seq, seqEnd } = params.unit;
|
||||
const timelineCursor: TimelinePosition = { epoch: params.epoch, seq: seqEnd, anchorSeq: seq };
|
||||
if (event.type === "timeline" && event.item.type === "user_message") {
|
||||
const applied = applyStreamEvent({
|
||||
tail: params.tail,
|
||||
@@ -1146,10 +1211,10 @@ function applyAcceptedTimelinePage(input: {
|
||||
});
|
||||
}
|
||||
const olderTail = hydrateStreamState(
|
||||
acceptedUnits.map(({ event, timestamp, seqEnd }) => ({
|
||||
acceptedUnits.map(({ event, timestamp, seq, seqEnd }) => ({
|
||||
event,
|
||||
timestamp,
|
||||
timelineCursor: { epoch: payload.epoch, seq: seqEnd },
|
||||
timelineCursor: { epoch: payload.epoch, seq: seqEnd, anchorSeq: seq },
|
||||
})),
|
||||
{
|
||||
source: "canonical",
|
||||
@@ -1181,7 +1246,12 @@ function applyTimelineIncrementalPath(args: {
|
||||
let cursorChanged = false;
|
||||
const sideEffects: TimelineReducerSideEffect[] = [];
|
||||
|
||||
if (timelineUnits.length === 0 && payload.direction !== "before") {
|
||||
// A forward page of retirements alone still advances the loaded end.
|
||||
if (
|
||||
timelineUnits.length === 0 &&
|
||||
payload.direction !== "before" &&
|
||||
(payload.retirements?.length ?? 0) === 0
|
||||
) {
|
||||
return {
|
||||
tail: currentTail,
|
||||
head: currentHead,
|
||||
@@ -1239,8 +1309,6 @@ export function processTimelineResponse(
|
||||
): ProcessTimelineResponseOutput {
|
||||
const {
|
||||
payload,
|
||||
currentTail,
|
||||
currentHead,
|
||||
currentCursor,
|
||||
isInitializing,
|
||||
hasActiveInitDeferred,
|
||||
@@ -1254,8 +1322,8 @@ export function processTimelineResponse(
|
||||
if (payload.error) {
|
||||
return {
|
||||
commit: "apply",
|
||||
tail: currentTail,
|
||||
head: currentHead,
|
||||
tail: input.currentTail,
|
||||
head: input.currentHead,
|
||||
cursor: currentCursor,
|
||||
cursorChanged: false,
|
||||
older: "unchanged",
|
||||
@@ -1267,6 +1335,13 @@ export function processTimelineResponse(
|
||||
};
|
||||
}
|
||||
|
||||
// Entries are already free of retired rows; the retirements apply to what this client holds.
|
||||
const { tail: currentTail, head: currentHead } = retireForPage({
|
||||
payload,
|
||||
tail: input.currentTail,
|
||||
head: input.currentHead,
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Convert entries to timeline units
|
||||
// ------------------------------------------------------------------
|
||||
@@ -1292,12 +1367,12 @@ export function processTimelineResponse(
|
||||
): Array<{
|
||||
event: AgentStreamEventPayload;
|
||||
timestamp: Date;
|
||||
timelineCursor: { epoch: string; seq: number };
|
||||
timelineCursor: TimelinePosition;
|
||||
}> =>
|
||||
units.map(({ event, timestamp, seqEnd }) => ({
|
||||
units.map(({ event, timestamp, seq, seqEnd }) => ({
|
||||
event,
|
||||
timestamp,
|
||||
timelineCursor: { epoch: payload.epoch, seq: seqEnd },
|
||||
timelineCursor: { epoch: payload.epoch, seq: seqEnd, anchorSeq: seq },
|
||||
}));
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
@@ -1432,7 +1507,7 @@ export function processTimelineResponse(
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface ProcessAgentStreamEventInput {
|
||||
event: AgentStreamEventPayload;
|
||||
event: AgentStreamEventPayload | TimelineRewindEvent;
|
||||
seq: number | undefined;
|
||||
epoch: string | undefined;
|
||||
currentTail: StreamItem[];
|
||||
@@ -1455,7 +1530,7 @@ export interface ProcessAgentStreamEventOutput {
|
||||
}
|
||||
|
||||
export interface AgentStreamReducerEvent {
|
||||
event: AgentStreamEventPayload;
|
||||
event: AgentStreamEventPayload | TimelineRewindEvent;
|
||||
seq: number | undefined;
|
||||
epoch: string | undefined;
|
||||
timestamp: Date;
|
||||
@@ -1573,11 +1648,70 @@ function processTimelineSequencingGate(input: {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a live rewind in sequence with the stream. One that does not follow the loaded end is
|
||||
* stale (already applied, or older than a page this client took) or leaves a gap to catch up.
|
||||
*/
|
||||
function processTimelineRewind(
|
||||
input: ProcessAgentStreamEventInput & { event: TimelineRewindEvent },
|
||||
): ProcessAgentStreamEventOutput {
|
||||
const { event, seq, epoch, currentTail, currentHead, currentCursor } = input;
|
||||
const unchanged: ProcessAgentStreamEventOutput = {
|
||||
tail: currentTail,
|
||||
head: currentHead,
|
||||
changedTail: false,
|
||||
changedHead: false,
|
||||
cursor: null,
|
||||
cursorChanged: false,
|
||||
acknowledgedClientMessageIds: [],
|
||||
sideEffects: [],
|
||||
};
|
||||
if (seq === undefined || epoch === undefined) return unchanged;
|
||||
const decision =
|
||||
input.hasAuthoritativeBaseline === false
|
||||
? "overlay"
|
||||
: classifySessionTimelineSeq({
|
||||
cursor: currentCursor
|
||||
? { epoch: currentCursor.epoch, endSeq: currentCursor.endSeq }
|
||||
: null,
|
||||
epoch,
|
||||
seq,
|
||||
});
|
||||
if (decision === "gap" && currentCursor) {
|
||||
return {
|
||||
...unchanged,
|
||||
sideEffects: [
|
||||
{ type: "catch_up", cursor: { epoch: currentCursor.epoch, endSeq: currentCursor.endSeq } },
|
||||
],
|
||||
};
|
||||
}
|
||||
if (decision !== "accept" && decision !== "init" && decision !== "overlay") return unchanged;
|
||||
const retired = retireRewoundStreamItems({
|
||||
tail: currentTail,
|
||||
head: currentHead,
|
||||
epoch,
|
||||
retirement: { seq, retireFromSeq: event.retireFromSeq },
|
||||
});
|
||||
let cursor: TimelineCursor | null = null;
|
||||
if (decision === "accept" && currentCursor) cursor = { ...currentCursor, endSeq: seq };
|
||||
if (decision === "init") cursor = { epoch, startSeq: seq, endSeq: seq };
|
||||
return {
|
||||
...unchanged,
|
||||
tail: retired.tail,
|
||||
head: retired.head,
|
||||
changedTail: retired.tail !== currentTail,
|
||||
changedHead: retired.head !== currentHead,
|
||||
cursor,
|
||||
cursorChanged: cursor !== null,
|
||||
};
|
||||
}
|
||||
|
||||
export function processAgentStreamEvent(
|
||||
input: ProcessAgentStreamEventInput,
|
||||
): ProcessAgentStreamEventOutput {
|
||||
const event = input.event;
|
||||
if (event.type === "rewind") return processTimelineRewind({ ...input, event });
|
||||
const {
|
||||
event,
|
||||
seq,
|
||||
epoch,
|
||||
currentTail,
|
||||
@@ -1596,7 +1730,7 @@ export function processAgentStreamEvent(
|
||||
});
|
||||
const timelineCursor =
|
||||
event.type === "timeline" && seq !== undefined && epoch !== undefined
|
||||
? { epoch, seq }
|
||||
? { epoch, seq, anchorSeq: seq }
|
||||
: undefined;
|
||||
// ------------------------------------------------------------------
|
||||
// Apply stream event to tail/head
|
||||
@@ -1910,6 +2044,10 @@ export function createSessionAgentStreamReducerQueue(
|
||||
};
|
||||
},
|
||||
commit: (agentId, result, events) => {
|
||||
for (const { event, seq, epoch } of events) {
|
||||
if (event.type !== "rewind" || seq === undefined || epoch === undefined) continue;
|
||||
useSessionStore.getState().recordAgentTimelineRewind(serverId, agentId, { epoch, seq });
|
||||
}
|
||||
if (
|
||||
result.changedTail ||
|
||||
result.changedHead ||
|
||||
|
||||
@@ -237,6 +237,13 @@ function commitProcessedTimeline(input: {
|
||||
const agentId = payload.agentId;
|
||||
const store = useSessionStore.getState();
|
||||
if (result.commit !== "discard") {
|
||||
const latestRewindSeq = Math.max(...(payload.retirements ?? []).map(({ seq }) => seq));
|
||||
if (Number.isFinite(latestRewindSeq)) {
|
||||
store.recordAgentTimelineRewind(serverId, agentId, {
|
||||
epoch: payload.epoch,
|
||||
seq: latestRewindSeq,
|
||||
});
|
||||
}
|
||||
store.applyAgentTimelineResponseState(serverId, agentId, {
|
||||
items: result.tail,
|
||||
head: result.head,
|
||||
@@ -457,8 +464,14 @@ export type ViewedTimelineOwnerPorts = Omit<
|
||||
| "applyCurrentTimeline"
|
||||
>;
|
||||
|
||||
/**
|
||||
* `stale`: the page was served before a rewind this client already applied, so it can hold rows
|
||||
* that rewind retired. Nothing was applied; request the page again.
|
||||
*/
|
||||
export type TimelineResponseOutcome = "applied" | "stale";
|
||||
|
||||
export interface ViewedTimelineOwner extends ViewedTimelineSync {
|
||||
applyTimelineResponse(payload: TimelineResponsePayload): void;
|
||||
applyTimelineResponse(payload: TimelineResponsePayload): TimelineResponseOutcome;
|
||||
/**
|
||||
* Accepts one live stream event. Content is coalesced to the next frame; a turn boundary
|
||||
* commits the turn's queued content before its liveness changes, so the view never shows
|
||||
@@ -468,6 +481,37 @@ export interface ViewedTimelineOwner extends ViewedTimelineSync {
|
||||
flushStreamAgent(agentId: string): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* The latest retirement each chat has seen, live or on a page. Tail, older and prompt-jump pages
|
||||
* are served from active rows at one moment; one served before that retirement can still hold the
|
||||
* rows it retired, and has no retirement to drop them with. Forward pages are sequenced against
|
||||
* the loaded end instead, so they are never stale here.
|
||||
*/
|
||||
function createRetirementHighWater() {
|
||||
const latest = new Map<string, { epoch: string; seq: number }>();
|
||||
function note(agentId: string, retirement: { epoch: string; seq: number }): void {
|
||||
const current = latest.get(agentId);
|
||||
if (current?.epoch === retirement.epoch && current.seq >= retirement.seq) return;
|
||||
latest.set(agentId, retirement);
|
||||
}
|
||||
return {
|
||||
note,
|
||||
notePage(payload: TimelineResponsePayload): void {
|
||||
for (const retirement of payload.retirements ?? []) {
|
||||
note(payload.agentId, { epoch: payload.epoch, seq: retirement.seq });
|
||||
}
|
||||
},
|
||||
servedBefore(payload: TimelineResponsePayload): boolean {
|
||||
const known = latest.get(payload.agentId);
|
||||
return (
|
||||
payload.direction !== "after" &&
|
||||
known?.epoch === payload.epoch &&
|
||||
payload.window.maxSeq < known.seq
|
||||
);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function createViewedTimelineOwner(input: {
|
||||
serverId: string;
|
||||
replica: TimelineReplica;
|
||||
@@ -477,6 +521,7 @@ export function createViewedTimelineOwner(input: {
|
||||
ports: ViewedTimelineOwnerPorts;
|
||||
}): ViewedTimelineOwner {
|
||||
const forcedTailReplacements = new Set<string>();
|
||||
const retirements = createRetirementHighWater();
|
||||
const sync = createViewedTimelineSync({
|
||||
...input.ports,
|
||||
fetchLatestTail: async (agentId) => {
|
||||
@@ -517,6 +562,8 @@ export function createViewedTimelineOwner(input: {
|
||||
return {
|
||||
...sync,
|
||||
applyTimelineResponse(receivedPayload) {
|
||||
if (retirements.servedBefore(receivedPayload)) return "stale";
|
||||
retirements.notePage(receivedPayload);
|
||||
const payload = consumeForcedTimelineTailReplacement(receivedPayload, forcedTailReplacements);
|
||||
const accepted = applyAuthoritativeTimelineResponse({
|
||||
serverId: input.serverId,
|
||||
@@ -526,8 +573,12 @@ export function createViewedTimelineOwner(input: {
|
||||
drainQueuedAgentMessage: input.drainQueuedAgentMessage,
|
||||
});
|
||||
if (accepted) input.replica.timelineUpdated(payload.agentId);
|
||||
return "applied";
|
||||
},
|
||||
applyStreamEvent(agentId, event) {
|
||||
if (event.event.type === "rewind" && event.epoch !== undefined && event.seq !== undefined) {
|
||||
retirements.note(agentId, { epoch: event.epoch, seq: event.seq });
|
||||
}
|
||||
streamQueue.enqueue(agentId, event);
|
||||
const turnLiveness = deriveAgentStreamTurnLiveness([event]);
|
||||
if (turnLiveness.length === 0) return;
|
||||
|
||||
@@ -152,7 +152,7 @@ describe("normalizeStoredHostProfile", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("gives a host stored before appearance existed the default appearance without an icon key", () => {
|
||||
it("gives a host stored before appearance existed the default appearance", () => {
|
||||
const profile = normalizeStoredHostProfile({
|
||||
serverId: "srv_old",
|
||||
connections: [
|
||||
@@ -161,35 +161,18 @@ describe("normalizeStoredHostProfile", () => {
|
||||
});
|
||||
|
||||
expect(profile?.appearance).toEqual({ color: "none", badgeDisplay: null });
|
||||
expect(profile && "icon" in profile.appearance).toBe(false);
|
||||
});
|
||||
|
||||
it("loads a stored appearance the user chose", () => {
|
||||
const profile = normalizeStoredHostProfile({
|
||||
serverId: "srv_new",
|
||||
appearance: { color: "teal", icon: "laptop", badgeDisplay: "icon" },
|
||||
appearance: { color: "teal", badgeDisplay: "icon" },
|
||||
connections: [
|
||||
{ id: "socket:/tmp/paseo.sock", type: "directSocket", path: "/tmp/paseo.sock" },
|
||||
],
|
||||
});
|
||||
|
||||
expect(profile?.appearance).toEqual({ color: "teal", icon: "laptop", badgeDisplay: "icon" });
|
||||
});
|
||||
|
||||
it("preserves an unknown stored icon intact without dropping the saved host", () => {
|
||||
const profile = normalizeStoredHostProfile({
|
||||
serverId: "srv_future_icon",
|
||||
appearance: { color: "violet", icon: "future-device", badgeDisplay: "name" },
|
||||
connections: [
|
||||
{ id: "socket:/tmp/paseo.sock", type: "directSocket", path: "/tmp/paseo.sock" },
|
||||
],
|
||||
});
|
||||
|
||||
expect(profile?.appearance).toEqual({
|
||||
color: "violet",
|
||||
icon: "future-device",
|
||||
badgeDisplay: "name",
|
||||
});
|
||||
expect(profile?.appearance).toEqual({ color: "teal", badgeDisplay: "icon" });
|
||||
});
|
||||
|
||||
it("normalizes stored Remote SSH connection parameters", () => {
|
||||
@@ -357,13 +340,12 @@ describe("upsertHostConnectionInProfiles", () => {
|
||||
});
|
||||
|
||||
expect(profile.appearance).toEqual({ color: "none", badgeDisplay: null });
|
||||
expect("icon" in profile.appearance).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps the appearance the user chose when the host reconnects", () => {
|
||||
const existing: HostProfile = {
|
||||
...makeHost("srv_known"),
|
||||
appearance: { color: "amber", icon: "workstation", badgeDisplay: "hidden" },
|
||||
appearance: { color: "amber", badgeDisplay: "hidden" },
|
||||
connections: [],
|
||||
};
|
||||
|
||||
@@ -373,11 +355,7 @@ describe("upsertHostConnectionInProfiles", () => {
|
||||
connection,
|
||||
});
|
||||
|
||||
expect(profile.appearance).toEqual({
|
||||
color: "amber",
|
||||
icon: "workstation",
|
||||
badgeDisplay: "hidden",
|
||||
});
|
||||
expect(profile.appearance).toEqual({ color: "amber", badgeDisplay: "hidden" });
|
||||
});
|
||||
|
||||
it("replaces a direct connection when its settings change", () => {
|
||||
|
||||
@@ -1009,7 +1009,7 @@ describe("stream reducer canonical tool calls", () => {
|
||||
});
|
||||
|
||||
it("keeps the timeline position on the whole assistant message", () => {
|
||||
const timelineCursor = { epoch: "epoch-1", seq: 42 };
|
||||
const timelineCursor = { epoch: "epoch-1", seq: 42, anchorSeq: 42 };
|
||||
const result = applyStreamEvent({
|
||||
tail: [],
|
||||
head: [],
|
||||
@@ -1890,7 +1890,7 @@ describe("turn lifecycle events", () => {
|
||||
new Date("2025-01-01T15:03:11Z"),
|
||||
{
|
||||
source: "canonical",
|
||||
timelineCursor: { epoch: "epoch-1", seq: 42 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 42, anchorSeq: 42 },
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1902,7 +1902,11 @@ describe("turn lifecycle events", () => {
|
||||
assert.strictEqual(userMessage.messageId, "provider-owned-canonical");
|
||||
assert.strictEqual(userMessage.text, "Analyze this");
|
||||
assert.strictEqual(userMessage.timestamp.getTime(), submittedTimestamp.getTime());
|
||||
assert.deepStrictEqual(userMessage.timelineCursor, { epoch: "epoch-1", seq: 42 });
|
||||
assert.deepStrictEqual(userMessage.timelineCursor, {
|
||||
epoch: "epoch-1",
|
||||
seq: 42,
|
||||
anchorSeq: 42,
|
||||
});
|
||||
assert.deepStrictEqual(userMessage.images, [image]);
|
||||
assert.deepStrictEqual(userMessage.attachments, [attachment]);
|
||||
});
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user