mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-25 17:55:18 +00:00
Compare commits
32
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bd4e817951 | ||
|
|
9f999bd570 | ||
|
|
bf10ea8732 | ||
|
|
a8528ad3d2 | ||
|
|
2c661fb076 | ||
|
|
531f6e549d | ||
|
|
e32564f2bc | ||
|
|
0258d6752e | ||
|
|
de5f139d33 | ||
|
|
372c1ba949 | ||
|
|
4dc1730a62 | ||
|
|
2581f2af45 | ||
|
|
6973c48d7e | ||
|
|
9dd0cbc146 | ||
|
|
f088fa5049 | ||
|
|
5dcd1e1e57 | ||
|
|
7ba54499d9 | ||
|
|
cbd5b7a73b | ||
|
|
8e88ce3a56 | ||
|
|
fb59e58ef1 | ||
|
|
825fa04467 | ||
|
|
8338e77f46 | ||
|
|
e5d81304f7 | ||
|
|
6b0fbfc640 | ||
|
|
b4e4803df2 | ||
|
|
3153f6f94a | ||
|
|
ecf8c812cd | ||
|
|
ab4bd6d59d | ||
|
|
2547edefcc | ||
|
|
5c82a2e999 | ||
|
|
60943dde1c | ||
|
|
e52bb6e3c4 |
@@ -131,6 +131,29 @@ jobs:
|
||||
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
|
||||
run: npm run typecheck:examples --workspace=@getpaseo/client
|
||||
|
||||
# Plugin process launches and launch wraps quote for cmd.exe, which only real Windows checks.
|
||||
sdk-tests-windows:
|
||||
name: sdk-tests (windows-latest)
|
||||
needs: changes
|
||||
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: "npm"
|
||||
|
||||
- name: Install dependencies
|
||||
run: node scripts/npm-retry.mjs ci
|
||||
|
||||
- name: Build plugin SDK
|
||||
run: npm run build:relay && npm run build:client && npm run build:plugin
|
||||
|
||||
- name: Run plugin SDK tests
|
||||
run: npm run test --workspace=@getpaseo/plugin
|
||||
|
||||
# The locked Playwright installers do not support ubuntu-latest's Ubuntu 26.04.
|
||||
typecheck:
|
||||
name: typecheck
|
||||
|
||||
@@ -54,7 +54,6 @@ 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 |
|
||||
|
||||
@@ -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. Resume does not read provider history when the agent already has a timeline;
|
||||
see [owned history](timeline-sync.md#owned-history).
|
||||
same Paseo agent ID. Provider history is not appended again when the canonical timeline is already
|
||||
primed.
|
||||
|
||||
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,8 +256,7 @@ 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. The timeline and the provider children stay, so an archived chat reads them without its
|
||||
provider; deleting the agent removes them.
|
||||
children.
|
||||
|
||||
`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.
|
||||
|
||||
@@ -353,8 +352,6 @@ 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,7 +94,6 @@ 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 |
|
||||
@@ -403,7 +402,7 @@ initializing → idle ⇄ running
|
||||
client-side dedup; the default fetch page is 200 items.
|
||||
- Timeline row `timestamp` values are canonical daemon-owned timestamps. Providers may supply original replay timestamps, but clients must not guess timestamp trust or hide time UI based on local clock heuristics.
|
||||
- Events stream to connected clients in real time; correctness is backed by authoritative timeline fetches and paged-to-completion catch-up.
|
||||
- Agent state persists to `$PASEO_HOME/agents/{cwd-with-dashes}/{agent-id}.json`. That storage path is derived from `cwd`, not from workspace id. Timeline rows persist in the daemon database, `$PASEO_HOME/paseo.db`. They are the transcript authority after the first import of provider history. See [owned history](timeline-sync.md#owned-history).
|
||||
- Agent state persists to `$PASEO_HOME/agents/{cwd-with-dashes}/{agent-id}.json`. Timeline rows are runtime memory; provider history is the durable transcript authority and resumed agents rebuild from it. That storage path is derived from `cwd`, not from workspace id.
|
||||
|
||||
## Right-sidebar boundary: directory-backed vs workspace-owned
|
||||
|
||||
@@ -479,7 +478,6 @@ Providers that can accept native tool definitions should set `supportsNativePase
|
||||
```
|
||||
$PASEO_HOME/
|
||||
├── agents/{cwd-with-dashes}/{agent-id}.json # Agent record
|
||||
├── paseo.db # Daemon database (SQLite): agent timelines
|
||||
├── projects/projects.json # Project registry
|
||||
├── projects/workspaces.json # Workspace registry
|
||||
├── projects/icons/ # Custom project icon images
|
||||
|
||||
+1
-41
@@ -34,7 +34,7 @@ Workspace archive runs lifecycle teardown from the exact `cwd` but removes only
|
||||
`worktreeRoot` after its last active reference disappears. Worktree recovery recreates that backing
|
||||
checkout from `mainRepoRoot`, then restores the relative path from `worktreeRoot` to `cwd`.
|
||||
|
||||
Paseo persists most stores as JSON files, and agent timelines in the [daemon database](#daemon-database). JSON data is validated at runtime with Zod schemas. Most JSON stores write atomically (write to temp file, then rename); a few still use plain `writeFile` — see each section. JSON stores have no schema-versioning/migration framework — schemas rely on optional fields with defaults for forward compatibility, with a small amount of inline normalization in `persisted-config.ts` for legacy provider/speech entries.
|
||||
Paseo uses **file-based JSON persistence** instead of a traditional database. All data is validated at runtime with Zod schemas. Most stores write atomically (write to temp file, then rename); a few still use plain `writeFile` — see each section. There is no schema-versioning/migration framework — schemas rely on optional fields with defaults for forward compatibility, with a small amount of inline normalization in `persisted-config.ts` for legacy provider/speech entries.
|
||||
|
||||
All server-side stores live under `$PASEO_HOME` (defaults to `~/.paseo`).
|
||||
|
||||
@@ -53,7 +53,6 @@ $PASEO_HOME/
|
||||
├── daemon-keypair.json # E2EE keypair for relay (mode 0600)
|
||||
├── paseo.pid # Daemon PID lock file
|
||||
├── local-credential # Per-run local client credential (mode 0600)
|
||||
├── paseo.db # Daemon database (SQLite, with -wal and -shm files)
|
||||
├── daemon.log # Default log file (path configurable)
|
||||
├── agents/
|
||||
│ └── {sanitized-cwd}/
|
||||
@@ -182,45 +181,6 @@ Terminal activity contributes to the workspace status bucket **per `workspaceId`
|
||||
|
||||
---
|
||||
|
||||
## Daemon database
|
||||
|
||||
`$PASEO_HOME/paseo.db` is one SQLite file that the daemon opens at startup with `node:sqlite`
|
||||
(`packages/server/src/server/database/`). Agent timelines are its only store today. Each store is a
|
||||
`SchemaModule`: its own table-name prefix and an append-only list of migrations.
|
||||
|
||||
- **Migrations.** Startup runs every module's pending migrations in one transaction, so a failed
|
||||
migration leaves the file as it was. `schema_versions` records each module's version and
|
||||
`min_reader_version`. Mark a migration `breaking` when an older daemon cannot read the result,
|
||||
for example a dropped or renamed column. An older daemon then refuses to start with
|
||||
`DatabaseSchemaTooNewError`. Additive migrations leave older daemons working, and they ignore
|
||||
modules they do not know. This matters because the app and the daemon update separately, and a
|
||||
user can run an older daemon on the same `$PASEO_HOME`.
|
||||
- **Failure.** A file that SQLite cannot open stops the daemon with `DatabaseOpenError`, which
|
||||
names the path. The daemon does not delete or recreate the file.
|
||||
- **Access.** The file holds every prompt and reply, so the daemon sets it and its `-wal` and `-shm`
|
||||
files to mode `0600` on every open. SQLite gives the WAL files it creates the mode of the database
|
||||
file.
|
||||
- **Durability.** The database uses WAL with `synchronous = NORMAL`. A power loss can drop the
|
||||
last commits but does not corrupt the file.
|
||||
- **Checkpoints.** A checkpoint syncs the file to disk and takes up to 100 ms. SQLite's
|
||||
auto-checkpoint runs it on the committing thread, which stalled the event loop during streaming.
|
||||
The daemon turns it off and checkpoints from a worker thread with its own connection. If the
|
||||
worker exits, the daemon turns auto-checkpoint back on.
|
||||
- **Transactions.** `write` and `read` callbacks are synchronous, so a transaction never spans an
|
||||
`await` and transactions never interleave.
|
||||
- **Node.** `node:sqlite` needs Node 22.16 or later. Node 22 prints an experimental warning once,
|
||||
when the daemon opens the database.
|
||||
|
||||
### Agent timelines
|
||||
|
||||
`AgentTimeline` owns each agent's history, and its SQLite backend stores the projected rows, the
|
||||
source ranges, retirements, the open rewind, and provider children in `timeline_*` tables. The text
|
||||
of a streamed assistant or reasoning message is stored as one chunk per source event, beside its
|
||||
row, so a chunk never rewrites the message. An earlier file store rewrote the whole transcript on
|
||||
every update. See [owned history](timeline-sync.md#owned-history).
|
||||
|
||||
---
|
||||
|
||||
## 2. Daemon Configuration
|
||||
|
||||
**Path:** `$PASEO_HOME/config.json`
|
||||
|
||||
+64
-2
@@ -462,8 +462,55 @@ Server entries register async handlers with `server.addHook(name, handler)`, ret
|
||||
function. Names follow `subject.operation.position`, ending in `before` or `after`. Waiting is a per-hook
|
||||
registry property, independent of position. The [hooks reference](../public-docs/plugins/hooks.md)
|
||||
owns payloads, ordering, failure behavior, and examples. `agent.create.before` edits saved
|
||||
configuration; `agent.open.before` contributes launch-only `env`, `tools`, and `mcpServers` on
|
||||
every open. Executable tool definitions stay in the plugin process; only metadata crosses the boundary.
|
||||
configuration; `agent.open.before` contributes launch-only `env`, `tools`, `mcpServers`, and a
|
||||
[launch wrap](#launch-wrap) on every open. Executable tool definitions stay in the plugin process; only metadata crosses the boundary.
|
||||
`packages/server/src/server/plugins/session-attachments.ts` records what each plugin contributed to
|
||||
each live session. A plugin start, stop, or reload reruns only that plugin's callback per session,
|
||||
swaps its tools in place, and reopens a session only when its launch would differ. A reopen closes
|
||||
the provider process, so a reload must not reopen agents the plugin does not change.
|
||||
|
||||
### Launch wrap
|
||||
|
||||
An `agent.open.before` result can carry `wrap: [executable, ...args]`. The provider then starts that
|
||||
session's harness as `[...wrap, command, ...args]` with the final hook env. It starts with no shell,
|
||||
except Windows script launchers, which go through cmd.exe like any provider launcher
|
||||
(`spawnProcess` quotes each argument). An argument with spaces stays one element. `executable` must
|
||||
be an absolute path.
|
||||
The wrap is never saved on the agent; every open asks the hooks again, and a plugin session reopen
|
||||
reuses the wrap it opened with.
|
||||
|
||||
- **Support is a provider property.** The provider snapshot entry carries `launchWrap: true` when the
|
||||
provider can apply a wrap. Read it in `agent.create.before` with `paseo.providers.snapshot()`; an
|
||||
absent field means unsupported, which is also what a host without this feature reports. Core
|
||||
providers declare it in the provider contract table in `provider-registry.ts`; every core provider
|
||||
that starts a local harness declares it, and custom ACP providers and providers that extend a core
|
||||
one inherit it. A plugin provider declares `ProviderRegistration.launchWrap`;
|
||||
`runAcpProvider({ command })` sets it, a connector declares it itself (Muse Code does). The declaration travels with the
|
||||
registration metadata, so it is in the snapshot before the provider first connects.
|
||||
- **One wrap per open.** A later hook, in the same plugin or a later one, may omit the wrap or return
|
||||
the same value. A different value fails the open.
|
||||
- **Fail closed.** `buildLaunchContext` admits a wrapped open before any session harness starts. It
|
||||
throws `LaunchWrapUnsupportedError` (`code: "launch_wrap_unsupported"`) when the provider does not
|
||||
declare support, or when a plugin provider's live connection lacks `session.launch_wrap`. A host
|
||||
that predates `wrap` rejects the key: the hook result schema is strict. A missing launcher fails the
|
||||
spawn; nothing retries the bare command.
|
||||
|
||||
Once an open selects a wrap, a supported provider runs that session's harness through it or fails
|
||||
before starting the harness. Every provider starts through `spawnProcess({ wrap })`, which owns the
|
||||
argv and Windows launcher handling; `applyLaunchWrap` covers the launches that do not go through it
|
||||
(pty terminals, MCP stdio transports, worktree commands). The wrap also covers what Paseo starts for
|
||||
the session: stdio MCP servers Paseo hosts for the agent (OMP, OpenCode v2), Pi's MCP probe, and ACP
|
||||
client terminals. OpenCode shares one server between sessions, so a wrapped session gets a dedicated
|
||||
server instead; an explicitly configured external OpenCode server cannot be wrapped and the open
|
||||
fails. The guarantee does not cover:
|
||||
|
||||
1. Paseo's host terminal tools (`create_terminal`, `send_terminal_keys`) run outside the wrap.
|
||||
2. Work before the open hook runs unwrapped: draft command and control discovery, and the catalog
|
||||
lookup during create when no model is set.
|
||||
3. Host-side operations run unwrapped: availability and capability probes (the ACP connection's
|
||||
initialize probe included), catalog and session listing, version and update commands, usage
|
||||
queries, and Codex native archive and unarchive.
|
||||
4. Losing the plugin that chose the wrap is not covered: a later open without it runs unwrapped.
|
||||
|
||||
Worktree placement is resolved before Git source planning, so a hook can change the branch and base
|
||||
without undoing fetched refs. Restores use the recorded destination and bypass creation hooks.
|
||||
@@ -483,6 +530,17 @@ change requests; `remove` and `restore` fall back to built-in Git when the plugi
|
||||
[worktree managers reference](../public-docs/plugins/reference.md#worktree-managers) and
|
||||
`plugin-examples/worktrunk`.
|
||||
|
||||
`terminal.create.before` runs in `withTerminalCreateHook`, which wraps the daemon's one terminal manager, so every creation path is covered and adopted terminals are not; callers pass an `origin` to name the source. `command.run.before` runs inside the setup and teardown runners through `commandRunHook`. Setup and archive dependencies take `lifecycle` as a required field so a new caller cannot skip the hook by omission; pass `null` only where no plugins run.
|
||||
|
||||
Both hooks change only `env` and a [launch wrap](#launch-wrap); `keepSelectedWrap` in the lifecycle
|
||||
module applies the one-wrap rule to all three wrap hooks. The terminal wrap becomes the terminal's
|
||||
`command` and `args` in `withTerminalCreateHook`, so the terminal worker protocol does not change and
|
||||
no previous-version adapter is needed. A default-shell terminal resolves the shell there through
|
||||
`default-terminal-shell.ts`, which stays apart from `terminal.ts` so the daemon does not load node-pty.
|
||||
The wrapped shell starts without Paseo's shell integration, which is why a wrapped script does not
|
||||
report command completion. A setup or teardown wrap goes in front of the
|
||||
`buildStringCommandShellInvocation` argv.
|
||||
|
||||
Emit from the operation owner, not a client subscription. Provider history replay must not trigger
|
||||
live hooks. Notifications must not be awaited inside agent mutations: a handler can send a prompt
|
||||
or answer a permission through its own daemon session. Awaiting it there deadlocks that command.
|
||||
@@ -582,6 +640,10 @@ persistence. Re-read credentials and provider-owned configuration on `session.op
|
||||
daemon launch from `connect` and the per-session env and MCP servers from `session.open`. There is
|
||||
no provider reload input.
|
||||
|
||||
Declare `ProviderRegistration.launchWrap: true` when every session spawns its own harness and can
|
||||
run it as `[...config.wrap, command, ...args]`; offer `session.launch_wrap` on the connection. See
|
||||
[Launch wrap](#launch-wrap). `runAcpProvider({ command })` does both.
|
||||
|
||||
For an ACP command, register `runAcpProvider({ id, label, command })` from
|
||||
`@getpaseo/plugin/server/acp`. The shim builds the standard row for each ACP tool `kind`
|
||||
(`acp-internal/tool-call-detail.ts`). Its transformer hooks cover narrow vendor differences; do not translate the
|
||||
|
||||
+11
-68
@@ -5,9 +5,15 @@ 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.
|
||||
|
||||
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 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.
|
||||
|
||||
The invariants are:
|
||||
|
||||
@@ -26,50 +32,6 @@ bounded item is used for runtime timeline rows and live stream events. Provider
|
||||
applies the same rule so reopening an agent cannot restore an oversized payload. Fetches apply it
|
||||
again to assistant and reasoning rows the projection merges from many chunks.
|
||||
|
||||
## Owned history
|
||||
|
||||
The daemon owns each agent's history in `AgentTimeline`
|
||||
(`packages/server/src/server/agent/timeline/`): one ordered history per agent, with each provider
|
||||
child's descriptor and history in a child scope of the same agent. Each source event advances the
|
||||
stream sequence, then replaces the previous tool state or merges into the current text item.
|
||||
Intermediate payloads are never retained for history or catch-up.
|
||||
|
||||
History is append-only: rewind, import, reload and archive never delete or rewrite a row. Only
|
||||
deleting the agent, or a provider removing one of its own children, deletes history.
|
||||
|
||||
- **Rewind** retires a range of rows. They leave the conversation and stay stored, in the same
|
||||
epoch. See [Rewind retires rows](#rewind-retires-rows).
|
||||
- **Provider history** is imported only into an agent that has no history. After that, resume
|
||||
does not read it. Reload agent and Unarchive require the provider history to start with the
|
||||
same prompt IDs and text in order. They then append whole new turns, starting at the next
|
||||
prompt. Existing replies, including partial replies, stay as recorded. If the prompts differ,
|
||||
for example because the provider stored expanded attachment text, the chat stays unchanged and
|
||||
Paseo reports a mismatch. A provider child Paseo already holds, listed or retired, is never imported again.
|
||||
- **Archive and reload** keep the history and the provider children. An archived chat reads them
|
||||
without its provider. Opening a stored agent that has no provider session to resume starts its
|
||||
first session on the same history.
|
||||
- **Delete** removes the agent's history and every child's, retired ones included, before the
|
||||
agent record. If the history cannot be removed, the request fails and the agent stays listed. The
|
||||
user can keep using it and delete it again.
|
||||
|
||||
`epoch` is the stored history's identity, minted once when the history is created.
|
||||
|
||||
`AgentTimeline` serializes every operation of one agent, child scopes included, and keeps its
|
||||
state in an `AgentTimelineBackend`: the sequence, the rows and retirements, prompt identities, the
|
||||
open rewind, and the children. The backend contract suite is `agent-timeline.test.ts`, run over
|
||||
`TIMELINE_CONTRACT_BACKENDS` in `timeline/testing.ts`. The daemon uses the SQLite backend in the
|
||||
[daemon database](data-model.md#daemon-database). History, retirements, the open rewind, and
|
||||
provider children survive a daemon restart in the same epoch, so clients keep their cursors. A
|
||||
closed or archived agent holds no history in memory. Each fetch reads the page from the database
|
||||
and starts no provider. An internal agent, such as the one that writes a commit message, keeps its
|
||||
history in a memory backend instead, so it leaves nothing on disk. The memory backend also serves
|
||||
tests.
|
||||
|
||||
An open rewind is stored with the history. Resuming an agent whose history holds one settles it
|
||||
before the agent takes prompts: a recorded provider cut is committed, and an unknown outcome is
|
||||
judged from the resumed provider history. When that history proves nothing, the rewind stays open
|
||||
and the agent refuses prompts with the unknown-outcome error.
|
||||
|
||||
## Presence is not delivery
|
||||
|
||||
Client heartbeat reports presence:
|
||||
@@ -206,7 +168,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 or epoch change atomically replaces stale canonical history with the
|
||||
- A true middle gap, epoch change, or rewind 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.
|
||||
|
||||
@@ -219,24 +181,6 @@ 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
|
||||
@@ -401,7 +345,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 replaces history and
|
||||
rows because a provider may never echo them. A known epoch change or rewind 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.
|
||||
@@ -417,7 +361,6 @@ 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`
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
sha256-IAhKhkolW4xvFvMaAEFdhYvPAhTm2azsqbGMKCKL3q0=
|
||||
sha256-TAVzJzziWDAapQkG4TLkLzOlodkdFNKSl3y/Tm9HB28=
|
||||
|
||||
Generated
+1
-20
@@ -45,9 +45,6 @@
|
||||
"react-dom": "19.2.3",
|
||||
"typescript": "^5.9.3",
|
||||
"ws": "^8.20.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.16.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@0no-co/graphql.web": {
|
||||
@@ -39722,9 +39719,6 @@
|
||||
"typescript": "^5.2.2",
|
||||
"vitest": "^4.1.6",
|
||||
"zx": "^8.8.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.16.0"
|
||||
}
|
||||
},
|
||||
"packages/cli/node_modules/@vitest/expect": {
|
||||
@@ -40652,7 +40646,7 @@
|
||||
"@playwright/test": "^1.56.1",
|
||||
"@types/express": "^4.17.20",
|
||||
"@types/markdown-it": "^14.2.0",
|
||||
"@types/node": "^22.16.0",
|
||||
"@types/node": "^20.9.0",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@types/uuid": "^9.0.7",
|
||||
"@types/ws": "^8.5.8",
|
||||
@@ -40660,9 +40654,6 @@
|
||||
"cross-env": "^10.1.0",
|
||||
"tsx": "^4.6.0",
|
||||
"vitest": "^4.1.6"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.16.0"
|
||||
}
|
||||
},
|
||||
"packages/server/node_modules/@esbuild/aix-ppc64": {
|
||||
@@ -41110,16 +41101,6 @@
|
||||
"@types/mdurl": "^2"
|
||||
}
|
||||
},
|
||||
"packages/server/node_modules/@types/node": {
|
||||
"version": "22.20.5",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz",
|
||||
"integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"undici-types": "~6.21.0"
|
||||
}
|
||||
},
|
||||
"packages/server/node_modules/@vitest/expect": {
|
||||
"version": "4.1.6",
|
||||
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.6.tgz",
|
||||
|
||||
@@ -169,8 +169,5 @@
|
||||
"tiny-async-pool": {
|
||||
"semver@^5": "5.7.2"
|
||||
}
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.16.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,13 +13,6 @@ 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,
|
||||
@@ -55,102 +48,26 @@ 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 prompt in place on every open client and keeps a human draft", async ({
|
||||
test("rewinds a submitted prompt without replaying history and preserves a human draft", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(150_000);
|
||||
test.setTimeout(90_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);
|
||||
const retainedMessage = await completeSubmittedTurn(page, agent, retainedPrompt);
|
||||
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,
|
||||
@@ -159,92 +76,19 @@ test.describe("Agent message rewind", () => {
|
||||
await blurComposerInput(page);
|
||||
rewindCompletion.clearTimelineStreamCount();
|
||||
|
||||
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;
|
||||
});
|
||||
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 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]);
|
||||
});
|
||||
await expect(page.getByTestId("user-message").filter({ hasText: rewoundPrompt })).toHaveCount(
|
||||
0,
|
||||
);
|
||||
await expectComposerDraft(page, preservedDraft);
|
||||
await expectComposerNotFocused(page);
|
||||
await expectNearBottom(page);
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { expect, test } from "../support/fixtures";
|
||||
import { gotoAppShell } from "../support/helpers/app";
|
||||
import {
|
||||
chooseProjectWithKeyboard,
|
||||
connectNewWorkspaceDaemonClient,
|
||||
expectNewWorkspaceControlsEnabled,
|
||||
expectNewWorkspaceProjectSelected,
|
||||
@@ -176,6 +177,33 @@ test.describe("New workspace entry points", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("choosing a project returns focus to the composer, even when the picker was opened by clicking it", async ({
|
||||
page,
|
||||
}) => {
|
||||
const projectA: SeededWorkspace = await seedWorkspace({ repoPrefix: "entry-focus-a-" });
|
||||
const projectB: SeededWorkspace = await seedWorkspace({ repoPrefix: "entry-focus-b-" });
|
||||
|
||||
try {
|
||||
await gotoAppShell(page);
|
||||
await waitForSidebarHydration(page);
|
||||
await openGlobalNewWorkspaceComposer(page);
|
||||
const composer = page.getByRole("textbox", { name: "Message agent..." });
|
||||
|
||||
await page.getByTestId("new-workspace-project-picker-trigger").click();
|
||||
await chooseProjectWithKeyboard(page, projectB.projectDisplayName);
|
||||
await expectNewWorkspaceProjectSelected(page, projectB.projectDisplayName);
|
||||
await expect(composer).toBeFocused();
|
||||
|
||||
await page.keyboard.press("Control+N");
|
||||
await chooseProjectWithKeyboard(page, projectA.projectDisplayName);
|
||||
await expectNewWorkspaceProjectSelected(page, projectA.projectDisplayName);
|
||||
await expect(composer).toBeFocused();
|
||||
} finally {
|
||||
await projectA.cleanup();
|
||||
await projectB.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps the in-progress form when the remembered workspace is archived elsewhere", async ({
|
||||
page,
|
||||
}) => {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { expect, test, type Page } from "../support/fixtures";
|
||||
import { gotoAppShell } from "../support/helpers/app";
|
||||
import { waitForSidebarHydration } from "../support/helpers/workspace-ui";
|
||||
import {
|
||||
chooseProjectWithKeyboard,
|
||||
expectNewWorkspaceDraft,
|
||||
fillNewWorkspaceDraft,
|
||||
openNewWorkspaceComposer,
|
||||
@@ -109,6 +110,27 @@ test.describe("New workspace: launching a terminal", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("with a profile that takes no prompt, choosing a project keeps focus on the Project field", async ({
|
||||
page,
|
||||
}) => {
|
||||
await gotoAppShell(page);
|
||||
await waitForSidebarHydration(page);
|
||||
await openNewWorkspaceComposer(page, {
|
||||
projectKey: workspace.projectKey,
|
||||
projectDisplayName: workspace.projectDisplayName,
|
||||
});
|
||||
await selectLaunchOption(page, BARE_PROFILE.id);
|
||||
await expect(terminalPromptInput(page)).toHaveCount(0);
|
||||
|
||||
// The read-only command preview has nothing to type into, so the picker
|
||||
// hands focus back to the field that opened it.
|
||||
const projectTrigger = page.getByTestId("new-workspace-project-picker-trigger");
|
||||
await projectTrigger.focus();
|
||||
await page.keyboard.press("Enter");
|
||||
await chooseProjectWithKeyboard(page, workspace.projectDisplayName);
|
||||
await expect(projectTrigger).toBeFocused();
|
||||
});
|
||||
|
||||
test("switching terminal profiles restores the prompt and its fullscreen affordance", async ({
|
||||
page,
|
||||
}) => {
|
||||
|
||||
@@ -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, 0);
|
||||
await expectUserMessageCount(page, 1);
|
||||
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, 1);
|
||||
await expectUserMessageCount(page, 2);
|
||||
|
||||
await fillComposerDraft(page, "");
|
||||
await composerLocator(page).evaluate((element) => element.blur());
|
||||
@@ -254,19 +254,7 @@ test.describe("Rewind sheet", () => {
|
||||
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
|
||||
await expectComposerDraft(page, "");
|
||||
await expectComposerNotFocused(page);
|
||||
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 expectUserMessageCount(page, 2);
|
||||
|
||||
await fillComposerDraft(page, "");
|
||||
await composerLocator(page).evaluate((element) => element.blur());
|
||||
@@ -277,7 +265,7 @@ test.describe("Rewind sheet", () => {
|
||||
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
|
||||
await expectComposerDraft(page, replacementPrompt);
|
||||
await expectComposerFocused(page);
|
||||
await expectUserMessageCount(page, 0);
|
||||
await expectUserMessageCount(page, 1);
|
||||
} finally {
|
||||
await session.cleanup();
|
||||
}
|
||||
|
||||
@@ -31,8 +31,6 @@ export interface RewindCompletionGate {
|
||||
clearTimelineStreamCount(): void;
|
||||
release(): void;
|
||||
timelineStreamCount(): number;
|
||||
/** Timeline reads this page sent since the last clear. */
|
||||
timelineFetchCount(): number;
|
||||
waitForDelayedResponse(): Promise<void>;
|
||||
}
|
||||
|
||||
@@ -188,20 +186,12 @@ 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) => {
|
||||
@@ -210,16 +200,7 @@ export async function holdRewindCompletion(
|
||||
|
||||
await page.routeWebSocket(daemonWsRoutePattern(), (ws) => {
|
||||
const server = ws.connectToServer();
|
||||
ws.onMessage((message) => {
|
||||
const sessionMessage = getSessionMessage(message);
|
||||
if (
|
||||
sessionMessage?.type === "fetch_agent_timeline_request" &&
|
||||
sessionMessage.agentId === agentId
|
||||
) {
|
||||
timelineFetchCount += 1;
|
||||
}
|
||||
server.send(message);
|
||||
});
|
||||
ws.onMessage((message) => server.send(message));
|
||||
server.onMessage((message) => {
|
||||
const sessionMessage = getSessionMessage(message);
|
||||
const payload = sessionMessage ? getPayload(sessionMessage) : null;
|
||||
@@ -235,11 +216,11 @@ export async function holdRewindCompletion(
|
||||
}
|
||||
if (
|
||||
!released &&
|
||||
sessionMessage &&
|
||||
REWIND_COMPLETION_MESSAGES.has(String(sessionMessage.type)) &&
|
||||
(sessionMessage?.type === "agent.rewind.response" ||
|
||||
sessionMessage?.type === "agent.timeline.replacement") &&
|
||||
payload?.agentId === agentId
|
||||
) {
|
||||
// The rewind also signals completion and removes the rewound row/menu.
|
||||
// The replacement 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?.();
|
||||
@@ -252,7 +233,6 @@ export async function holdRewindCompletion(
|
||||
return {
|
||||
clearTimelineStreamCount() {
|
||||
timelineStreamCount = 0;
|
||||
timelineFetchCount = 0;
|
||||
},
|
||||
release() {
|
||||
released = true;
|
||||
@@ -261,7 +241,6 @@ export async function holdRewindCompletion(
|
||||
}
|
||||
},
|
||||
timelineStreamCount: () => timelineStreamCount,
|
||||
timelineFetchCount: () => timelineFetchCount,
|
||||
waitForDelayedResponse: () => delayedResponse,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -243,6 +243,14 @@ export async function openNewWorkspaceProjectPickerWithShortcut(
|
||||
await expect(searchInput).toBeFocused();
|
||||
}
|
||||
|
||||
export async function chooseProjectWithKeyboard(page: Page, projectName: string): Promise<void> {
|
||||
const searchInput = page.getByPlaceholder("Search projects");
|
||||
await expect(searchInput).toBeFocused({ timeout: 30_000 });
|
||||
await page.keyboard.type(projectName);
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(searchInput).toBeHidden({ timeout: 10_000 });
|
||||
}
|
||||
|
||||
export async function expectNewWorkspaceProjectSelected(
|
||||
page: Page,
|
||||
projectDisplayName: string,
|
||||
|
||||
@@ -56,7 +56,6 @@ export function ChatFind({
|
||||
agentId,
|
||||
serverId,
|
||||
epoch,
|
||||
rewindSeq,
|
||||
items,
|
||||
viewportRef,
|
||||
revealLoadedMessage,
|
||||
@@ -96,8 +95,8 @@ export function ChatFind({
|
||||
);
|
||||
const state = useSyncExternalStore(model.subscribe, model.getSnapshot, model.getSnapshot);
|
||||
useEffect(() => {
|
||||
model.updateHistory(epoch, items, rewindSeq);
|
||||
}, [model, epoch, items, rewindSeq]);
|
||||
model.updateHistory(epoch, items);
|
||||
}, [model, epoch, items]);
|
||||
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, anchorSeq: seq },
|
||||
timelineCursor: { epoch: "epoch", 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, anchorSeq: index + 1 },
|
||||
timelineCursor: { epoch: "epoch", seq: 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, null);
|
||||
model.updateHistory("epoch", history);
|
||||
},
|
||||
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", [], null);
|
||||
model.updateHistory("epoch", []);
|
||||
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)], null);
|
||||
model.updateHistory("epoch", [message(1), message(2)]);
|
||||
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)], null);
|
||||
model.updateHistory("epoch", [message(1)]);
|
||||
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", [], null);
|
||||
model.updateHistory("epoch", []);
|
||||
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", [], null);
|
||||
model.updateHistory("epoch", []);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("error");
|
||||
@@ -207,160 +207,24 @@ it("reports a search result that outlived its epoch as a changed history", async
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1)], null);
|
||||
model.updateHistory("epoch", [message(1)]);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
model.updateHistory("epoch-2", [message(1)], null);
|
||||
model.updateHistory("epoch-2", [message(1)]);
|
||||
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)], null);
|
||||
model.updateHistory("epoch", [message(1)]);
|
||||
},
|
||||
async reveal() {
|
||||
return { count: 1, occurrence: 0 };
|
||||
@@ -368,7 +232,7 @@ it("can load a search location before the initial chat history has arrived", asy
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory(null, [], null);
|
||||
model.updateHistory(null, []);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
@@ -396,7 +260,7 @@ it("reports the position across the whole chat and corrects it with rendered cou
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.updateHistory("epoch", [message(1), message(2)]);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
@@ -433,7 +297,7 @@ it("counts one match per message from a host that reports no counts", async () =
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.updateHistory("epoch", [message(1), message(2)]);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
|
||||
@@ -76,10 +76,6 @@ 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;
|
||||
@@ -117,7 +113,6 @@ 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 };
|
||||
@@ -149,7 +144,6 @@ export class ChatFindModel {
|
||||
});
|
||||
}
|
||||
private async search(signal: AbortSignal) {
|
||||
this.searchedRewindSeq = this.rewindSeq;
|
||||
try {
|
||||
let cursor: number | undefined;
|
||||
do {
|
||||
@@ -174,14 +168,15 @@ export class ChatFindModel {
|
||||
this.fail(error, signal);
|
||||
}
|
||||
}
|
||||
/** `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) {
|
||||
updateHistory(epoch: string | null, items: StreamItem[]) {
|
||||
if (
|
||||
this.resultEpoch !== null &&
|
||||
epoch !== null &&
|
||||
epoch !== this.resultEpoch &&
|
||||
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,8 +9,6 @@ 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, anchorSeq: seq },
|
||||
timelineCursor: { epoch: "epoch-1", 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, anchorSeq: 2 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 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, anchorSeq: 1 },
|
||||
timelineCursor: { epoch: "epoch-2", seq: 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, anchorSeq: 1 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 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, anchorSeq: 1 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 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, anchorSeq: 2 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2 },
|
||||
};
|
||||
const revealLoadedMessage = vi.fn();
|
||||
revealLoadedMessage.mockReturnValue(false);
|
||||
|
||||
@@ -320,7 +320,7 @@ describe("stream presentation through installed plugins", () => {
|
||||
const source = harness.source();
|
||||
const live = source.head[0];
|
||||
if (live?.kind !== "assistant_message") throw new Error("Expected a live assistant message");
|
||||
const canonical = { ...live, timelineCursor: { epoch: "epoch-1", seq: 42, anchorSeq: 42 } };
|
||||
const canonical = { ...live, timelineCursor: { epoch: "epoch-1", seq: 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, anchorSeq: 42 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 42 },
|
||||
},
|
||||
]);
|
||||
});
|
||||
@@ -517,7 +517,7 @@ describe("timeline presentation", () => {
|
||||
messageId: "provider-message",
|
||||
clientMessageId: "client-message",
|
||||
turnId: "turn-1",
|
||||
timelineCursor: { epoch: "epoch", seq: 12, anchorSeq: 12 },
|
||||
timelineCursor: { epoch: "epoch", seq: 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, anchorSeq: 42 },
|
||||
timelineCursor: { epoch: "timeline-1", seq: 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, anchorSeq: 42 },
|
||||
timelineCursor: { epoch: "timeline-1", seq: 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, anchorSeq: 42 },
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42 },
|
||||
};
|
||||
|
||||
expect(
|
||||
@@ -116,7 +116,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
|
||||
it("resolves a fork boundary from the reply a plugin card replaced", () => {
|
||||
const reply = {
|
||||
...assistantMessage("assistant-1", 2, "msg-assistant-1"),
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42 },
|
||||
};
|
||||
const card: StreamItem = {
|
||||
kind: "plugin",
|
||||
@@ -154,7 +154,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
|
||||
const appended: StreamItem = {
|
||||
kind: "plugin",
|
||||
id: "plugin/card-1",
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42 },
|
||||
timestamp: timestamp(2),
|
||||
pluginId: "plugin",
|
||||
pluginItemId: "card-1",
|
||||
|
||||
@@ -1,13 +1,7 @@
|
||||
import { getAssistantReply, type StreamItem } from "@/types/stream";
|
||||
|
||||
/** The daemon's timeline cursor; the row's anchor stays in the client. */
|
||||
interface TimelineBoundaryCursor {
|
||||
epoch: string;
|
||||
seq: number;
|
||||
}
|
||||
import { getAssistantReply, type StreamItem, type TimelinePosition } from "@/types/stream";
|
||||
|
||||
export type AssistantTurnForkBoundary =
|
||||
| { boundaryCursor: TimelineBoundaryCursor; boundaryMessageId?: string }
|
||||
| { boundaryCursor: TimelinePosition; boundaryMessageId?: string }
|
||||
| { boundaryCursor?: undefined; boundaryMessageId: string };
|
||||
|
||||
export function resolveAssistantTurnForkBoundary(input: {
|
||||
@@ -21,7 +15,7 @@ export function resolveAssistantTurnForkBoundary(input: {
|
||||
}
|
||||
if (input.supportsTimelineCursor && reply.timelineCursor) {
|
||||
return {
|
||||
boundaryCursor: { epoch: reply.timelineCursor.epoch, seq: reply.timelineCursor.seq },
|
||||
boundaryCursor: reply.timelineCursor,
|
||||
...(reply.messageId ? { boundaryMessageId: reply.messageId } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -139,7 +139,7 @@ describe("collapseTurns", () => {
|
||||
it("stands at its host's timeline position, taking a new row when that position lands", () => {
|
||||
const live = collapse([user("u1"), shell("c1"), reply("r1")]);
|
||||
expect(live.summaryRowsByHostId.get("u1")).not.toHaveProperty("timelineCursor");
|
||||
const cursor = { epoch: "epoch-1", seq: 7, anchorSeq: 7 };
|
||||
const cursor = { epoch: "epoch-1", seq: 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"));
|
||||
|
||||
@@ -159,10 +159,10 @@ const projectedReply: StreamItem = {
|
||||
id: "reply",
|
||||
messageId: "provider-reply-1",
|
||||
text: 'Done.\n\n```ui\nCard("Summary", [])\n```',
|
||||
timelineCursor: { epoch: "e1", seq: 5, anchorSeq: 5 },
|
||||
timelineCursor: { epoch: "e1", seq: 5 },
|
||||
timestamp: FRIDAY_NIGHT,
|
||||
},
|
||||
timelineCursor: { epoch: "e1", seq: 5, anchorSeq: 5 },
|
||||
timelineCursor: { epoch: "e1", seq: 5 },
|
||||
timestamp: FRIDAY_NIGHT,
|
||||
pluginId: "genui",
|
||||
pluginItemId: "reply/1",
|
||||
|
||||
@@ -408,10 +408,6 @@ 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,
|
||||
);
|
||||
@@ -1170,7 +1166,6 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
agentId={agentId}
|
||||
serverId={resolvedServerId}
|
||||
epoch={timelineEpoch}
|
||||
rewindSeq={timelineRewindSeq}
|
||||
items={findItems}
|
||||
viewportRef={viewportRef}
|
||||
revealLoadedMessage={revealLoadedMessage}
|
||||
|
||||
@@ -7,7 +7,6 @@ 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";
|
||||
|
||||
@@ -20,7 +19,6 @@ 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);
|
||||
|
||||
@@ -29,15 +27,12 @@ export function ArchivedAgentCallout({ serverId, agentId }: ArchivedAgentCallout
|
||||
setIsUnarchiving(true);
|
||||
setUnarchiveError(null);
|
||||
try {
|
||||
const refreshed = await client.refreshAgent(agentId);
|
||||
if (refreshed.historyDiverged) {
|
||||
toast.show(t("workspace.tabs.toasts.reloadedAgentHistoryDiverged"), { variant: "warning" });
|
||||
}
|
||||
await client.refreshAgent(agentId);
|
||||
} catch (error) {
|
||||
setUnarchiveError(toErrorMessage(error));
|
||||
setIsUnarchiving(false);
|
||||
}
|
||||
}, [client, isConnected, isUnarchiving, agentId, toast, t]);
|
||||
}, [client, isConnected, isUnarchiving, agentId]);
|
||||
|
||||
return (
|
||||
<KeyboardTranslateView style={styles.container}>
|
||||
|
||||
@@ -232,6 +232,7 @@ export interface HostPickerProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
anchorRef: React.RefObject<View | null>;
|
||||
restoreFocusRef?: ComboboxProps["restoreFocusRef"];
|
||||
includeAllHost?: boolean;
|
||||
includeAddHost?: boolean;
|
||||
onAddHost?: () => void;
|
||||
@@ -254,6 +255,7 @@ export function HostPicker({
|
||||
open,
|
||||
onOpenChange,
|
||||
anchorRef,
|
||||
restoreFocusRef,
|
||||
includeAllHost,
|
||||
includeAddHost,
|
||||
onAddHost,
|
||||
@@ -404,6 +406,7 @@ export function HostPicker({
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
anchorRef={anchorRef}
|
||||
restoreFocusRef={restoreFocusRef}
|
||||
desktopPlacement={desktopPlacement}
|
||||
desktopMinWidth={desktopMinWidth}
|
||||
/>
|
||||
|
||||
@@ -55,6 +55,7 @@ import { HostPicker } from "@/components/hosts/host-picker";
|
||||
import { SidebarDisplayPreferencesMenu } from "@/components/sidebar/display-preferences/menu";
|
||||
import { SidebarSeparator } from "@/components/sidebar/sidebar-separator";
|
||||
import { SidebarToastRegion } from "@/components/sidebar/sidebar-toast-region";
|
||||
import { SidebarSelectionHost } from "@/sidebar-selection";
|
||||
import { SidebarNavRows, useVisibleSidebarNavItems } from "@/components/sidebar/sidebar-nav-rows";
|
||||
import { SidebarFooterIconHighlight } from "@/components/sidebar/sidebar-footer-icon-highlight";
|
||||
import { SidebarHelpMenu } from "@/components/sidebar/sidebar-help-menu";
|
||||
@@ -667,6 +668,7 @@ function MobileSidebar({
|
||||
listHeaderComponent={workspacesSectionHeaderElement}
|
||||
/>
|
||||
)}
|
||||
<SidebarSelectionHost active={active} workspaceEntriesByKey={workspaceEntriesByKey} />
|
||||
</SidebarToastRegion>
|
||||
</SidebarViewSlot>
|
||||
|
||||
@@ -922,6 +924,7 @@ function DesktopSidebar({
|
||||
listHeaderComponent={workspacesSectionHeaderElement}
|
||||
/>
|
||||
)}
|
||||
<SidebarSelectionHost active={active} workspaceEntriesByKey={workspaceEntriesByKey} />
|
||||
</SidebarToastRegion>
|
||||
</SidebarViewSlot>
|
||||
|
||||
|
||||
@@ -9,7 +9,6 @@ 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;
|
||||
@@ -43,16 +42,7 @@ export function useRewindAgentMutation(input: UseRewindAgentMutationInput): {
|
||||
throw new Error(t("common.errors.daemonClientUnavailable"));
|
||||
}
|
||||
await input.client.rewindAgent(input.agentId, input.messageId, mode);
|
||||
// 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) {
|
||||
if (mode !== "files") {
|
||||
const cursor = input.serverId
|
||||
? useSessionStore
|
||||
.getState()
|
||||
|
||||
@@ -101,7 +101,17 @@ import {
|
||||
import { useLongPressDragInteraction } from "@/components/sidebar/use-long-press-drag-interaction";
|
||||
import { SidebarSectionHeader } from "@/components/sidebar/sidebar-section-header";
|
||||
import { SidebarGroupToggleRow } from "@/components/sidebar/sidebar-group-toggle-row";
|
||||
import { createWorkspaceVisibilityPolicy } from "@/components/sidebar/sidebar-group-visibility";
|
||||
import {
|
||||
createWorkspaceVisibilityPolicy,
|
||||
selectSidebarGroupVisibility,
|
||||
} from "@/components/sidebar/sidebar-group-visibility";
|
||||
import {
|
||||
isShiftPressEvent,
|
||||
registerSidebarVisibleWorkspaceKeysReader,
|
||||
useIsSidebarSelectionMode,
|
||||
useIsWorkspaceBulkSelected,
|
||||
useSidebarSelectionStore,
|
||||
} from "@/sidebar-selection";
|
||||
import { useLimitedSidebarGroup } from "@/components/sidebar/use-limited-sidebar-group";
|
||||
import {
|
||||
SidebarWorkspaceRowFrame,
|
||||
@@ -284,6 +294,7 @@ interface WorkspaceRowInnerProps {
|
||||
archiveLabel?: string;
|
||||
archiveStatus?: "idle" | "pending" | "success";
|
||||
archivePendingLabel?: string;
|
||||
onSelectWorkspace?: () => void;
|
||||
onArchive?: () => void;
|
||||
onCopyBranchName?: () => void;
|
||||
onCopyPath?: () => void;
|
||||
@@ -607,12 +618,14 @@ function WorkspaceRowRightGroup({
|
||||
isHovered,
|
||||
isTouchPlatform,
|
||||
isCreating,
|
||||
isSelectionMode,
|
||||
showShortcutBadge,
|
||||
shortcutNumber,
|
||||
archiveLabel,
|
||||
archiveStatus,
|
||||
archivePendingLabel,
|
||||
archiveShortcutKeys,
|
||||
onSelectWorkspace,
|
||||
onArchive,
|
||||
onMarkAsRead,
|
||||
onMarkAsUnread,
|
||||
@@ -627,12 +640,14 @@ function WorkspaceRowRightGroup({
|
||||
isHovered: boolean;
|
||||
isTouchPlatform: boolean;
|
||||
isCreating: boolean;
|
||||
isSelectionMode: boolean;
|
||||
showShortcutBadge: boolean;
|
||||
shortcutNumber: number | null;
|
||||
archiveLabel?: string;
|
||||
archiveStatus?: "idle" | "pending" | "success";
|
||||
archivePendingLabel?: string;
|
||||
archiveShortcutKeys?: ShortcutKey[][] | null;
|
||||
onSelectWorkspace?: () => void;
|
||||
onArchive?: () => void;
|
||||
onMarkAsRead?: () => void;
|
||||
onMarkAsUnread?: () => void;
|
||||
@@ -660,6 +675,7 @@ function WorkspaceRowRightGroup({
|
||||
isHovered,
|
||||
isTouchPlatform,
|
||||
showShortcut,
|
||||
isSelectionMode,
|
||||
});
|
||||
const kebab = useOpenKebabMenuVisibility(showKebabInSlot);
|
||||
|
||||
@@ -695,6 +711,7 @@ function WorkspaceRowRightGroup({
|
||||
onRename={onRename}
|
||||
onMarkAsRead={onMarkAsRead}
|
||||
onMarkAsUnread={onMarkAsUnread}
|
||||
onSelectWorkspace={onSelectWorkspace}
|
||||
onArchive={onArchive}
|
||||
archiveLabel={archiveLabel}
|
||||
archiveStatus={archiveStatus}
|
||||
@@ -1065,6 +1082,7 @@ function WorkspaceRowInner({
|
||||
archiveLabel,
|
||||
archiveStatus = "idle",
|
||||
archivePendingLabel,
|
||||
onSelectWorkspace,
|
||||
onArchive,
|
||||
onCopyBranchName,
|
||||
onCopyPath,
|
||||
@@ -1079,6 +1097,8 @@ function WorkspaceRowInner({
|
||||
}: WorkspaceRowInnerProps) {
|
||||
const isCompact = useIsCompactFormFactor();
|
||||
const [isHighlighted, setIsHighlighted] = useState(false);
|
||||
const isSelectionMode = useIsSidebarSelectionMode();
|
||||
const isBulkSelected = useIsWorkspaceBulkSelected(workspace.workspaceKey);
|
||||
const isTouchPlatform = platformIsNative || isCompact;
|
||||
const interaction = useLongPressDragInteraction({
|
||||
drag,
|
||||
@@ -1091,30 +1111,75 @@ function WorkspaceRowInner({
|
||||
...dragAttributes
|
||||
} = dragHandleProps?.attributes ?? {};
|
||||
|
||||
const { onPress: handlePress, feedback } = useWorkspaceRowPress({
|
||||
const { onPress: handleNavigatePress, feedback } = useWorkspaceRowPress({
|
||||
didLongPressRef: interaction.didLongPressRef,
|
||||
onPress,
|
||||
selected,
|
||||
});
|
||||
|
||||
const accessibilityState = useMemo(() => ({ selected }), [selected]);
|
||||
const handleRowPress = useCallback(
|
||||
(event: GestureResponderEvent) => {
|
||||
const shiftKey = isShiftPressEvent(event);
|
||||
if (isSelectionMode || shiftKey) {
|
||||
if (interaction.didLongPressRef.current) {
|
||||
interaction.didLongPressRef.current = false;
|
||||
return;
|
||||
}
|
||||
event.preventDefault?.();
|
||||
useSidebarSelectionStore.getState().pressWorkspace(workspace.workspaceKey, { shiftKey });
|
||||
return;
|
||||
}
|
||||
handleNavigatePress();
|
||||
},
|
||||
[handleNavigatePress, interaction.didLongPressRef, isSelectionMode, workspace.workspaceKey],
|
||||
);
|
||||
|
||||
const handleRowPressIn = useCallback(
|
||||
(event: GestureResponderEvent) => {
|
||||
if (isShiftPressEvent(event)) {
|
||||
event.preventDefault?.();
|
||||
return;
|
||||
}
|
||||
if (!isSelectionMode) {
|
||||
interaction.handlePressIn(event);
|
||||
}
|
||||
},
|
||||
[interaction, isSelectionMode],
|
||||
);
|
||||
|
||||
const rowSelected = isSelectionMode ? isBulkSelected : selected;
|
||||
const accessibilityState = useMemo(
|
||||
() => (isSelectionMode ? { checked: isBulkSelected } : { selected }),
|
||||
[isSelectionMode, isBulkSelected, selected],
|
||||
);
|
||||
const isEditingTitle = titleEditor !== null;
|
||||
const disableDrag = isEditingTitle || isSelectionMode;
|
||||
|
||||
return (
|
||||
<SidebarWorkspaceRowFrame
|
||||
workspace={workspace}
|
||||
isDragging={isDragging}
|
||||
isEditingTitle={isEditingTitle}
|
||||
isSelectionMode={isSelectionMode}
|
||||
>
|
||||
{({ isHovered, contextMenuOpen, onContextMenuOpenChange, hoverHandlers }) => {
|
||||
const isDesktop = !isTouchPlatform;
|
||||
const serviceSummary = isDesktop ? selectWorkspaceServiceSummary(workspace.scripts) : null;
|
||||
const workspaceRowStyle = getProjectWorkspaceRowStyle({ isDragging, selected, isHovered });
|
||||
const backdrop = getSidebarRowBackdrop({ isDragging, isHighlighted, selected, isHovered });
|
||||
const workspaceRowStyle = getProjectWorkspaceRowStyle({
|
||||
isDragging,
|
||||
selected: rowSelected,
|
||||
isHovered,
|
||||
});
|
||||
const backdrop = getSidebarRowBackdrop({
|
||||
isDragging,
|
||||
isHighlighted,
|
||||
selected: rowSelected,
|
||||
isHovered,
|
||||
});
|
||||
return (
|
||||
<View
|
||||
{...dragAttributes}
|
||||
{...(isEditingTitle ? null : dragHandleProps?.listeners)}
|
||||
{...(disableDrag ? null : dragHandleProps?.listeners)}
|
||||
ref={dragHandleProps?.setActivatorNodeRef as unknown as Ref<View>}
|
||||
style={styles.workspaceRowContainer}
|
||||
{...hoverHandlers}
|
||||
@@ -1131,6 +1196,7 @@ function WorkspaceRowInner({
|
||||
onRename={onRename}
|
||||
onMarkAsRead={onMarkAsRead}
|
||||
onMarkAsUnread={onMarkAsUnread}
|
||||
onSelectWorkspace={onSelectWorkspace}
|
||||
onArchive={onArchive}
|
||||
archiveLabel={archiveLabel}
|
||||
archiveStatus={archiveStatus}
|
||||
@@ -1140,17 +1206,18 @@ function WorkspaceRowInner({
|
||||
onTogglePin={onTogglePin}
|
||||
openInFileManagerPath={workspace.workspaceDirectory}
|
||||
disabled={isArchiving}
|
||||
enabled={!isEditingTitle}
|
||||
aria-selected={selected}
|
||||
accessibilityRole="button"
|
||||
enabled={!isEditingTitle && !isSelectionMode}
|
||||
aria-selected={isSelectionMode ? undefined : selected}
|
||||
aria-checked={isSelectionMode ? isBulkSelected : undefined}
|
||||
accessibilityRole={isSelectionMode ? "checkbox" : "button"}
|
||||
accessibilityState={accessibilityState}
|
||||
style={workspaceRowStyle}
|
||||
highlightStyle={isEditingTitle ? undefined : styles.workspaceRowPressed}
|
||||
onHighlightChange={setIsHighlighted}
|
||||
onPressIn={isEditingTitle ? undefined : interaction.handlePressIn}
|
||||
onTouchMove={isEditingTitle ? undefined : interaction.handleTouchMove}
|
||||
onPressOut={isEditingTitle ? undefined : interaction.handlePressOut}
|
||||
onPress={isEditingTitle ? undefined : handlePress}
|
||||
onPressIn={isEditingTitle ? undefined : handleRowPressIn}
|
||||
onTouchMove={disableDrag ? undefined : interaction.handleTouchMove}
|
||||
onPressOut={disableDrag ? undefined : interaction.handlePressOut}
|
||||
onPress={isEditingTitle ? undefined : handleRowPress}
|
||||
testID={`sidebar-workspace-row-${workspace.workspaceKey}`}
|
||||
>
|
||||
<SidebarWorkspaceRowContent
|
||||
@@ -1163,6 +1230,8 @@ function WorkspaceRowInner({
|
||||
isHovered={isHovered}
|
||||
isLoading={isArchiving || isCreating}
|
||||
isCreating={isCreating}
|
||||
isSelectionMode={isSelectionMode}
|
||||
isBulkSelected={isBulkSelected}
|
||||
shortcutNumber={shortcutNumber}
|
||||
showShortcutBadge={showShortcutBadge}
|
||||
reserveIdleStatusIndicatorSpace={reserveIdleStatusIndicatorSpace}
|
||||
@@ -1174,12 +1243,14 @@ function WorkspaceRowInner({
|
||||
isHovered={isHovered}
|
||||
isTouchPlatform={isTouchPlatform}
|
||||
isCreating={isCreating}
|
||||
isSelectionMode={isSelectionMode}
|
||||
showShortcutBadge={showShortcutBadge}
|
||||
shortcutNumber={shortcutNumber}
|
||||
archiveLabel={archiveLabel}
|
||||
archiveStatus={archiveStatus}
|
||||
archivePendingLabel={archivePendingLabel}
|
||||
archiveShortcutKeys={archiveShortcutKeys}
|
||||
onSelectWorkspace={onSelectWorkspace}
|
||||
onArchive={onArchive}
|
||||
onCopyBranchName={onCopyBranchName}
|
||||
onCopyPath={onCopyPath}
|
||||
@@ -1265,6 +1336,10 @@ function WorkspaceRowWithMenu({
|
||||
archiveController.archive();
|
||||
}, [archiveController, isArchiving]);
|
||||
|
||||
const handleSelectWorkspace = useCallback(() => {
|
||||
useSidebarSelectionStore.getState().enter(workspace.workspaceKey);
|
||||
}, [workspace.workspaceKey]);
|
||||
|
||||
const clipboard = useWorkspaceClipboardActions();
|
||||
const handleCopyPath = useCallback(() => {
|
||||
clipboard.copyPath(workspace);
|
||||
@@ -1317,6 +1392,7 @@ function WorkspaceRowWithMenu({
|
||||
archiveLabel={t("sidebar.workspace.actions.archive")}
|
||||
archiveStatus={isArchiving ? "pending" : "idle"}
|
||||
archivePendingLabel={t("sidebar.workspace.actions.archiving")}
|
||||
onSelectWorkspace={handleSelectWorkspace}
|
||||
onArchive={handleArchive}
|
||||
onCopyBranchName={canCopyBranchName ? handleCopyBranchName : undefined}
|
||||
onCopyPath={handleCopyPath}
|
||||
@@ -2199,6 +2275,62 @@ function ProjectModeList({
|
||||
selection: selectionEnabled ? activeWorkspaceSelection : null,
|
||||
expanded: pinnedChatsExpanded,
|
||||
});
|
||||
|
||||
const visibleOrderInputRef = useRef({
|
||||
pinnedCollapsed,
|
||||
leadingPinnedChat,
|
||||
visiblePinnedChats,
|
||||
unpinnedProjects,
|
||||
collapsedProjectKeys,
|
||||
expandedProjectKeys,
|
||||
selectionEnabled,
|
||||
activeWorkspaceSelection,
|
||||
workspaceEntriesByKey,
|
||||
});
|
||||
visibleOrderInputRef.current = {
|
||||
pinnedCollapsed,
|
||||
leadingPinnedChat,
|
||||
visiblePinnedChats,
|
||||
unpinnedProjects,
|
||||
collapsedProjectKeys,
|
||||
expandedProjectKeys,
|
||||
selectionEnabled,
|
||||
activeWorkspaceSelection,
|
||||
workspaceEntriesByKey,
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
return registerSidebarVisibleWorkspaceKeysReader(() => {
|
||||
const current = visibleOrderInputRef.current;
|
||||
const keys: string[] = [];
|
||||
if (!current.pinnedCollapsed) {
|
||||
if (current.leadingPinnedChat) keys.push(current.leadingPinnedChat.workspaceKey);
|
||||
for (const item of current.visiblePinnedChats) {
|
||||
keys.push(item.workspaceKey);
|
||||
}
|
||||
}
|
||||
const policy = createWorkspaceVisibilityPolicy<SidebarWorkspacePlacement>(
|
||||
current.workspaceEntriesByKey,
|
||||
);
|
||||
const selection = current.selectionEnabled ? current.activeWorkspaceSelection : null;
|
||||
for (const project of current.unpinnedProjects) {
|
||||
if (current.collapsedProjectKeys.has(project.viewKey) || project.workspaces.length === 0) {
|
||||
continue;
|
||||
}
|
||||
const { leadingItem, visibleItems } = selectSidebarGroupVisibility({
|
||||
items: project.workspaces,
|
||||
selection,
|
||||
expanded: current.expandedProjectKeys.has(project.viewKey),
|
||||
policy,
|
||||
});
|
||||
if (leadingItem) keys.push(leadingItem.workspaceKey);
|
||||
for (const item of visibleItems) {
|
||||
keys.push(item.workspaceKey);
|
||||
}
|
||||
}
|
||||
return keys;
|
||||
});
|
||||
}, []);
|
||||
const nativeScrollGestureProps = useMemo(
|
||||
() =>
|
||||
parentGestureRef
|
||||
|
||||
@@ -3,14 +3,16 @@ import { PressHighlight as Pressable } from "@/components/ui/press-highlight";
|
||||
import {
|
||||
memo,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type MutableRefObject,
|
||||
type ReactNode,
|
||||
type Ref,
|
||||
} from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { View, Text, ScrollView } from "react-native";
|
||||
import { View, Text, ScrollView, type GestureResponderEvent } from "react-native";
|
||||
import { NestableScrollContainer } from "react-native-draggable-flatlist";
|
||||
import type { GestureType } from "react-native-gesture-handler";
|
||||
import { navigateToWorkspace } from "@/stores/navigation-active-workspace-store";
|
||||
@@ -69,7 +71,15 @@ import {
|
||||
} from "@/components/sidebar/sidebar-workspace-menu";
|
||||
import { SidebarSectionHeader } from "@/components/sidebar/sidebar-section-header";
|
||||
import { SidebarGroupToggleRow } from "@/components/sidebar/sidebar-group-toggle-row";
|
||||
import { selectSidebarGroupVisibility } from "@/components/sidebar/sidebar-group-visibility";
|
||||
import { useLimitedSidebarGroup } from "@/components/sidebar/use-limited-sidebar-group";
|
||||
import {
|
||||
isShiftPressEvent,
|
||||
registerSidebarVisibleWorkspaceKeysReader,
|
||||
useIsSidebarSelectionMode,
|
||||
useIsWorkspaceBulkSelected,
|
||||
useSidebarSelectionStore,
|
||||
} from "@/sidebar-selection";
|
||||
import type { ToggleSidebarWorkspacePin } from "@/hooks/use-sidebar-workspace-pin";
|
||||
import { DraggableList, type DraggableRenderItemInfo } from "@/components/draggable-list";
|
||||
import type { DraggableListDragHandleProps } from "@/components/draggable-list.types";
|
||||
@@ -154,6 +164,14 @@ export function SidebarStatusWorkspaceList({
|
||||
() => setPinnedWorkspacesExpanded((current) => !current),
|
||||
[],
|
||||
);
|
||||
const [expandedGroupKeys, setExpandedGroupKeys] = useState<ReadonlySet<string>>(() => new Set());
|
||||
const toggleGroupWorkspacesExpanded = useCallback((groupKey: string) => {
|
||||
setExpandedGroupKeys((current) => {
|
||||
const next = new Set(current);
|
||||
if (!next.delete(groupKey)) next.add(groupKey);
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
const {
|
||||
leadingItem: leadingPinnedWorkspace,
|
||||
visibleItems: visiblePinnedWorkspaces,
|
||||
@@ -164,6 +182,56 @@ export function SidebarStatusWorkspaceList({
|
||||
expanded: pinnedWorkspacesExpanded,
|
||||
});
|
||||
|
||||
const visibleOrderInputRef = useRef({
|
||||
pinnedCollapsed,
|
||||
leadingPinnedWorkspace,
|
||||
visiblePinnedWorkspaces,
|
||||
groups,
|
||||
collapsedWorkspaceGroupKeys,
|
||||
expandedGroupKeys,
|
||||
activeWorkspaceSelection,
|
||||
});
|
||||
visibleOrderInputRef.current = {
|
||||
pinnedCollapsed,
|
||||
leadingPinnedWorkspace,
|
||||
visiblePinnedWorkspaces,
|
||||
groups,
|
||||
collapsedWorkspaceGroupKeys,
|
||||
expandedGroupKeys,
|
||||
activeWorkspaceSelection,
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
return registerSidebarVisibleWorkspaceKeysReader(() => {
|
||||
const current = visibleOrderInputRef.current;
|
||||
const keys: string[] = [];
|
||||
if (!current.pinnedCollapsed) {
|
||||
if (current.leadingPinnedWorkspace) {
|
||||
keys.push(current.leadingPinnedWorkspace.workspaceKey);
|
||||
}
|
||||
for (const item of current.visiblePinnedWorkspaces) {
|
||||
keys.push(item.workspaceKey);
|
||||
}
|
||||
}
|
||||
for (const group of current.groups) {
|
||||
if (current.collapsedWorkspaceGroupKeys.has(group.key) || group.rows.length === 0) {
|
||||
continue;
|
||||
}
|
||||
const { leadingItem, visibleItems } = selectSidebarGroupVisibility({
|
||||
items: group.rows,
|
||||
selection: current.activeWorkspaceSelection,
|
||||
expanded: current.expandedGroupKeys.has(group.key),
|
||||
policy: STATUS_GROUP_VISIBILITY,
|
||||
});
|
||||
if (leadingItem) keys.push(leadingItem.workspaceKey);
|
||||
for (const item of visibleItems) {
|
||||
keys.push(item.workspaceKey);
|
||||
}
|
||||
}
|
||||
return keys;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const statusShortcutIndex = showShortcutBadges
|
||||
? shortcutIndexByWorkspaceKey
|
||||
: EMPTY_SHORTCUT_INDEX;
|
||||
@@ -262,6 +330,8 @@ export function SidebarStatusWorkspaceList({
|
||||
<StatusGroupList
|
||||
groups={groups}
|
||||
collapsedWorkspaceGroupKeys={collapsedWorkspaceGroupKeys}
|
||||
expandedGroupKeys={expandedGroupKeys}
|
||||
onToggleGroupWorkspacesExpanded={toggleGroupWorkspacesExpanded}
|
||||
projectIconByProjectViewKey={projectIconByProjectViewKey}
|
||||
shortcutIndex={statusShortcutIndex}
|
||||
showShortcutBadges={showShortcutBadges}
|
||||
@@ -303,6 +373,8 @@ export function SidebarStatusWorkspaceList({
|
||||
function StatusGroupList({
|
||||
groups,
|
||||
collapsedWorkspaceGroupKeys,
|
||||
expandedGroupKeys,
|
||||
onToggleGroupWorkspacesExpanded,
|
||||
projectIconByProjectViewKey,
|
||||
shortcutIndex,
|
||||
showShortcutBadges,
|
||||
@@ -313,6 +385,8 @@ function StatusGroupList({
|
||||
}: {
|
||||
groups: SidebarWorkspaceGroup[];
|
||||
collapsedWorkspaceGroupKeys: ReadonlySet<string>;
|
||||
expandedGroupKeys: ReadonlySet<string>;
|
||||
onToggleGroupWorkspacesExpanded: (groupKey: string) => void;
|
||||
projectIconByProjectViewKey: ReadonlyMap<string, string | null>;
|
||||
shortcutIndex: Map<string, number>;
|
||||
showShortcutBadges: boolean;
|
||||
@@ -328,6 +402,8 @@ function StatusGroupList({
|
||||
key={group.key}
|
||||
group={group}
|
||||
collapsed={collapsedWorkspaceGroupKeys.has(group.key)}
|
||||
workspacesExpanded={expandedGroupKeys.has(group.key)}
|
||||
onToggleWorkspacesExpanded={onToggleGroupWorkspacesExpanded}
|
||||
projectIconByProjectViewKey={projectIconByProjectViewKey}
|
||||
shortcutIndex={shortcutIndex}
|
||||
showShortcutBadges={showShortcutBadges}
|
||||
@@ -349,6 +425,8 @@ const STATUS_GROUP_VISIBILITY = {
|
||||
function StatusGroupRows({
|
||||
group,
|
||||
collapsed,
|
||||
workspacesExpanded,
|
||||
onToggleWorkspacesExpanded,
|
||||
projectIconByProjectViewKey,
|
||||
shortcutIndex,
|
||||
showShortcutBadges,
|
||||
@@ -359,6 +437,8 @@ function StatusGroupRows({
|
||||
}: {
|
||||
group: SidebarWorkspaceGroup;
|
||||
collapsed: boolean;
|
||||
workspacesExpanded: boolean;
|
||||
onToggleWorkspacesExpanded: (groupKey: string) => void;
|
||||
projectIconByProjectViewKey: ReadonlyMap<string, string | null>;
|
||||
shortcutIndex: Map<string, number>;
|
||||
showShortcutBadges: boolean;
|
||||
@@ -368,10 +448,9 @@ function StatusGroupRows({
|
||||
onToggleWorkspacePin: ToggleSidebarWorkspacePin;
|
||||
}) {
|
||||
const activeWorkspaceSelection = useActiveWorkspaceSelection();
|
||||
const [workspacesExpanded, setWorkspacesExpanded] = useState(false);
|
||||
const toggleWorkspacesExpanded = useCallback(
|
||||
() => setWorkspacesExpanded((current) => !current),
|
||||
[],
|
||||
() => onToggleWorkspacesExpanded(group.key),
|
||||
[group.key, onToggleWorkspacesExpanded],
|
||||
);
|
||||
const {
|
||||
leadingItem: leadingWorkspace,
|
||||
@@ -669,6 +748,10 @@ function StatusWorkspaceRowWithMenu({
|
||||
archiveController.archive();
|
||||
}, [archiveController, isArchiving]);
|
||||
|
||||
const handleSelectWorkspace = useCallback(() => {
|
||||
useSidebarSelectionStore.getState().enter(workspace.workspaceKey);
|
||||
}, [workspace.workspaceKey]);
|
||||
|
||||
const clipboard = useWorkspaceClipboardActions();
|
||||
const handleCopyPath = useCallback(() => {
|
||||
clipboard.copyPath(workspace);
|
||||
@@ -716,6 +799,7 @@ function StatusWorkspaceRowWithMenu({
|
||||
archiveLabel={t("sidebar.workspace.actions.archive")}
|
||||
archiveStatus={isArchiving ? "pending" : "idle"}
|
||||
archivePendingLabel={t("sidebar.workspace.actions.archiving")}
|
||||
onSelectWorkspace={handleSelectWorkspace}
|
||||
onArchive={handleArchive}
|
||||
onCopyBranchName={workspace.projectKind === "git" ? handleCopyBranchName : undefined}
|
||||
onCopyPath={handleCopyPath}
|
||||
@@ -750,6 +834,7 @@ interface StatusWorkspaceRowInnerProps {
|
||||
archiveLabel?: string;
|
||||
archiveStatus?: "idle" | "pending" | "success";
|
||||
archivePendingLabel?: string;
|
||||
onSelectWorkspace?: () => void;
|
||||
onArchive?: () => void;
|
||||
onCopyBranchName?: () => void;
|
||||
onCopyPath?: () => void;
|
||||
@@ -799,6 +884,7 @@ function StatusWorkspaceRowInnerContent({
|
||||
archiveLabel,
|
||||
archiveStatus = "idle",
|
||||
archivePendingLabel,
|
||||
onSelectWorkspace,
|
||||
onArchive,
|
||||
onCopyBranchName,
|
||||
onCopyPath,
|
||||
@@ -820,6 +906,8 @@ function StatusWorkspaceRowInnerContent({
|
||||
const isCompact = useIsCompactFormFactor();
|
||||
const isTouchPlatform = platformIsNative || isCompact;
|
||||
const [isHighlighted, setIsHighlighted] = useState(false);
|
||||
const isSelectionMode = useIsSidebarSelectionMode();
|
||||
const isBulkSelected = useIsWorkspaceBulkSelected(workspace.workspaceKey);
|
||||
const trailing = useSidebarWorkspaceTrailing();
|
||||
const {
|
||||
role: _dragRole,
|
||||
@@ -831,23 +919,59 @@ function StatusWorkspaceRowInnerContent({
|
||||
const isDesktop = !isTouchPlatform;
|
||||
const serviceSummary = isDesktop ? selectWorkspaceServiceSummary(workspace.scripts) : null;
|
||||
|
||||
const accessibilityState = useMemo(() => ({ selected }), [selected]);
|
||||
const rowSelected = isSelectionMode ? isBulkSelected : selected;
|
||||
const accessibilityState = useMemo(
|
||||
() => (isSelectionMode ? { checked: isBulkSelected } : { selected }),
|
||||
[isSelectionMode, isBulkSelected, selected],
|
||||
);
|
||||
const isEditingTitle = titleEditor !== null;
|
||||
const disableDrag = isEditingTitle || isSelectionMode;
|
||||
const didLongPressRef = dragInteraction?.didLongPressRef;
|
||||
const startDragPress = dragInteraction?.handlePressIn;
|
||||
const moveDragPress = dragInteraction?.handleTouchMove;
|
||||
const endDragPress = dragInteraction?.handlePressOut;
|
||||
const { onPress: handlePress, feedback } = useWorkspaceRowPress({
|
||||
const { onPress: handleNavigatePress, feedback } = useWorkspaceRowPress({
|
||||
didLongPressRef,
|
||||
onPress,
|
||||
selected,
|
||||
});
|
||||
|
||||
const handleRowPress = useCallback(
|
||||
(event: GestureResponderEvent) => {
|
||||
const shiftKey = isShiftPressEvent(event);
|
||||
if (isSelectionMode || shiftKey) {
|
||||
if (didLongPressRef?.current) {
|
||||
didLongPressRef.current = false;
|
||||
return;
|
||||
}
|
||||
event.preventDefault?.();
|
||||
useSidebarSelectionStore.getState().pressWorkspace(workspace.workspaceKey, { shiftKey });
|
||||
return;
|
||||
}
|
||||
handleNavigatePress();
|
||||
},
|
||||
[didLongPressRef, handleNavigatePress, isSelectionMode, workspace.workspaceKey],
|
||||
);
|
||||
|
||||
const handleRowPressIn = useCallback(
|
||||
(event: GestureResponderEvent) => {
|
||||
if (isShiftPressEvent(event)) {
|
||||
event.preventDefault?.();
|
||||
return;
|
||||
}
|
||||
if (!isSelectionMode) {
|
||||
startDragPress?.(event);
|
||||
}
|
||||
},
|
||||
[isSelectionMode, startDragPress],
|
||||
);
|
||||
|
||||
return (
|
||||
<SidebarWorkspaceRowFrame
|
||||
workspace={workspace}
|
||||
isDragging={isDragging}
|
||||
isEditingTitle={isEditingTitle}
|
||||
isSelectionMode={isSelectionMode}
|
||||
>
|
||||
{({ isHovered, contextMenuOpen, onContextMenuOpenChange, hoverHandlers }) => {
|
||||
const showShortcut = showShortcutBadge && shortcutNumber !== null;
|
||||
@@ -865,18 +989,24 @@ function StatusWorkspaceRowInnerContent({
|
||||
isHovered,
|
||||
isTouchPlatform,
|
||||
showShortcut,
|
||||
isSelectionMode,
|
||||
});
|
||||
const workspaceRowStyle = getStatusWorkspaceRowStyle({
|
||||
selected,
|
||||
selected: rowSelected,
|
||||
isHovered,
|
||||
inStatusGroup,
|
||||
isDragging,
|
||||
});
|
||||
const backdrop = getSidebarRowBackdrop({ isDragging, isHighlighted, selected, isHovered });
|
||||
const backdrop = getSidebarRowBackdrop({
|
||||
isDragging,
|
||||
isHighlighted,
|
||||
selected: rowSelected,
|
||||
isHovered,
|
||||
});
|
||||
return (
|
||||
<View
|
||||
{...dragAttributes}
|
||||
{...(isEditingTitle ? null : dragHandleProps?.listeners)}
|
||||
{...(disableDrag ? null : dragHandleProps?.listeners)}
|
||||
ref={dragHandleProps?.setActivatorNodeRef as unknown as Ref<View>}
|
||||
style={styles.workspaceRowContainer}
|
||||
{...hoverHandlers}
|
||||
@@ -894,6 +1024,7 @@ function StatusWorkspaceRowInnerContent({
|
||||
onRename={onRename}
|
||||
onMarkAsRead={onMarkAsRead}
|
||||
onMarkAsUnread={onMarkAsUnread}
|
||||
onSelectWorkspace={onSelectWorkspace}
|
||||
onArchive={onArchive}
|
||||
archiveLabel={archiveLabel}
|
||||
archiveStatus={archiveStatus}
|
||||
@@ -903,16 +1034,18 @@ function StatusWorkspaceRowInnerContent({
|
||||
onTogglePin={onTogglePin}
|
||||
openInFileManagerPath={workspace.workspaceDirectory}
|
||||
disabled={isArchiving}
|
||||
enabled={!isEditingTitle}
|
||||
accessibilityRole="button"
|
||||
enabled={!isEditingTitle && !isSelectionMode}
|
||||
aria-selected={isSelectionMode ? undefined : selected}
|
||||
aria-checked={isSelectionMode ? isBulkSelected : undefined}
|
||||
accessibilityRole={isSelectionMode ? "checkbox" : "button"}
|
||||
accessibilityState={accessibilityState}
|
||||
style={workspaceRowStyle}
|
||||
highlightStyle={isEditingTitle ? undefined : styles.workspaceRowPressed}
|
||||
onHighlightChange={setIsHighlighted}
|
||||
onPressIn={isEditingTitle ? undefined : startDragPress}
|
||||
onTouchMove={isEditingTitle ? undefined : moveDragPress}
|
||||
onPressOut={isEditingTitle ? undefined : endDragPress}
|
||||
onPress={isEditingTitle ? undefined : handlePress}
|
||||
onPressIn={isEditingTitle ? undefined : handleRowPressIn}
|
||||
onTouchMove={disableDrag ? undefined : moveDragPress}
|
||||
onPressOut={disableDrag ? undefined : endDragPress}
|
||||
onPress={isEditingTitle ? undefined : handleRowPress}
|
||||
testID={`sidebar-workspace-row-${workspace.workspaceKey}`}
|
||||
>
|
||||
<SidebarWorkspaceRowContent
|
||||
@@ -924,6 +1057,8 @@ function StatusWorkspaceRowInnerContent({
|
||||
backdrop={backdrop}
|
||||
isHovered={isHovered}
|
||||
isLoading={isArchiving}
|
||||
isSelectionMode={isSelectionMode}
|
||||
isBulkSelected={isBulkSelected}
|
||||
shortcutNumber={shortcutNumber}
|
||||
showShortcutBadge={showShortcutBadge}
|
||||
reserveIdleStatusIndicatorSpace={reserveIdleStatusIndicatorSpace}
|
||||
@@ -946,6 +1081,7 @@ function StatusWorkspaceRowInnerContent({
|
||||
onRename={onRename}
|
||||
onMarkAsRead={onMarkAsRead}
|
||||
onMarkAsUnread={onMarkAsUnread}
|
||||
onSelectWorkspace={onSelectWorkspace}
|
||||
onArchive={onArchive}
|
||||
archiveLabel={archiveLabel}
|
||||
archiveStatus={archiveStatus}
|
||||
@@ -979,6 +1115,7 @@ function StatusWorkspaceActionSlot({
|
||||
onRename,
|
||||
onMarkAsRead,
|
||||
onMarkAsUnread,
|
||||
onSelectWorkspace,
|
||||
onArchive,
|
||||
archiveLabel,
|
||||
archiveStatus,
|
||||
@@ -1000,6 +1137,7 @@ function StatusWorkspaceActionSlot({
|
||||
onRename?: () => void;
|
||||
onMarkAsRead?: () => void;
|
||||
onMarkAsUnread?: () => void;
|
||||
onSelectWorkspace?: () => void;
|
||||
onArchive?: () => void;
|
||||
archiveLabel?: string;
|
||||
archiveStatus?: "idle" | "pending" | "success";
|
||||
@@ -1034,6 +1172,7 @@ function StatusWorkspaceActionSlot({
|
||||
onRename={onRename}
|
||||
onMarkAsRead={onMarkAsRead}
|
||||
onMarkAsUnread={onMarkAsUnread}
|
||||
onSelectWorkspace={onSelectWorkspace}
|
||||
onArchive={onArchive}
|
||||
archiveLabel={archiveLabel}
|
||||
archiveStatus={archiveStatus}
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { View } from "react-native";
|
||||
@@ -15,7 +16,13 @@ import Animated, {
|
||||
type SharedValue,
|
||||
} from "react-native-reanimated";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { TOAST_FADE_MS, ToastViewport, useToastHost, type ToastApi } from "@/components/toast-host";
|
||||
import {
|
||||
TOAST_FADE_MS,
|
||||
ToastViewport,
|
||||
useToastHost,
|
||||
type ToastApi,
|
||||
type ToastState,
|
||||
} from "@/components/toast-host";
|
||||
import { ToastApiProvider, useToast } from "@/contexts/toast-context";
|
||||
|
||||
interface SidebarToastCoverage {
|
||||
@@ -25,6 +32,10 @@ interface SidebarToastCoverage {
|
||||
}
|
||||
|
||||
const SidebarToastCoverageContext = createContext<SidebarToastCoverage | null>(null);
|
||||
const SidebarPersistentToastContext = createContext<((toast: ToastState | null) => void) | null>(
|
||||
null,
|
||||
);
|
||||
const SidebarAppToastContext = createContext<ToastApi | null>(null);
|
||||
|
||||
/**
|
||||
* Shows toasts raised by the sidebar's list over its bottom edge, just above the footer.
|
||||
@@ -36,9 +47,10 @@ const SidebarToastCoverageContext = createContext<SidebarToastCoverage | null>(n
|
||||
export function SidebarToastRegion({ active, children }: { active: boolean; children: ReactNode }) {
|
||||
const appToast = useToast();
|
||||
const { api: sidebarToast, toast, dismiss } = useToastHost();
|
||||
const [persistentToast, setPersistentToast] = useState<ToastState | null>(null);
|
||||
const activeRef = useRef(active);
|
||||
const coverageHeight = useSharedValue(0);
|
||||
const toastVisible = toast !== null;
|
||||
const toastVisible = toast !== null || persistentToast !== null;
|
||||
|
||||
useEffect(() => {
|
||||
activeRef.current = active;
|
||||
@@ -72,19 +84,48 @@ export function SidebarToastRegion({ active, children }: { active: boolean; chil
|
||||
|
||||
return (
|
||||
<View style={styles.region}>
|
||||
<SidebarToastCoverageContext.Provider value={coverage}>
|
||||
<ToastApiProvider api={api}>{children}</ToastApiProvider>
|
||||
</SidebarToastCoverageContext.Provider>
|
||||
<ToastViewport
|
||||
toast={toast}
|
||||
onDismiss={dismiss}
|
||||
placement="sidebar"
|
||||
onBottomCoverageChange={handleCoverageChange}
|
||||
/>
|
||||
<ToastApiProvider api={api}>
|
||||
<SidebarAppToastContext.Provider value={appToast}>
|
||||
<SidebarPersistentToastContext.Provider value={setPersistentToast}>
|
||||
<SidebarToastCoverageContext.Provider value={coverage}>
|
||||
{children}
|
||||
</SidebarToastCoverageContext.Provider>
|
||||
</SidebarPersistentToastContext.Provider>
|
||||
</SidebarAppToastContext.Provider>
|
||||
<ToastViewport
|
||||
toast={toast}
|
||||
persistentToast={persistentToast}
|
||||
onDismiss={dismiss}
|
||||
placement="sidebar"
|
||||
onBottomCoverageChange={handleCoverageChange}
|
||||
/>
|
||||
</ToastApiProvider>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
/** Returns the enclosing app-level toast API so sidebar callers can report errors without displacing an active sidebar undo toast. */
|
||||
export function useSidebarAppToast(): ToastApi {
|
||||
const fallbackToast = useToast();
|
||||
return useContext(SidebarAppToastContext) ?? fallbackToast;
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays a persistent toast in the enclosing `SidebarToastRegion`, stacked below any active
|
||||
* transient toast so controls stay reachable while a previous toast is up.
|
||||
*/
|
||||
export function useSidebarPersistentToast(toast: ToastState | null): void {
|
||||
const setPersistentToast = useContext(SidebarPersistentToastContext);
|
||||
useEffect(() => {
|
||||
setPersistentToast?.(toast);
|
||||
}, [setPersistentToast, toast]);
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
setPersistentToast?.(null);
|
||||
};
|
||||
}, [setPersistentToast]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Space at the end of a sidebar list that matches the toast covering it, so the last row can
|
||||
* scroll clear of the toast. It sits below every row, so growing it moves nothing. It shrinks
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { useMemo, type ComponentProps, type PropsWithChildren, type ReactNode } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { PressableStateCallbackType } from "react-native";
|
||||
import type { GestureResponderEvent, PressableStateCallbackType } from "react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import {
|
||||
Archive,
|
||||
CheckSquare,
|
||||
Circle,
|
||||
CircleCheck,
|
||||
Copy,
|
||||
@@ -56,6 +57,7 @@ const foregroundMutedColorMapping = (theme: Theme) => ({
|
||||
const ThemedMoreVertical = withUnistyles(MoreVertical);
|
||||
const ThemedCopy = withUnistyles(Copy);
|
||||
const ThemedArchive = withUnistyles(Archive);
|
||||
const ThemedCheckSquare = withUnistyles(CheckSquare);
|
||||
const ThemedCircle = withUnistyles(Circle);
|
||||
const ThemedPencil = withUnistyles(Pencil);
|
||||
const ThemedCircleCheck = withUnistyles(CircleCheck);
|
||||
@@ -69,6 +71,7 @@ const markAsReadLeadingIcon = (
|
||||
<ThemedCircleCheck size={14} uniProps={foregroundMutedColorMapping} />
|
||||
);
|
||||
const markAsUnreadLeadingIcon = <ThemedCircle size={14} uniProps={foregroundMutedColorMapping} />;
|
||||
const selectLeadingIcon = <ThemedCheckSquare size={14} uniProps={foregroundMutedColorMapping} />;
|
||||
const archiveLeadingIcon = <ThemedArchive size={14} uniProps={foregroundMutedColorMapping} />;
|
||||
const pinLeadingIcon = <ThemedPin size={14} uniProps={foregroundMutedColorMapping} />;
|
||||
const unpinLeadingIcon = <ThemedPinOff size={14} uniProps={foregroundMutedColorMapping} />;
|
||||
@@ -124,6 +127,7 @@ export interface SidebarWorkspaceMenuProps {
|
||||
onRename?: () => void;
|
||||
onMarkAsRead?: () => void;
|
||||
onMarkAsUnread?: () => void;
|
||||
onSelectWorkspace?: () => void;
|
||||
onArchive: () => void;
|
||||
archiveLabel?: string;
|
||||
archiveStatus?: "idle" | "pending" | "success";
|
||||
@@ -172,6 +176,7 @@ function SidebarWorkspaceMenuItems({
|
||||
onRename,
|
||||
onMarkAsRead,
|
||||
onMarkAsUnread,
|
||||
onSelectWorkspace,
|
||||
onArchive,
|
||||
archiveLabel,
|
||||
archiveStatus,
|
||||
@@ -267,6 +272,16 @@ function SidebarWorkspaceMenuItems({
|
||||
path={openInFileManagerPath}
|
||||
testID={`sidebar-workspace-menu-open-folder-${workspaceKey}`}
|
||||
/>
|
||||
{onSelectWorkspace ? (
|
||||
<WorkspaceMenuItem
|
||||
surface={surface}
|
||||
testID={`sidebar-workspace-menu-select-${workspaceKey}`}
|
||||
leading={selectLeadingIcon}
|
||||
onSelect={onSelectWorkspace}
|
||||
>
|
||||
{t("sidebar.workspace.actions.select")}
|
||||
</WorkspaceMenuItem>
|
||||
) : null}
|
||||
{onArchive ? (
|
||||
<WorkspaceMenuItem
|
||||
surface={surface}
|
||||
@@ -294,6 +309,7 @@ export function SidebarWorkspaceMenu({
|
||||
onRename,
|
||||
onMarkAsRead,
|
||||
onMarkAsUnread,
|
||||
onSelectWorkspace,
|
||||
onArchive,
|
||||
archiveLabel,
|
||||
archiveStatus,
|
||||
@@ -340,6 +356,7 @@ export function SidebarWorkspaceMenu({
|
||||
onRename={onRename}
|
||||
onMarkAsRead={onMarkAsRead}
|
||||
onMarkAsUnread={onMarkAsUnread}
|
||||
onSelectWorkspace={onSelectWorkspace}
|
||||
onArchive={onArchive}
|
||||
archiveLabel={archiveLabel}
|
||||
archiveStatus={archiveStatus}
|
||||
@@ -373,6 +390,7 @@ export function SidebarWorkspaceContextMenu({
|
||||
onRename,
|
||||
onMarkAsRead,
|
||||
onMarkAsUnread,
|
||||
onSelectWorkspace,
|
||||
onArchive,
|
||||
archiveLabel,
|
||||
archiveStatus,
|
||||
@@ -426,11 +444,37 @@ export function SidebarWorkspaceContextMenu({
|
||||
[workspace],
|
||||
);
|
||||
const pages = useWorkspaceLabelMenuPages(workspaceTarget);
|
||||
const checkboxSpaceKeyProps = useMemo(() => {
|
||||
if (!isWeb || triggerProps.accessibilityRole !== "checkbox" || !triggerProps.onPress) {
|
||||
return {};
|
||||
}
|
||||
const onPress = triggerProps.onPress;
|
||||
return {
|
||||
// React Native Web's Pressable activates Space only for role="button", not checkbox.
|
||||
onKeyDown: (event: {
|
||||
key?: string;
|
||||
repeat?: boolean;
|
||||
target?: unknown;
|
||||
currentTarget?: unknown;
|
||||
preventDefault?: () => void;
|
||||
}) => {
|
||||
if (triggerProps.disabled) return;
|
||||
if (event.target !== event.currentTarget) return;
|
||||
if (event.key === " " || event.key === "Spacebar") {
|
||||
event.preventDefault?.();
|
||||
if (!event.repeat) {
|
||||
onPress(event as unknown as GestureResponderEvent);
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
}, [triggerProps.accessibilityRole, triggerProps.disabled, triggerProps.onPress]);
|
||||
|
||||
return (
|
||||
<ContextMenu open={contextMenuOpen} onOpenChange={onContextMenuOpenChange}>
|
||||
<ContextMenuTrigger
|
||||
{...triggerProps}
|
||||
{...checkboxSpaceKeyProps}
|
||||
enabledOnMobile={false}
|
||||
accessibilityLabel={accessibilityLabel ?? rowAccessibilityLabel}
|
||||
highlightStyle={highlightStyle}
|
||||
@@ -454,6 +498,7 @@ export function SidebarWorkspaceContextMenu({
|
||||
onRename={onRename}
|
||||
onMarkAsRead={onMarkAsRead}
|
||||
onMarkAsUnread={onMarkAsUnread}
|
||||
onSelectWorkspace={onSelectWorkspace}
|
||||
onArchive={onArchive}
|
||||
archiveLabel={archiveLabel}
|
||||
archiveStatus={archiveStatus}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { memo, useMemo, useCallback, useState, type ReactNode } from "react";
|
||||
import { Text, View, type ViewStyle } from "react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { CircleAlert, Folder, FolderGit2, Monitor } from "lucide-react-native";
|
||||
import { Check, CircleAlert, Folder, FolderGit2, Monitor } from "lucide-react-native";
|
||||
import { bySizing } from "@/components/ui/control-geometry";
|
||||
import { ProjectStatusIndicator } from "@/components/sidebar/project-leading-visual";
|
||||
import type { SidebarSurfaceBackdrop } from "@/styles/surface-backdrop";
|
||||
import {
|
||||
@@ -40,19 +41,26 @@ const needsInputColorMapping = (theme: Theme) => ({
|
||||
color: theme.colors.surface0,
|
||||
fill: getStatusDotColor({ theme, bucket: "needs_input" }) ?? undefined,
|
||||
});
|
||||
const checkedIconMapping = (theme: Theme) => ({
|
||||
color: theme.colors.accentForeground,
|
||||
});
|
||||
|
||||
const ThemedCheck = withUnistyles(Check);
|
||||
const ThemedCircleAlert = withUnistyles(CircleAlert);
|
||||
|
||||
export function SidebarWorkspaceRowFrame({
|
||||
workspace,
|
||||
isDragging = false,
|
||||
isEditingTitle = false,
|
||||
isSelectionMode = false,
|
||||
children,
|
||||
}: {
|
||||
workspace: SidebarWorkspaceEntry;
|
||||
isDragging?: boolean;
|
||||
/** Hover would fade the kebab in over the title being edited and open the hover card. */
|
||||
isEditingTitle?: boolean;
|
||||
/** Hover cards would cover neighbouring rows while the user clicks through a selection. */
|
||||
isSelectionMode?: boolean;
|
||||
children: (input: {
|
||||
isHovered: boolean;
|
||||
contextMenuOpen: boolean;
|
||||
@@ -80,7 +88,7 @@ export function SidebarWorkspaceRowFrame({
|
||||
workspace={workspace}
|
||||
prHint={workspace.prHint}
|
||||
isDragging={isDragging}
|
||||
disabled={contextMenuOpen || isEditingTitle}
|
||||
disabled={contextMenuOpen || isEditingTitle || isSelectionMode}
|
||||
>
|
||||
{children({
|
||||
isHovered: isHovered && !contextMenuOpen && !isDragging && !isEditingTitle,
|
||||
@@ -102,6 +110,8 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
|
||||
isHovered,
|
||||
isLoading,
|
||||
isCreating = false,
|
||||
isSelectionMode = false,
|
||||
isBulkSelected = false,
|
||||
shortcutNumber = null,
|
||||
showShortcutBadge = false,
|
||||
reserveIdleStatusIndicatorSpace = true,
|
||||
@@ -119,6 +129,8 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
|
||||
isHovered: boolean;
|
||||
isLoading: boolean;
|
||||
isCreating?: boolean;
|
||||
isSelectionMode?: boolean;
|
||||
isBulkSelected?: boolean;
|
||||
shortcutNumber?: number | null;
|
||||
showShortcutBadge?: boolean;
|
||||
/** Keep the empty leading slot when the workspace has no active status. */
|
||||
@@ -137,33 +149,44 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
|
||||
const workspaceBranchTextStyle = useMemo(
|
||||
() => [
|
||||
styles.workspaceBranchText,
|
||||
isHovered && styles.workspaceBranchTextHovered,
|
||||
(isHovered || isBulkSelected) && styles.workspaceBranchTextHovered,
|
||||
isCreating && styles.workspaceBranchTextCreating,
|
||||
],
|
||||
[isHovered, isCreating],
|
||||
[isHovered, isBulkSelected, isCreating],
|
||||
);
|
||||
|
||||
let leadingVisual: ReactNode;
|
||||
if (isSelectionMode) {
|
||||
leadingVisual = (
|
||||
<WorkspaceSelectionCheckbox checked={isBulkSelected} workspaceKey={workspace.workspaceKey} />
|
||||
);
|
||||
} else if (leadingProjectName) {
|
||||
leadingVisual = (
|
||||
<ProjectStatusIndicator
|
||||
iconDataUri={leadingProjectIconDataUri}
|
||||
displayName={leadingProjectName}
|
||||
projectViewKey={workspace.projectViewKey}
|
||||
statusBucket={workspace.statusBucket}
|
||||
backdrop={backdrop}
|
||||
loading={isLoading}
|
||||
testID={`sidebar-row-project-icon-${workspace.workspaceKey}`}
|
||||
/>
|
||||
);
|
||||
} else {
|
||||
leadingVisual = (
|
||||
<WorkspaceStatusIndicator
|
||||
bucket={workspace.statusBucket}
|
||||
workspaceKind={workspace.workspaceKind}
|
||||
loading={isLoading}
|
||||
reserveIdleSpace={reserveIdleStatusIndicatorSpace}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={styles.workspaceRowContent}>
|
||||
<View style={styles.workspaceRowMain}>
|
||||
{leadingProjectName ? (
|
||||
<ProjectStatusIndicator
|
||||
iconDataUri={leadingProjectIconDataUri}
|
||||
displayName={leadingProjectName}
|
||||
projectViewKey={workspace.projectViewKey}
|
||||
statusBucket={workspace.statusBucket}
|
||||
backdrop={backdrop}
|
||||
loading={isLoading}
|
||||
testID={`sidebar-row-project-icon-${workspace.workspaceKey}`}
|
||||
/>
|
||||
) : (
|
||||
<WorkspaceStatusIndicator
|
||||
bucket={workspace.statusBucket}
|
||||
workspaceKind={workspace.workspaceKind}
|
||||
loading={isLoading}
|
||||
reserveIdleSpace={reserveIdleStatusIndicatorSpace}
|
||||
/>
|
||||
)}
|
||||
{leadingVisual}
|
||||
<View style={styles.workspaceContentColumn}>
|
||||
<View style={styles.workspaceTitleRow}>
|
||||
{titleEditor ? (
|
||||
@@ -191,7 +214,7 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
{showShortcutBadge && shortcutNumber !== null ? (
|
||||
{!isSelectionMode && showShortcutBadge && shortcutNumber !== null ? (
|
||||
<View style={styles.shortcutBadgeOverlay} pointerEvents="none">
|
||||
<SidebarWorkspaceShortcutBadge number={shortcutNumber} />
|
||||
</View>
|
||||
@@ -200,6 +223,22 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
|
||||
);
|
||||
});
|
||||
|
||||
function WorkspaceSelectionCheckbox({
|
||||
checked,
|
||||
workspaceKey,
|
||||
}: {
|
||||
checked: boolean;
|
||||
workspaceKey: string;
|
||||
}) {
|
||||
return (
|
||||
<View style={styles.workspaceStatusDot} testID={`sidebar-workspace-checkbox-${workspaceKey}`}>
|
||||
<View style={checked ? styles.selectionCheckboxChecked : styles.selectionCheckbox}>
|
||||
{checked ? <ThemedCheck size={11} strokeWidth={2.5} uniProps={checkedIconMapping} /> : null}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function WorkspaceStatusIndicator({
|
||||
bucket,
|
||||
workspaceKind,
|
||||
@@ -382,6 +421,7 @@ export function resolveTrailingActionVisibility({
|
||||
isHovered,
|
||||
isTouchPlatform,
|
||||
showShortcut,
|
||||
isSelectionMode = false,
|
||||
}: {
|
||||
workspace: SidebarWorkspaceEntry;
|
||||
trailing: SidebarWorkspaceTrailing;
|
||||
@@ -389,6 +429,7 @@ export function resolveTrailingActionVisibility({
|
||||
isHovered: boolean;
|
||||
isTouchPlatform: boolean;
|
||||
showShortcut: boolean;
|
||||
isSelectionMode?: boolean;
|
||||
}): {
|
||||
trailingPresentation: SidebarWorkspaceTrailingPresentation;
|
||||
showKebab: boolean;
|
||||
@@ -398,10 +439,11 @@ export function resolveTrailingActionVisibility({
|
||||
reserveSlotWidth: boolean;
|
||||
} {
|
||||
const hasTrailing = hasSidebarWorkspaceTrailing({ workspace, trailing });
|
||||
const showKebab = Boolean(hasArchiveAction && (isHovered || isTouchPlatform)) && !showShortcut;
|
||||
const allowRowActions = hasArchiveAction && !isSelectionMode;
|
||||
const showKebab = Boolean(allowRowActions && (isHovered || isTouchPlatform)) && !showShortcut;
|
||||
// Touch permanently replaces the stats with the menu. Only temporary shortcut hints
|
||||
// conceal content while retaining its width, so desktop rows do not shift.
|
||||
const hasContent = hasTrailing && !(hasArchiveAction && isTouchPlatform);
|
||||
const hasContent = hasTrailing && !(allowRowActions && isTouchPlatform);
|
||||
let trailingPresentation: SidebarWorkspaceTrailingPresentation = "absent";
|
||||
if (hasContent) trailingPresentation = showShortcut ? "hidden" : "visible";
|
||||
return {
|
||||
@@ -414,12 +456,12 @@ export function resolveTrailingActionVisibility({
|
||||
// row — over an unhovered one the gradient fades to the wrong color. That is also why
|
||||
// touch, which shows the kebab without ever hovering, never gets one.
|
||||
showScrim: showKebab && isHovered,
|
||||
renderSlot: hasArchiveAction || hasTrailing,
|
||||
renderSlot: allowRowActions || hasTrailing,
|
||||
// The slot only holds width for something that permanently sits in it. Trailing content
|
||||
// does; the kebab only does on touch, where there is no hover for it to appear on and so
|
||||
// no scrim to let it overlay the title. Everywhere else the width goes back to the title
|
||||
// and the kebab fades in over its tail.
|
||||
reserveSlotWidth: hasContent || (hasArchiveAction && isTouchPlatform),
|
||||
reserveSlotWidth: hasContent || (allowRowActions && isTouchPlatform),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -536,6 +578,25 @@ const styles = StyleSheet.create((theme) => ({
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
selectionCheckbox: {
|
||||
width: bySizing({ touch: 18, pointer: 15 }),
|
||||
height: bySizing({ touch: 18, pointer: 15 }),
|
||||
borderRadius: theme.borderRadius.sm,
|
||||
borderWidth: 1.5,
|
||||
borderColor: theme.colors.borderAccent,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
selectionCheckboxChecked: {
|
||||
width: bySizing({ touch: 18, pointer: 15 }),
|
||||
height: bySizing({ touch: 18, pointer: 15 }),
|
||||
borderRadius: theme.borderRadius.sm,
|
||||
borderWidth: 1.5,
|
||||
borderColor: theme.colors.accent,
|
||||
backgroundColor: theme.colors.accent,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
statusDotOverlay: {
|
||||
position: "absolute",
|
||||
right: 0,
|
||||
|
||||
@@ -16,6 +16,7 @@ import Animated, { FadeIn, FadeOut } from "react-native-reanimated";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { SPACING, type Theme } from "@/styles/theme";
|
||||
import { CONTROL_HEIGHTS, mapLayout } from "@/components/ui/control-geometry";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
@@ -28,10 +29,16 @@ import {
|
||||
} from "@/constants/layout";
|
||||
|
||||
export type ToastVariant = "default" | "info" | "success" | "warning" | "error";
|
||||
/**
|
||||
* `action` tightens vertical and trailing insets around `size="sm"` pill controls and uses a
|
||||
* concentric corner radius (`controlHeight / 2 + inset`) so buttons nest evenly in the shell.
|
||||
*/
|
||||
export type ToastLayout = "default" | "action";
|
||||
|
||||
export interface ToastShowOptions {
|
||||
icon?: ReactNode;
|
||||
variant?: ToastVariant;
|
||||
layout?: ToastLayout;
|
||||
durationMs?: number | null;
|
||||
nativeAndroid?: boolean;
|
||||
testID?: string;
|
||||
@@ -45,6 +52,7 @@ export interface ToastState {
|
||||
nativeMessage: string | null;
|
||||
icon?: ReactNode;
|
||||
variant: ToastVariant;
|
||||
layout?: ToastLayout;
|
||||
durationMs: number | null;
|
||||
testID?: string;
|
||||
onDismiss?: () => void;
|
||||
@@ -73,6 +81,11 @@ const TOAST_MAX_WIDTH = 480;
|
||||
/** How long a toast takes to fade in or out. */
|
||||
export const TOAST_FADE_MS = 140;
|
||||
const SIDEBAR_TOAST_INSET = SPACING[2];
|
||||
const ACTION_TOAST_INSET = SPACING[1.5];
|
||||
const ACTION_TOAST_RADIUS = mapLayout(
|
||||
CONTROL_HEIGHTS.sm,
|
||||
(height) => height / 2 + ACTION_TOAST_INSET,
|
||||
);
|
||||
const toastEntering = FadeIn.duration(TOAST_FADE_MS);
|
||||
const toastExiting = FadeOut.duration(TOAST_FADE_MS);
|
||||
const ThemedCheckCircle = withUnistyles(CheckCircle2);
|
||||
@@ -136,6 +149,7 @@ export function useToastHost(): {
|
||||
nativeMessage,
|
||||
icon: options?.icon,
|
||||
variant,
|
||||
layout: options?.layout,
|
||||
durationMs,
|
||||
testID: options?.testID,
|
||||
onDismiss: options?.onDismiss,
|
||||
@@ -163,11 +177,14 @@ export function useToastHost(): {
|
||||
|
||||
export function ToastViewport({
|
||||
toast,
|
||||
persistentToast = null,
|
||||
onDismiss,
|
||||
placement = "app-shell",
|
||||
onBottomCoverageChange,
|
||||
}: {
|
||||
toast: ToastState | null;
|
||||
/** Sidebar placement: persistent bar (such as select mode) that stays visible below transient toasts. */
|
||||
persistentToast?: ToastState | null;
|
||||
/** Called with the ID of the toast that timed out. */
|
||||
onDismiss: (id: number) => void;
|
||||
placement?: ToastViewportPlacement;
|
||||
@@ -232,7 +249,10 @@ export function ToastViewport({
|
||||
|
||||
const handleSidebarLayout = useCallback(
|
||||
(event: LayoutChangeEvent) => {
|
||||
onBottomCoverageChange?.(event.nativeEvent.layout.height + SIDEBAR_TOAST_INSET);
|
||||
const height = event.nativeEvent.layout.height;
|
||||
if (height > 0) {
|
||||
onBottomCoverageChange?.(height + SIDEBAR_TOAST_INSET);
|
||||
}
|
||||
},
|
||||
[onBottomCoverageChange],
|
||||
);
|
||||
@@ -243,28 +263,41 @@ export function ToastViewport({
|
||||
const topOffset =
|
||||
placement === "app-shell" ? insets.top + headerTopPadding + headerHeight : panelClearance;
|
||||
|
||||
if (placement === "sidebar") {
|
||||
return (
|
||||
<View
|
||||
style={animatedStyles.sidebarContainer}
|
||||
pointerEvents="box-none"
|
||||
collapsable={false}
|
||||
onLayout={handleSidebarLayout}
|
||||
>
|
||||
<SidebarToastSlot
|
||||
toast={toast}
|
||||
onPointerEnter={pauseDismiss}
|
||||
onPointerLeave={resumeDismiss}
|
||||
/>
|
||||
<SidebarToastSlot
|
||||
toast={persistentToast}
|
||||
onPointerEnter={noopDismiss}
|
||||
onPointerLeave={noopDismiss}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
// Keep the bottom anchor and its contents together while the native exit retains the view.
|
||||
const content = toast ? (
|
||||
<Animated.View
|
||||
entering={toastEntering}
|
||||
exiting={toastExiting}
|
||||
style={
|
||||
placement === "sidebar"
|
||||
? animatedStyles.sidebarContainer
|
||||
: [
|
||||
animatedStyles.container,
|
||||
{ top: topOffset + (placement === "app-shell" ? SPACING[2] : SPACING[3]) },
|
||||
]
|
||||
}
|
||||
style={[
|
||||
animatedStyles.container,
|
||||
{ top: topOffset + (placement === "app-shell" ? SPACING[2] : SPACING[3]) },
|
||||
]}
|
||||
pointerEvents="box-none"
|
||||
collapsable={false}
|
||||
onLayout={placement === "sidebar" ? handleSidebarLayout : undefined}
|
||||
>
|
||||
<View
|
||||
style={placement === "sidebar" ? styles.sidebarWidthBoundary : styles.widthBoundary}
|
||||
pointerEvents="box-none"
|
||||
collapsable={false}
|
||||
>
|
||||
<View style={styles.widthBoundary} pointerEvents="box-none" collapsable={false}>
|
||||
<View
|
||||
style={animatedStyles.surface}
|
||||
testID={toast.testID ?? "app-toast"}
|
||||
@@ -283,6 +316,35 @@ export function ToastViewport({
|
||||
return placement === "panel" ? <FloatingHeaderOverlay>{content}</FloatingHeaderOverlay> : content;
|
||||
}
|
||||
|
||||
function SidebarToastSlot({
|
||||
toast,
|
||||
onPointerEnter,
|
||||
onPointerLeave,
|
||||
}: {
|
||||
toast: ToastState | null;
|
||||
onPointerEnter: () => void;
|
||||
onPointerLeave: () => void;
|
||||
}) {
|
||||
if (!toast) return null;
|
||||
return (
|
||||
<Animated.View
|
||||
entering={toastEntering}
|
||||
exiting={toastExiting}
|
||||
style={styles.sidebarWidthBoundary}
|
||||
pointerEvents="box-none"
|
||||
collapsable={false}
|
||||
>
|
||||
<View
|
||||
style={animatedStyles.surface}
|
||||
testID={toast.testID ?? "app-toast"}
|
||||
accessibilityRole="alert"
|
||||
>
|
||||
<ToastCard toast={toast} onPointerEnter={onPointerEnter} onPointerLeave={onPointerLeave} />
|
||||
</View>
|
||||
</Animated.View>
|
||||
);
|
||||
}
|
||||
|
||||
function ToastCard({
|
||||
toast,
|
||||
onPointerEnter,
|
||||
@@ -310,6 +372,7 @@ function ToastCard({
|
||||
onPointerLeave={onPointerLeave}
|
||||
style={[
|
||||
styles.toast,
|
||||
toast.layout === "action" ? styles.toastAction : null,
|
||||
toast.variant === "info" ? styles.toastInfo : null,
|
||||
toast.variant === "warning" ? styles.toastWarning : null,
|
||||
toast.variant === "error" ? styles.toastError : null,
|
||||
@@ -344,6 +407,7 @@ const animatedStyles = NativeStyleSheet.create({
|
||||
bottom: SIDEBAR_TOAST_INSET,
|
||||
zIndex: OVERLAY_Z.toast,
|
||||
alignItems: "center",
|
||||
gap: SIDEBAR_TOAST_INSET,
|
||||
},
|
||||
surface: { alignSelf: "center", maxWidth: "100%" },
|
||||
});
|
||||
@@ -372,6 +436,12 @@ const styles = StyleSheet.create((theme) => ({
|
||||
paddingHorizontal: theme.spacing[3],
|
||||
...theme.shadow.md,
|
||||
},
|
||||
toastAction: {
|
||||
borderRadius: ACTION_TOAST_RADIUS,
|
||||
paddingVertical: theme.spacing[1.5],
|
||||
paddingLeft: theme.spacing[3.5],
|
||||
paddingRight: theme.spacing[1.5],
|
||||
},
|
||||
toastInfo: {
|
||||
borderColor: theme.colors.palette.blue[300],
|
||||
},
|
||||
|
||||
@@ -146,6 +146,8 @@ export interface ComboboxProps {
|
||||
/** When true, selecting an option does not close the picker (multi-select mode). */
|
||||
keepOpenOnSelect?: boolean;
|
||||
anchorRef: React.RefObject<View | null>;
|
||||
/** Where focus goes when the picker closes. Defaults to whatever had focus when it opened. */
|
||||
restoreFocusRef?: React.RefObject<unknown>;
|
||||
children?: ReactNode;
|
||||
}
|
||||
|
||||
@@ -1437,6 +1439,7 @@ export function Combobox({
|
||||
footer,
|
||||
keepOpenOnSelect = false,
|
||||
anchorRef,
|
||||
restoreFocusRef,
|
||||
children,
|
||||
}: ComboboxProps): ReactElement | null {
|
||||
const { t } = useTranslation();
|
||||
@@ -1728,6 +1731,7 @@ export function Combobox({
|
||||
layer: floatingLayer,
|
||||
keys: ["Escape", "Enter", "ArrowUp", "ArrowDown"],
|
||||
onKeyDown: (event) => (isDesktopKey(event.key) ? handleDesktopKey(event.key, event) : false),
|
||||
restoreFocusRef,
|
||||
});
|
||||
|
||||
const effectiveSearchPlaceholder = searchPlaceholder ?? resolvedPlaceholder;
|
||||
|
||||
@@ -385,16 +385,6 @@ 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,
|
||||
@@ -405,7 +395,6 @@ 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;
|
||||
|
||||
@@ -146,3 +146,41 @@ export async function confirmRiskyWorktreeArchive(
|
||||
destructive: true,
|
||||
});
|
||||
}
|
||||
|
||||
export async function confirmRiskyBulkWorktreeArchive(
|
||||
input: {
|
||||
totalCount: number;
|
||||
riskyWorkspaces: readonly WorktreeArchiveConfirmationInput[];
|
||||
},
|
||||
labels: WorktreeArchiveWarningLabels = DEFAULT_WORKTREE_ARCHIVE_WARNING_LABELS,
|
||||
): Promise<boolean> {
|
||||
const lines: string[] = [];
|
||||
let singleRisky: WorktreeArchiveConfirmationInput | null = null;
|
||||
for (const workspace of input.riskyWorkspaces) {
|
||||
const reasons = buildWorktreeArchiveRiskReasons(workspace, labels);
|
||||
if (reasons.length === 0) continue;
|
||||
singleRisky = workspace;
|
||||
lines.push(
|
||||
i18n.t("workspace.git.actions.archiveWarning.bulkWorkspaceReason", {
|
||||
workspaceName: workspace.workspaceName,
|
||||
reason: reasons.join(", "),
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (lines.length === 0) {
|
||||
return true;
|
||||
}
|
||||
if (input.totalCount === 1 && singleRisky) {
|
||||
return await confirmRiskyWorktreeArchive(singleRisky, labels);
|
||||
}
|
||||
|
||||
return await confirmDialog({
|
||||
title: i18n.t("workspace.git.actions.archiveWarning.bulkTitle", {
|
||||
count: input.totalCount,
|
||||
}),
|
||||
message: lines.join("\n"),
|
||||
confirmLabel: labels.confirm,
|
||||
cancelLabel: labels.cancel,
|
||||
destructive: true,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -166,7 +166,7 @@ describe("ensureAgentIsInitialized", () => {
|
||||
kind: "assistant_message",
|
||||
id: "canonical-item",
|
||||
text: "Canonical before restart",
|
||||
timelineCursor: { epoch: "epoch-1", seq: 12, anchorSeq: 12 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 12 },
|
||||
timestamp: new Date("2026-07-27T10:00:00.000Z"),
|
||||
},
|
||||
],
|
||||
|
||||
@@ -741,8 +741,6 @@ export const ar: TranslationResources = {
|
||||
resumeCommandUnavailable: "أمر الاستئناف غير متوفر",
|
||||
reloadingAgent: "وكيل إعادة التحميل...",
|
||||
reloadedAgent: "وكيل إعادة تحميل",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"تمت إعادة تحميل الوكيل، لكن سجل المزوّد لا يطابق هذه المحادثة، لذا لم تتم مزامنته",
|
||||
failedToReloadAgent: "فشل في إعادة تحميل الوكيل",
|
||||
failedToCloseAgent: "فشل في إغلاق الوكيل",
|
||||
},
|
||||
@@ -962,6 +960,8 @@ export const ar: TranslationResources = {
|
||||
},
|
||||
archiveWarning: {
|
||||
title: 'الأرشيف "{{workspaceName}}"؟',
|
||||
bulkTitle: "أرشفة {{count}} مساحات عمل؟",
|
||||
bulkWorkspaceReason: "{{workspaceName}}: {{reason}}",
|
||||
confirm: "أرشيف",
|
||||
cancel: "يلغي",
|
||||
uncommittedChanges: "تغييرات غير ملتزم بها",
|
||||
@@ -1371,6 +1371,7 @@ export const ar: TranslationResources = {
|
||||
rename: "إعادة تسمية مساحة العمل",
|
||||
pin: "تثبيت في الأعلى",
|
||||
unpin: "إلغاء التثبيت",
|
||||
select: "تحديد",
|
||||
archive: "أرشيف",
|
||||
archiveWorkspace: "أرشفة مساحة العمل",
|
||||
hideFromSidebar: "إخفاء من الشريط الجانبي",
|
||||
@@ -1389,6 +1390,10 @@ export const ar: TranslationResources = {
|
||||
submit: "إعادة تسمية",
|
||||
invalidBranchName: "اسم الفرع غير صالح",
|
||||
},
|
||||
selection: {
|
||||
count: "تم تحديد {{count}}",
|
||||
exit: "إنهاء التحديد",
|
||||
},
|
||||
toasts: {
|
||||
workspacePathUnavailable: "مسار Workspace غير متوفر",
|
||||
pathCopied: "تم نسخ المسار",
|
||||
@@ -1396,7 +1401,9 @@ export const ar: TranslationResources = {
|
||||
hostDisconnected: "Host غير متصل",
|
||||
hideFailed: "فشل في إخفاء مساحة العمل",
|
||||
archiveFailed: "فشل في أرشفة مساحة العمل",
|
||||
archiveMultipleFailed: "فشل في أرشفة {{count}} مساحات عمل",
|
||||
archived: "تمت أرشفة مساحة العمل",
|
||||
archivedCount: "تمت أرشفة {{count}} مساحات عمل",
|
||||
undoArchive: "تراجع",
|
||||
undoArchiveFailed: "تعذّر التراجع عن الأرشفة",
|
||||
},
|
||||
|
||||
@@ -740,8 +740,6 @@ 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",
|
||||
},
|
||||
@@ -973,6 +971,8 @@ export const en = {
|
||||
},
|
||||
archiveWarning: {
|
||||
title: 'Archive "{{workspaceName}}"?',
|
||||
bulkTitle: "Archive {{count}} workspaces?",
|
||||
bulkWorkspaceReason: "{{workspaceName}}: {{reason}}",
|
||||
confirm: "Archive",
|
||||
cancel: "Cancel",
|
||||
uncommittedChanges: "Uncommitted changes",
|
||||
@@ -1382,6 +1382,7 @@ export const en = {
|
||||
rename: "Rename workspace",
|
||||
pin: "Pin to top",
|
||||
unpin: "Unpin",
|
||||
select: "Select",
|
||||
archive: "Archive",
|
||||
archiveWorkspace: "Archive workspace",
|
||||
hideFromSidebar: "Hide from sidebar",
|
||||
@@ -1400,6 +1401,10 @@ export const en = {
|
||||
submit: "Rename",
|
||||
invalidBranchName: "Invalid branch name",
|
||||
},
|
||||
selection: {
|
||||
count: "{{count}} selected",
|
||||
exit: "Exit selection",
|
||||
},
|
||||
toasts: {
|
||||
workspacePathUnavailable: "Workspace path not available",
|
||||
pathCopied: "Path copied",
|
||||
@@ -1407,7 +1412,9 @@ export const en = {
|
||||
hostDisconnected: "Host is not connected",
|
||||
hideFailed: "Failed to hide workspace",
|
||||
archiveFailed: "Failed to archive workspace",
|
||||
archiveMultipleFailed: "Failed to archive {{count}} workspaces",
|
||||
archived: "Workspace archived",
|
||||
archivedCount: "{{count}} workspaces archived",
|
||||
undoArchive: "Undo",
|
||||
undoArchiveFailed: "Couldn't undo the archive",
|
||||
},
|
||||
|
||||
@@ -748,8 +748,6 @@ 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",
|
||||
},
|
||||
@@ -996,6 +994,8 @@ export const es: TranslationResources = {
|
||||
},
|
||||
archiveWarning: {
|
||||
title: '¿Archivo "{{workspaceName}}"?',
|
||||
bulkTitle: "¿Archivar {{count}} espacios de trabajo?",
|
||||
bulkWorkspaceReason: "{{workspaceName}}: {{reason}}",
|
||||
confirm: "Archivo",
|
||||
cancel: "Cancelar",
|
||||
uncommittedChanges: "Cambios no confirmados",
|
||||
@@ -1408,6 +1408,7 @@ export const es: TranslationResources = {
|
||||
rename: "Cambiar nombre del espacio de trabajo",
|
||||
pin: "Anclar arriba",
|
||||
unpin: "Desanclar",
|
||||
select: "Seleccionar",
|
||||
archive: "Archivo",
|
||||
archiveWorkspace: "Archivar espacio de trabajo",
|
||||
hideFromSidebar: "Ocultar de la barra lateral",
|
||||
@@ -1426,6 +1427,10 @@ export const es: TranslationResources = {
|
||||
submit: "Rebautizar",
|
||||
invalidBranchName: "Nombre de sucursal no válido",
|
||||
},
|
||||
selection: {
|
||||
count: "{{count}} seleccionados",
|
||||
exit: "Salir de la selección",
|
||||
},
|
||||
toasts: {
|
||||
workspacePathUnavailable: "RutaWorkspaceno disponible",
|
||||
pathCopied: "Ruta copiada",
|
||||
@@ -1433,7 +1438,9 @@ export const es: TranslationResources = {
|
||||
hostDisconnected: "Hostno está conectado",
|
||||
hideFailed: "No se pudo ocultar el espacio de trabajo",
|
||||
archiveFailed: "No se pudo archivar el espacio de trabajo",
|
||||
archiveMultipleFailed: "No se pudieron archivar {{count}} espacios de trabajo",
|
||||
archived: "Espacio de trabajo archivado",
|
||||
archivedCount: "{{count}} espacios de trabajo archivados",
|
||||
undoArchive: "Deshacer",
|
||||
undoArchiveFailed: "No se pudo deshacer el archivado",
|
||||
},
|
||||
|
||||
@@ -748,8 +748,6 @@ 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",
|
||||
},
|
||||
@@ -988,6 +986,8 @@ export const fr: TranslationResources = {
|
||||
},
|
||||
archiveWarning: {
|
||||
title: "Archiver « {{workspaceName}} » ?",
|
||||
bulkTitle: "Archiver {{count}} espaces de travail ?",
|
||||
bulkWorkspaceReason: "{{workspaceName}} : {{reason}}",
|
||||
confirm: "Archiver",
|
||||
cancel: "Annuler",
|
||||
uncommittedChanges: "Modifications non commitées",
|
||||
@@ -1401,6 +1401,7 @@ export const fr: TranslationResources = {
|
||||
rename: "Renommer l’espace de travail",
|
||||
pin: "Épingler en haut",
|
||||
unpin: "Désépingler",
|
||||
select: "Sélectionner",
|
||||
archive: "Archiver",
|
||||
archiveWorkspace: "Archiver l’espace de travail",
|
||||
hideFromSidebar: "Masquer de la barre latérale",
|
||||
@@ -1419,6 +1420,10 @@ export const fr: TranslationResources = {
|
||||
submit: "Renommer",
|
||||
invalidBranchName: "Nom de branche invalide",
|
||||
},
|
||||
selection: {
|
||||
count: "{{count}} sélectionnés",
|
||||
exit: "Quitter la sélection",
|
||||
},
|
||||
toasts: {
|
||||
workspacePathUnavailable: "Chemin de l’espace de travail indisponible",
|
||||
pathCopied: "Chemin copié",
|
||||
@@ -1426,7 +1431,9 @@ export const fr: TranslationResources = {
|
||||
hostDisconnected: "L’hôte n’est pas connecté",
|
||||
hideFailed: "Impossible de masquer l’espace de travail",
|
||||
archiveFailed: "Impossible d’archiver l’espace de travail",
|
||||
archiveMultipleFailed: "Impossible d’archiver {{count}} espaces de travail",
|
||||
archived: "Espace de travail archivé",
|
||||
archivedCount: "{{count}} espaces de travail archivés",
|
||||
undoArchive: "Annuler",
|
||||
undoArchiveFailed: "Impossible d’annuler l’archivage",
|
||||
},
|
||||
|
||||
@@ -748,8 +748,6 @@ export const ja: TranslationResources = {
|
||||
resumeCommandUnavailable: "再開コマンドが利用できません",
|
||||
reloadingAgent: "エージェントを再読み込み中...",
|
||||
reloadedAgent: "エージェントを再読み込みしました",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"エージェントを再読み込みしましたが、プロバイダーの履歴がこのチャットと一致しないため同期しませんでした",
|
||||
failedToReloadAgent: "エージェントの再読み込みに失敗しました",
|
||||
failedToCloseAgent: "エージェントを閉じられませんでした",
|
||||
},
|
||||
@@ -976,6 +974,8 @@ export const ja: TranslationResources = {
|
||||
},
|
||||
archiveWarning: {
|
||||
title: '"{{workspaceName}}"をアーカイブしますか?',
|
||||
bulkTitle: "{{count}}件のワークスペースをアーカイブしますか?",
|
||||
bulkWorkspaceReason: "{{workspaceName}}:{{reason}}",
|
||||
confirm: "アーカイブ",
|
||||
cancel: "キャンセル",
|
||||
uncommittedChanges: "未コミットの変更",
|
||||
@@ -1386,6 +1386,7 @@ export const ja: TranslationResources = {
|
||||
rename: "ワークスペースの名前を変更",
|
||||
pin: "上部に固定",
|
||||
unpin: "固定解除",
|
||||
select: "選択",
|
||||
archive: "アーカイブ",
|
||||
archiveWorkspace: "ワークスペースをアーカイブ",
|
||||
hideFromSidebar: "サイドバーから非表示",
|
||||
@@ -1404,6 +1405,10 @@ export const ja: TranslationResources = {
|
||||
submit: "名前を変更",
|
||||
invalidBranchName: "無効なブランチ名",
|
||||
},
|
||||
selection: {
|
||||
count: "{{count}}件選択中",
|
||||
exit: "選択を終了",
|
||||
},
|
||||
toasts: {
|
||||
workspacePathUnavailable: "ワークスペースパスが利用できません",
|
||||
pathCopied: "パスをコピーしました",
|
||||
@@ -1411,7 +1416,9 @@ export const ja: TranslationResources = {
|
||||
hostDisconnected: "ホストが接続されていません",
|
||||
hideFailed: "ワークスペースの非表示に失敗しました",
|
||||
archiveFailed: "ワークスペースのアーカイブに失敗しました",
|
||||
archiveMultipleFailed: "{{count}}件のワークスペースのアーカイブに失敗しました",
|
||||
archived: "ワークスペースをアーカイブしました",
|
||||
archivedCount: "{{count}}件のワークスペースをアーカイブしました",
|
||||
undoArchive: "元に戻す",
|
||||
undoArchiveFailed: "アーカイブを元に戻せませんでした",
|
||||
},
|
||||
|
||||
@@ -743,8 +743,6 @@ export const ko: TranslationResources = {
|
||||
resumeCommandUnavailable: "재개 명령을 사용할 수 없습니다",
|
||||
reloadingAgent: "에이전트 다시 로드 중...",
|
||||
reloadedAgent: "에이전트를 다시 로드했습니다",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"에이전트를 다시 로드했지만 제공자 기록이 이 채팅과 일치하지 않아 동기화하지 않았습니다",
|
||||
failedToReloadAgent: "에이전트를 다시 로드하지 못했습니다",
|
||||
failedToCloseAgent: "에이전트를 닫지 못했습니다",
|
||||
},
|
||||
@@ -969,6 +967,8 @@ export const ko: TranslationResources = {
|
||||
},
|
||||
archiveWarning: {
|
||||
title: '"{{workspaceName}}"를 보관하시겠습니까?',
|
||||
bulkTitle: "워크스페이스 {{count}}개를 보관하시겠습니까?",
|
||||
bulkWorkspaceReason: "{{workspaceName}}: {{reason}}",
|
||||
confirm: "보관",
|
||||
cancel: "취소",
|
||||
uncommittedChanges: "커밋되지 않은 변경 사항",
|
||||
@@ -1378,6 +1378,7 @@ export const ko: TranslationResources = {
|
||||
rename: "워크스페이스 이름 변경",
|
||||
pin: "상단에 고정",
|
||||
unpin: "고정 해제",
|
||||
select: "선택",
|
||||
archive: "보관",
|
||||
archiveWorkspace: "워크스페이스 보관",
|
||||
hideFromSidebar: "사이드바에서 숨기기",
|
||||
@@ -1396,6 +1397,10 @@ export const ko: TranslationResources = {
|
||||
submit: "이름 변경",
|
||||
invalidBranchName: "잘못된 브랜치 이름",
|
||||
},
|
||||
selection: {
|
||||
count: "{{count}}개 선택됨",
|
||||
exit: "선택 종료",
|
||||
},
|
||||
toasts: {
|
||||
workspacePathUnavailable: "워크스페이스 경로를 사용할 수 없습니다",
|
||||
pathCopied: "경로가 복사되었습니다",
|
||||
@@ -1403,7 +1408,9 @@ export const ko: TranslationResources = {
|
||||
hostDisconnected: "호스트가 연결되어 있지 않습니다",
|
||||
hideFailed: "워크스페이스를 숨기지 못했습니다",
|
||||
archiveFailed: "워크스페이스를 보관하지 못했습니다.",
|
||||
archiveMultipleFailed: "워크스페이스 {{count}}개를 보관하지 못했습니다",
|
||||
archived: "워크스페이스를 보관했습니다",
|
||||
archivedCount: "워크스페이스 {{count}}개를 보관했습니다",
|
||||
undoArchive: "실행 취소",
|
||||
undoArchiveFailed: "보관을 취소하지 못했습니다",
|
||||
},
|
||||
|
||||
@@ -746,8 +746,6 @@ 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",
|
||||
},
|
||||
@@ -986,6 +984,8 @@ export const ptBR: TranslationResources = {
|
||||
},
|
||||
archiveWarning: {
|
||||
title: 'Arquivar "{{workspaceName}}"?',
|
||||
bulkTitle: "Arquivar {{count}} workspaces?",
|
||||
bulkWorkspaceReason: "{{workspaceName}}: {{reason}}",
|
||||
confirm: "Arquivar",
|
||||
cancel: "Cancelar",
|
||||
uncommittedChanges: "Alterações sem commit",
|
||||
@@ -1398,6 +1398,7 @@ export const ptBR: TranslationResources = {
|
||||
rename: "Renomear workspace",
|
||||
pin: "Fixar no topo",
|
||||
unpin: "Desafixar",
|
||||
select: "Selecionar",
|
||||
archive: "Arquivar",
|
||||
archiveWorkspace: "Arquivar workspace",
|
||||
hideFromSidebar: "Ocultar da barra lateral",
|
||||
@@ -1416,6 +1417,10 @@ export const ptBR: TranslationResources = {
|
||||
submit: "Renomear",
|
||||
invalidBranchName: "Nome de branch inválido",
|
||||
},
|
||||
selection: {
|
||||
count: "{{count}} selecionados",
|
||||
exit: "Sair da seleção",
|
||||
},
|
||||
toasts: {
|
||||
workspacePathUnavailable: "Caminho do workspace indisponível",
|
||||
pathCopied: "Caminho copiado",
|
||||
@@ -1423,7 +1428,9 @@ export const ptBR: TranslationResources = {
|
||||
hostDisconnected: "Host não está conectado",
|
||||
hideFailed: "Falha ao ocultar workspace",
|
||||
archiveFailed: "Falha ao arquivar workspace",
|
||||
archiveMultipleFailed: "Falha ao arquivar {{count}} workspaces",
|
||||
archived: "Workspace arquivado",
|
||||
archivedCount: "{{count}} workspaces arquivados",
|
||||
undoArchive: "Desfazer",
|
||||
undoArchiveFailed: "Não foi possível desfazer o arquivamento",
|
||||
},
|
||||
|
||||
@@ -749,8 +749,6 @@ export const ru: TranslationResources = {
|
||||
resumeCommandUnavailable: "Команда возобновления недоступна",
|
||||
reloadingAgent: "Перезагрузка агента...",
|
||||
reloadedAgent: "Агент перезагружен",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"Агент перезагружен, но история провайдера не совпадает с этим чатом, поэтому она не синхронизирована",
|
||||
failedToReloadAgent: "Не удалось перезагрузить агента",
|
||||
failedToCloseAgent: "Не удалось закрыть агента",
|
||||
},
|
||||
@@ -981,6 +979,8 @@ export const ru: TranslationResources = {
|
||||
},
|
||||
archiveWarning: {
|
||||
title: "Архивировать «{{workspaceName}}»?",
|
||||
bulkTitle: "Архивировать рабочие пространства ({{count}})?",
|
||||
bulkWorkspaceReason: "{{workspaceName}}: {{reason}}",
|
||||
confirm: "Архивировать",
|
||||
cancel: "Отмена",
|
||||
uncommittedChanges: "Незафиксированные изменения",
|
||||
@@ -1391,6 +1391,7 @@ export const ru: TranslationResources = {
|
||||
rename: "Переименовать рабочее пространство",
|
||||
pin: "Закрепить вверху",
|
||||
unpin: "Открепить",
|
||||
select: "Выбрать",
|
||||
archive: "Архивировать",
|
||||
archiveWorkspace: "Архивировать рабочее пространство",
|
||||
hideFromSidebar: "Скрыть на боковой панели",
|
||||
@@ -1409,6 +1410,10 @@ export const ru: TranslationResources = {
|
||||
submit: "Переименовать",
|
||||
invalidBranchName: "Недопустимое имя ветки",
|
||||
},
|
||||
selection: {
|
||||
count: "Выбрано: {{count}}",
|
||||
exit: "Выйти из выбора",
|
||||
},
|
||||
toasts: {
|
||||
workspacePathUnavailable: "Путь к рабочему пространству недоступен",
|
||||
pathCopied: "Путь скопирован",
|
||||
@@ -1416,7 +1421,9 @@ export const ru: TranslationResources = {
|
||||
hostDisconnected: "Хост не подключён",
|
||||
hideFailed: "Не удалось скрыть рабочее пространство",
|
||||
archiveFailed: "Не удалось архивировать рабочее пространство",
|
||||
archiveMultipleFailed: "Не удалось архивировать рабочие пространства ({{count}})",
|
||||
archived: "Рабочее пространство архивировано",
|
||||
archivedCount: "Архивировано рабочих пространств: {{count}}",
|
||||
undoArchive: "Отменить",
|
||||
undoArchiveFailed: "Не удалось отменить архивацию",
|
||||
},
|
||||
|
||||
@@ -741,8 +741,6 @@ export const zhCN: TranslationResources = {
|
||||
resumeCommandUnavailable: "恢复命令不可用",
|
||||
reloadingAgent: "正在重新加载 Agent...",
|
||||
reloadedAgent: "已重新加载 Agent",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"已重新加载 Agent,但提供方的历史记录与此对话不一致,因此未同步",
|
||||
failedToReloadAgent: "重新加载 Agent 失败",
|
||||
failedToCloseAgent: "关闭 Agent 失败",
|
||||
},
|
||||
@@ -954,6 +952,8 @@ export const zhCN: TranslationResources = {
|
||||
},
|
||||
archiveWarning: {
|
||||
title: "归档「{{workspaceName}}」?",
|
||||
bulkTitle: "归档 {{count}} 个工作区?",
|
||||
bulkWorkspaceReason: "{{workspaceName}}:{{reason}}",
|
||||
confirm: "归档",
|
||||
cancel: "取消",
|
||||
uncommittedChanges: "未 commit 的变更",
|
||||
@@ -1361,6 +1361,7 @@ export const zhCN: TranslationResources = {
|
||||
rename: "重命名 workspace",
|
||||
pin: "置顶",
|
||||
unpin: "取消置顶",
|
||||
select: "选择",
|
||||
archive: "归档",
|
||||
archiveWorkspace: "归档工作区",
|
||||
hideFromSidebar: "从侧边栏隐藏",
|
||||
@@ -1378,6 +1379,10 @@ export const zhCN: TranslationResources = {
|
||||
submit: "重命名",
|
||||
invalidBranchName: "无效的分支名称",
|
||||
},
|
||||
selection: {
|
||||
count: "已选 {{count}} 项",
|
||||
exit: "退出选择",
|
||||
},
|
||||
toasts: {
|
||||
workspacePathUnavailable: "Workspace 路径不可用",
|
||||
pathCopied: "路径已复制",
|
||||
@@ -1385,7 +1390,9 @@ export const zhCN: TranslationResources = {
|
||||
hostDisconnected: "Host 未连接",
|
||||
hideFailed: "隐藏 workspace 失败",
|
||||
archiveFailed: "归档工作区失败",
|
||||
archiveMultipleFailed: "归档 {{count}} 个工作区失败",
|
||||
archived: "工作区已归档",
|
||||
archivedCount: "已归档 {{count}} 个工作区",
|
||||
undoArchive: "撤销",
|
||||
undoArchiveFailed: "无法撤销归档",
|
||||
},
|
||||
|
||||
@@ -14,3 +14,4 @@ export type { HardwareKeyboardEvent } from "./internal/sources/hardware";
|
||||
export { usesDesktopBindings, supportsConfigurableComposerSendKeys } from "./internal/conventions";
|
||||
export type { BrowserKeyboardPolicy } from "./internal/sources/electron-browser";
|
||||
export { useHardwareKeyboardPresent } from "./availability";
|
||||
export { isShiftKeyDown } from "./internal/shift-modifier";
|
||||
|
||||
@@ -9,6 +9,10 @@ export interface OverlayRegistration {
|
||||
*/
|
||||
keys: readonly string[];
|
||||
onKeyDown(event: KeyboardInputEvent): boolean;
|
||||
/**
|
||||
* Where focus goes when the overlay closes: an element, or any handle with `focus()`. Defaults
|
||||
* to whatever had focus when the overlay opened.
|
||||
*/
|
||||
restoreFocusRef?: RefObject<unknown>;
|
||||
manageFocus?: boolean;
|
||||
}
|
||||
|
||||
@@ -3,12 +3,29 @@ import { overlays, type OverlayEntry, type KeyboardInputEvent } from "./overlays
|
||||
import type { OverlayRegistration } from "./overlay-contract";
|
||||
type WebOverlayKeyHandler = (event: KeyboardInputEvent) => boolean;
|
||||
|
||||
/** A DOM element, or a component handle that knows how to focus itself (such as a text input). */
|
||||
interface FocusTarget {
|
||||
focus(): void;
|
||||
}
|
||||
|
||||
function isFocusTarget(value: unknown): value is FocusTarget {
|
||||
return (
|
||||
typeof value === "object" &&
|
||||
value !== null &&
|
||||
typeof (value as Partial<FocusTarget>).focus === "function"
|
||||
);
|
||||
}
|
||||
|
||||
function canRestoreFocusTo(target: FocusTarget): boolean {
|
||||
return !(target instanceof HTMLElement) || document.contains(target);
|
||||
}
|
||||
|
||||
interface WebOverlayEntry {
|
||||
getLayer: () => number;
|
||||
getKeys: () => readonly string[];
|
||||
getScope: () => HTMLElement | null;
|
||||
getKeyHandler: () => WebOverlayKeyHandler;
|
||||
restoreFocus: HTMLElement | null;
|
||||
restoreFocus: FocusTarget | null;
|
||||
manageFocus: boolean;
|
||||
}
|
||||
|
||||
@@ -156,7 +173,7 @@ function addWebOverlay(entry: WebOverlayEntry): (options?: RemoveWebOverlayOptio
|
||||
entry.manageFocus &&
|
||||
options?.restoreFocus !== false &&
|
||||
entry.restoreFocus &&
|
||||
document.contains(entry.restoreFocus)
|
||||
canRestoreFocusTo(entry.restoreFocus)
|
||||
) {
|
||||
entry.restoreFocus.focus();
|
||||
}
|
||||
@@ -181,7 +198,7 @@ export function useOverlayRegistration({
|
||||
keysRef.current = keys;
|
||||
const layerRef = useRef(layer);
|
||||
const keyHandlerRef = useRef(onKeyDown);
|
||||
const capturedRestoreFocusRef = useRef<HTMLElement | null>(null);
|
||||
const capturedRestoreFocusRef = useRef<FocusTarget | null>(null);
|
||||
const removeEntryRef = useRef<((options?: RemoveWebOverlayOptions) => void) | null>(null);
|
||||
const detachedRemoveEntryRef = useRef<((options?: RemoveWebOverlayOptions) => void) | null>(null);
|
||||
const registeredRef = useRef(false);
|
||||
@@ -193,7 +210,7 @@ export function useOverlayRegistration({
|
||||
keyHandlerRef.current = onKeyDown;
|
||||
if (active && !wasActiveRef.current && typeof document !== "undefined") {
|
||||
const requestedRestoreTarget = preferredRestoreFocusRef?.current;
|
||||
if (requestedRestoreTarget instanceof HTMLElement) {
|
||||
if (isFocusTarget(requestedRestoreTarget)) {
|
||||
capturedRestoreFocusRef.current = requestedRestoreTarget;
|
||||
} else {
|
||||
capturedRestoreFocusRef.current =
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
export interface ShiftModifierKeyEvent {
|
||||
key: string;
|
||||
code?: string;
|
||||
shiftKey: boolean;
|
||||
}
|
||||
|
||||
export interface ShiftModifierTracker {
|
||||
isDown(): boolean;
|
||||
handleKeyDown(event: ShiftModifierKeyEvent): void;
|
||||
handleKeyUp(event: ShiftModifierKeyEvent): void;
|
||||
reset(): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tracks whether a physical Shift key is currently held across DOM and native
|
||||
* hardware keyboard streams so touch/pointer press handlers that omit
|
||||
* `shiftKey` (native GestureResponderEvent, touch-synthesized clicks) can still
|
||||
* observe Shift+tap and Shift+click.
|
||||
*/
|
||||
export function createShiftModifierTracker(): ShiftModifierTracker {
|
||||
const pressedCodes = new Set<string>();
|
||||
return {
|
||||
isDown: () => pressedCodes.size > 0,
|
||||
handleKeyDown(event) {
|
||||
if (event.key === "Shift") {
|
||||
pressedCodes.add(event.code || "Shift");
|
||||
} else if (!event.shiftKey && pressedCodes.size > 0) {
|
||||
pressedCodes.clear();
|
||||
}
|
||||
},
|
||||
handleKeyUp(event) {
|
||||
if (event.key === "Shift") {
|
||||
pressedCodes.delete(event.code || "Shift");
|
||||
if (!event.shiftKey) {
|
||||
pressedCodes.clear();
|
||||
}
|
||||
} else if (!event.shiftKey && pressedCodes.size > 0) {
|
||||
pressedCodes.clear();
|
||||
}
|
||||
},
|
||||
reset() {
|
||||
pressedCodes.clear();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export const shiftModifier = createShiftModifierTracker();
|
||||
|
||||
export function isShiftKeyDown(): boolean {
|
||||
return shiftModifier.isDown();
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AppState } from "react-native";
|
||||
import type { KeyboardPolicyInput, KeyboardSourceHandlers } from "./contract";
|
||||
import {
|
||||
setHardwareKeyboardClaimedShortcuts,
|
||||
@@ -7,6 +8,14 @@ import {
|
||||
import { createHardwareKeyboardSource } from "./native";
|
||||
const hardwareKeyboard = createHardwareKeyboardSource({
|
||||
subscribe: subscribeHardwareKeyboard,
|
||||
subscribeBlur: (onBlur) => {
|
||||
const subscription = AppState.addEventListener("change", (nextState) => {
|
||||
if (nextState !== "active") {
|
||||
onBlur();
|
||||
}
|
||||
});
|
||||
return () => subscription.remove();
|
||||
},
|
||||
setOverlayKeys: setHardwareKeyboardOverlayKeys,
|
||||
setClaimedShortcuts: setHardwareKeyboardClaimedShortcuts,
|
||||
});
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
import type { ClaimedShortcut, HardwareKeyboardEvent } from "./hardware";
|
||||
interface HardwareKeySource {
|
||||
subscribe(handler: (event: HardwareKeyboardEvent) => void): () => void;
|
||||
subscribeBlur?(handler: () => void): () => void;
|
||||
setOverlayKeys(keys: readonly string[]): void;
|
||||
setClaimedShortcuts(shortcuts: readonly ClaimedShortcut[]): void;
|
||||
}
|
||||
@@ -78,7 +79,9 @@ export function createHardwareKeyboardSource(source: HardwareKeySource) {
|
||||
nativeKeyboardInput(event, focusSurfaces.resolve(handlers.commandCenterOpen())),
|
||||
);
|
||||
});
|
||||
const unsubscribeBlur = source.subscribeBlur?.(() => handlers.blur()) ?? (() => {});
|
||||
return () => {
|
||||
unsubscribeBlur();
|
||||
unsubscribeHardware();
|
||||
unsubscribeFocus();
|
||||
unsubscribeCommandCenter();
|
||||
|
||||
@@ -269,4 +269,80 @@ describe("hardware source adapter", () => {
|
||||
expect(claimed).toEqual([]);
|
||||
releaseFinal();
|
||||
});
|
||||
|
||||
it("forwards native blur events and unsubscribes on detach", async () => {
|
||||
const { createHardwareKeyboardSource } = await import("./internal/sources/native");
|
||||
const blurListeners = new Set<() => void>();
|
||||
let blurCalls = 0;
|
||||
const detach = createHardwareKeyboardSource({
|
||||
subscribe: () => () => {},
|
||||
subscribeBlur(listener) {
|
||||
blurListeners.add(listener);
|
||||
return () => {
|
||||
blurListeners.delete(listener);
|
||||
};
|
||||
},
|
||||
setOverlayKeys() {},
|
||||
setClaimedShortcuts() {},
|
||||
}).attach({
|
||||
keyDown() {},
|
||||
keyUp() {},
|
||||
blur() {
|
||||
blurCalls += 1;
|
||||
},
|
||||
commandCenterOpen: () => false,
|
||||
subscribeCommandCenter: () => () => {},
|
||||
});
|
||||
for (const listener of blurListeners) listener();
|
||||
expect(blurCalls).toBe(1);
|
||||
detach();
|
||||
expect(blurListeners.size).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("shift modifier tracking", () => {
|
||||
it("tracks left/right Shift holds, self-heals on non-shifted keys, and resets on blur", async () => {
|
||||
const { createShiftModifierTracker } = await import("./internal/shift-modifier");
|
||||
const tracker = createShiftModifierTracker();
|
||||
expect(tracker.isDown()).toBe(false);
|
||||
|
||||
tracker.handleKeyDown({ key: "Shift", code: "ShiftLeft", shiftKey: true });
|
||||
expect(tracker.isDown()).toBe(true);
|
||||
|
||||
tracker.handleKeyDown({ key: "Shift", code: "ShiftRight", shiftKey: true });
|
||||
tracker.handleKeyUp({ key: "Shift", code: "ShiftLeft", shiftKey: true });
|
||||
expect(tracker.isDown()).toBe(true);
|
||||
|
||||
tracker.handleKeyUp({ key: "Shift", code: "ShiftRight", shiftKey: false });
|
||||
expect(tracker.isDown()).toBe(false);
|
||||
|
||||
// Self-heals if a Shift key-up was swallowed by the OS.
|
||||
tracker.handleKeyDown({ key: "Shift", code: "ShiftLeft", shiftKey: true });
|
||||
expect(tracker.isDown()).toBe(true);
|
||||
tracker.handleKeyDown({ key: "a", code: "KeyA", shiftKey: false });
|
||||
expect(tracker.isDown()).toBe(false);
|
||||
|
||||
// Clears on blur / backgrounding.
|
||||
tracker.handleKeyDown({ key: "Shift", code: "ShiftLeft", shiftKey: true });
|
||||
expect(tracker.isDown()).toBe(true);
|
||||
tracker.reset();
|
||||
expect(tracker.isDown()).toBe(false);
|
||||
});
|
||||
|
||||
it("exposes live hardware Shift state through isShiftKeyDown", async () => {
|
||||
const { shiftModifier } = await import("./internal/shift-modifier");
|
||||
const { isShiftKeyDown } = await import("./index");
|
||||
try {
|
||||
shiftModifier.reset();
|
||||
expect(isShiftKeyDown()).toBe(false);
|
||||
|
||||
shiftModifier.handleKeyDown({ key: "Shift", code: "ShiftLeft", shiftKey: true });
|
||||
expect(isShiftKeyDown()).toBe(true);
|
||||
|
||||
shiftModifier.handleKeyUp({ key: "Shift", code: "ShiftLeft", shiftKey: false });
|
||||
expect(isShiftKeyDown()).toBe(false);
|
||||
} finally {
|
||||
shiftModifier.reset();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { usesDesktopBindings } from "./internal/conventions";
|
||||
import { createKeyboardPipeline } from "./internal/pipeline";
|
||||
import { overlays } from "./internal/overlays";
|
||||
import { shiftModifier } from "./internal/shift-modifier";
|
||||
import { attachKeyboardSources, publishKeyboardPolicy } from "./internal/sources";
|
||||
import type { KeyboardSourceInput } from "./internal/sources/contract";
|
||||
import type { KeyboardInputEvent } from "./internal/overlays";
|
||||
@@ -249,19 +250,30 @@ export function useKeyboardShortcuts({
|
||||
[getContext, getBindings, isCapturing, dispatchMatch, beforeResolve, chordChanged],
|
||||
);
|
||||
|
||||
const handleKeyDown = useStableEvent((input: KeyboardSourceInput) => {
|
||||
shiftModifier.handleKeyDown(input.event);
|
||||
return pipeline.keyDown(input);
|
||||
});
|
||||
|
||||
const handleKeyUp = useStableEvent((event: KeyboardInputEvent) => {
|
||||
shiftModifier.handleKeyUp(event);
|
||||
const key = event.key ?? "";
|
||||
if (key === badgeModifierKey) {
|
||||
setBadgeModifierDown(false);
|
||||
}
|
||||
});
|
||||
|
||||
const handleBlur = useStableEvent(() => {
|
||||
shiftModifier.reset();
|
||||
resetModifiers();
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
const detach = attachKeyboardSources({
|
||||
keyDown: pipeline.keyDown,
|
||||
keyDown: handleKeyDown,
|
||||
keyUp: handleKeyUp,
|
||||
blur: resetModifiers,
|
||||
blur: handleBlur,
|
||||
commandCenterOpen: () => useKeyboardShortcutsStore.getState().commandCenterOpen,
|
||||
subscribeCommandCenter: (listener) =>
|
||||
useKeyboardShortcutsStore.subscribe((state, previous) => {
|
||||
@@ -270,7 +282,8 @@ export function useKeyboardShortcuts({
|
||||
});
|
||||
return () => {
|
||||
detach();
|
||||
shiftModifier.reset();
|
||||
pipeline.dispose();
|
||||
};
|
||||
}, [enabled, pipeline, handleKeyUp, resetModifiers]);
|
||||
}, [enabled, pipeline, handleKeyDown, handleKeyUp, handleBlur]);
|
||||
}
|
||||
|
||||
@@ -197,7 +197,7 @@ describe("plugin timeline projection", () => {
|
||||
kind: "assistant_message",
|
||||
id: "assistant-1",
|
||||
messageId: "provider-msg-1",
|
||||
timelineCursor: { epoch: "e1", seq: 7, anchorSeq: 7 },
|
||||
timelineCursor: { epoch: "e1", seq: 7 },
|
||||
turnId: "turn-1",
|
||||
text: 'Summary\n\n```ui\nCard("Hi", [])\n```',
|
||||
timestamp: new Date("2026-01-01T00:00:02.000Z"),
|
||||
@@ -226,13 +226,13 @@ describe("plugin timeline projection", () => {
|
||||
{
|
||||
kind: "plugin",
|
||||
id: "genui/assistant-1/text",
|
||||
timelineCursor: { epoch: "e1", seq: 7, anchorSeq: 7 },
|
||||
timelineCursor: { epoch: "e1", seq: 7 },
|
||||
turnId: "turn-1",
|
||||
},
|
||||
{
|
||||
kind: "plugin",
|
||||
id: "genui/assistant-1/card",
|
||||
timelineCursor: { epoch: "e1", seq: 7, anchorSeq: 7 },
|
||||
timelineCursor: { epoch: "e1", seq: 7 },
|
||||
turnId: "turn-1",
|
||||
},
|
||||
]);
|
||||
|
||||
@@ -91,7 +91,7 @@ describe("AgentDirectoryReplica", () => {
|
||||
id: "reply",
|
||||
text: "server history",
|
||||
timestamp: new Date(),
|
||||
timelineCursor: { epoch: "e", seq: 1, anchorSeq: 1 },
|
||||
timelineCursor: { epoch: "e", seq: 1 },
|
||||
},
|
||||
],
|
||||
head: [],
|
||||
|
||||
@@ -255,7 +255,6 @@ 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;
|
||||
|
||||
@@ -3129,19 +3128,12 @@ 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;
|
||||
// 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;
|
||||
}
|
||||
const page = await directory.fetchTimeline(agentId, request);
|
||||
if (owner && useSessionStore.getState().sessions[serverId]?.viewedTimelineSync === owner) {
|
||||
owner.flushStreamAgent(agentId);
|
||||
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`);
|
||||
}
|
||||
owner.applyTimelineResponse(page);
|
||||
}
|
||||
return page;
|
||||
}
|
||||
|
||||
createViewedTimelineOwner(
|
||||
|
||||
@@ -189,7 +189,7 @@ function timelineItem(text = "Cached"): StreamItem {
|
||||
id: "message-1",
|
||||
text,
|
||||
timestamp: new Date("2026-07-18T08:02:00.000Z"),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 12, anchorSeq: 12 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 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, anchorSeq: 12 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 12 },
|
||||
};
|
||||
writer.commitTimeline(SERVER_ID, "agent-1", {
|
||||
agentId: "agent-1",
|
||||
@@ -885,32 +885,6 @@ 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);
|
||||
@@ -1381,7 +1355,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, anchorSeq: 12 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 12 },
|
||||
payload: {
|
||||
source: "agent",
|
||||
data: {
|
||||
|
||||
@@ -22,7 +22,6 @@ import {
|
||||
isUnreconciledLocalUserMessage,
|
||||
type AgentToolCallData,
|
||||
type StreamItem,
|
||||
type TimelinePosition,
|
||||
} from "@/types/stream";
|
||||
import type { UnsettledTurn } from "@/timeline/turn-liveness";
|
||||
import { normalizeAgentSnapshot } from "@/utils/agent-snapshots";
|
||||
@@ -83,15 +82,7 @@ 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(),
|
||||
@@ -432,10 +423,6 @@ 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),
|
||||
@@ -552,20 +539,11 @@ 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,
|
||||
...anchoredPosition(item.timelineCursor),
|
||||
...(item.timelineCursor ? { timelineCursor: item.timelineCursor } : {}),
|
||||
...(item.turnId ? { turnId: item.turnId } : {}),
|
||||
timestamp: new Date(item.timestamp),
|
||||
kind: item.kind,
|
||||
@@ -584,7 +562,7 @@ function deserializeBuiltinTimelineItem(
|
||||
): StreamItem {
|
||||
const base = {
|
||||
id: item.id,
|
||||
...anchoredPosition(item.timelineCursor),
|
||||
...(item.timelineCursor ? { timelineCursor: item.timelineCursor } : {}),
|
||||
...(item.turnId ? { turnId: item.turnId } : {}),
|
||||
timestamp: new Date(item.timestamp),
|
||||
};
|
||||
|
||||
@@ -1578,9 +1578,18 @@ export function NewWorkspaceScreen({
|
||||
? t("newWorkspace.refPicker.searching")
|
||||
: t("newWorkspace.refPicker.noMatchingRefs");
|
||||
|
||||
// The prompt is where the user types; when a field's picker closes, focus returns there rather
|
||||
// than to whatever had focus when the picker opened. A terminal profile that takes no prompt
|
||||
// shows a read-only command preview, so its pickers keep returning focus to their field.
|
||||
const composerFocusRef = useRef<{ focus: () => void } | null>(null);
|
||||
const handleComposerFocusInput = useCallback((focus: () => void) => {
|
||||
composerFocusRef.current = { focus };
|
||||
}, []);
|
||||
|
||||
const formStack = useNewWorkspaceForm({
|
||||
isCompact,
|
||||
isPending,
|
||||
restoreFocusRef: terminalTakesPrompt ? composerFocusRef : undefined,
|
||||
pluginItems: (
|
||||
<PluginNewWorkspaceItems serverId={selectedServerId} screen={pluginScreen} setup={setup} />
|
||||
),
|
||||
@@ -1682,6 +1691,7 @@ export function NewWorkspaceScreen({
|
||||
clearDraft={noopClearDraft}
|
||||
autoFocus={terminalTakesPrompt}
|
||||
autoFocusKey={launchFocusKey}
|
||||
onFocusInput={handleComposerFocusInput}
|
||||
error={errorMessage}
|
||||
/>
|
||||
) : (
|
||||
@@ -1712,6 +1722,7 @@ export function NewWorkspaceScreen({
|
||||
clearDraft={handleClearDraft}
|
||||
autoFocus
|
||||
autoFocusKey={launchFocusKey}
|
||||
onFocusInput={handleComposerFocusInput}
|
||||
commandDraft={composerState?.commandDraft}
|
||||
agentControls={agentControlsWithDisabled}
|
||||
error={errorMessage}
|
||||
|
||||
@@ -67,6 +67,11 @@ export interface NewWorkspaceFormProps {
|
||||
isPending: boolean;
|
||||
/** Plugin fields, drawn after the base ref. */
|
||||
pluginItems: ReactNode;
|
||||
/**
|
||||
* Where focus goes when a field's picker closes, so the user keeps typing the prompt. Without
|
||||
* one, focus returns to the field that opened the picker.
|
||||
*/
|
||||
restoreFocusRef?: RefObject<unknown>;
|
||||
project: PickerControl & {
|
||||
options: ComboboxOption[];
|
||||
projectByOptionId: Map<string, HostProjectListItem>;
|
||||
@@ -373,7 +378,17 @@ function useRefPicker(base: NewWorkspaceFormProps["base"], isPending: boolean) {
|
||||
*/
|
||||
export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const { isCompact, isPending, pluginItems, project, host, isolation, base, launch } = props;
|
||||
const {
|
||||
isCompact,
|
||||
isPending,
|
||||
pluginItems,
|
||||
restoreFocusRef,
|
||||
project,
|
||||
host,
|
||||
isolation,
|
||||
base,
|
||||
launch,
|
||||
} = props;
|
||||
const variant: FieldTriggerVariant = isCompact ? "field" : "badge";
|
||||
const projectPicker = useProjectPicker(project, isPending);
|
||||
const isolationPicker = useIsolationPicker({
|
||||
@@ -432,6 +447,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
|
||||
open={host.openState}
|
||||
onOpenChange={host.onOpenChange}
|
||||
anchorRef={host.anchorRef}
|
||||
restoreFocusRef={restoreFocusRef}
|
||||
includeAddHost
|
||||
onAddHost={host.onAddHost}
|
||||
addHostTestID="new-workspace-host-picker-add-host"
|
||||
@@ -525,6 +541,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
|
||||
desktopPlacement="bottom-start"
|
||||
desktopMinWidth={360}
|
||||
anchorRef={project.anchorRef}
|
||||
restoreFocusRef={restoreFocusRef}
|
||||
emptyText="No projects available."
|
||||
renderOption={projectPicker.renderOption}
|
||||
footer={projectPicker.footer}
|
||||
@@ -539,6 +556,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
|
||||
searchable={false}
|
||||
desktopPlacement="bottom-start"
|
||||
anchorRef={isolation.anchorRef}
|
||||
restoreFocusRef={restoreFocusRef}
|
||||
desktopMinWidth={280}
|
||||
renderOption={isolationPicker.renderOption}
|
||||
/>
|
||||
@@ -555,6 +573,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
|
||||
desktopPlacement="bottom-start"
|
||||
desktopMinWidth={440}
|
||||
anchorRef={base.anchorRef}
|
||||
restoreFocusRef={restoreFocusRef}
|
||||
emptyText={base.emptyText}
|
||||
toolbar={refPicker.toolbar}
|
||||
renderOption={refPicker.renderOption}
|
||||
@@ -571,6 +590,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
|
||||
desktopPlacement="bottom-start"
|
||||
desktopMinWidth={360}
|
||||
anchorRef={worktreePicker.anchorRef}
|
||||
restoreFocusRef={restoreFocusRef}
|
||||
emptyText={t("newWorkspace.worktreePicker.empty")}
|
||||
renderOption={worktreePicker.renderOption}
|
||||
/>
|
||||
|
||||
@@ -2188,10 +2188,11 @@ function WorkspaceScreenContent({
|
||||
|
||||
toast.show(t("workspace.tabs.toasts.reloadingAgent"), { durationMs: null });
|
||||
try {
|
||||
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.
|
||||
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 sessionState = useSessionStore.getState().sessions[normalizedServerId];
|
||||
const currentCursor = sessionState?.agentTimelineCursor.get(agentId);
|
||||
await getHostRuntimeStore().fetchAgentTimeline(normalizedServerId, agentId, {
|
||||
@@ -2200,13 +2201,7 @@ function WorkspaceScreenContent({
|
||||
? { cursor: { epoch: currentCursor.epoch, seq: currentCursor.endSeq } }
|
||||
: {}),
|
||||
});
|
||||
if (refreshed.historyDiverged) {
|
||||
toast.show(t("workspace.tabs.toasts.reloadedAgentHistoryDiverged"), {
|
||||
variant: "warning",
|
||||
});
|
||||
} else {
|
||||
toast.show(t("workspace.tabs.toasts.reloadedAgent"), { variant: "success" });
|
||||
}
|
||||
toast.show(t("workspace.tabs.toasts.reloadedAgent"), { variant: "success" });
|
||||
} catch (error) {
|
||||
toast.error(
|
||||
error instanceof Error ? error.message : t("workspace.tabs.toasts.failedToReloadAgent"),
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
export { isShiftPressEvent } from "./internal/selection-state";
|
||||
export {
|
||||
registerSidebarVisibleWorkspaceKeysReader,
|
||||
useIsSidebarSelectionMode,
|
||||
useIsWorkspaceBulkSelected,
|
||||
useSidebarSelectionStore,
|
||||
} from "./internal/selection-store";
|
||||
export { SidebarSelectionHost } from "./internal/sidebar-selection-host";
|
||||
@@ -0,0 +1,280 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { ToastApi } from "@/components/toast-host";
|
||||
import type { SidebarWorkspaceEntry } from "@/hooks/use-sidebar-workspaces-list";
|
||||
import {
|
||||
archiveSelectedWorkspaces,
|
||||
type BulkArchiveClient,
|
||||
type BulkArchiveWorkspacesDeps,
|
||||
} from "./archive-selected";
|
||||
|
||||
function makeEntry(
|
||||
overrides: Partial<SidebarWorkspaceEntry> & { workspaceId: string },
|
||||
): SidebarWorkspaceEntry {
|
||||
return {
|
||||
workspaceKey: `srv:${overrides.workspaceId}`,
|
||||
serverId: "srv",
|
||||
projectViewKey: "prj-view",
|
||||
projectName: "Repo",
|
||||
projectRootPath: "/repo",
|
||||
workspaceDirectory: `/repo/${overrides.workspaceId}`,
|
||||
workspaceDirectoryLabel: overrides.workspaceId,
|
||||
projectKind: "git",
|
||||
workspaceKind: "local_checkout",
|
||||
name: overrides.workspaceId,
|
||||
title: null,
|
||||
currentBranch: overrides.workspaceId,
|
||||
statusBucket: "done",
|
||||
statusEnteredAt: null,
|
||||
archivingAt: null,
|
||||
diffStat: null,
|
||||
prHint: null,
|
||||
pinnedAt: null,
|
||||
background: false,
|
||||
labels: [],
|
||||
scripts: [],
|
||||
hasRunningScripts: false,
|
||||
archiveHasUncommittedChanges: null,
|
||||
archiveUnpushedCommitCount: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function createFakeToast(): { toast: ToastApi; errors: string[] } {
|
||||
const errors: string[] = [];
|
||||
return {
|
||||
errors,
|
||||
toast: {
|
||||
show: () => () => {},
|
||||
copied: () => {},
|
||||
error: (message) => errors.push(message),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function createFakeClient(): BulkArchiveClient {
|
||||
return {
|
||||
archiveWorkspace: async () => ({ error: null }),
|
||||
undoWorkspaceArchive: async () => {},
|
||||
getCheckoutStatus: async () =>
|
||||
({
|
||||
isGit: true,
|
||||
isDirty: false,
|
||||
aheadOfOrigin: 0,
|
||||
}) as Awaited<ReturnType<BulkArchiveClient["getCheckoutStatus"]>>,
|
||||
};
|
||||
}
|
||||
|
||||
describe("archiveSelectedWorkspaces", () => {
|
||||
it("archives multiple workspaces with one undo batch and redirects active workspace first", async () => {
|
||||
const order: string[] = [];
|
||||
const client = createFakeClient();
|
||||
const { toast, errors } = createFakeToast();
|
||||
const confirmRiskyBulkArchive = vi.fn(async () => true);
|
||||
const deps: BulkArchiveWorkspacesDeps = {
|
||||
getClient: () => client,
|
||||
supportsUndo: () => true,
|
||||
readWorktreeRisk: async () => ({ isDirty: false, aheadOfOrigin: 0 }),
|
||||
confirmRiskyBulkArchive,
|
||||
archiveWithUndo: async (input) => {
|
||||
order.push(
|
||||
`archive:${input.entries.map((entry) => entry.workspace.workspaceId).join(",")}`,
|
||||
);
|
||||
return { failures: [], showPartialFailure: () => false };
|
||||
},
|
||||
archiveWithoutUndo: async () => "archived",
|
||||
hasActiveUndo: () => false,
|
||||
purgeWorkspaceState: vi.fn(),
|
||||
redirectActiveWorkspace: (workspace) => {
|
||||
order.push(`redirect:${workspace.workspaceId}`);
|
||||
},
|
||||
};
|
||||
|
||||
const ok = await archiveSelectedWorkspaces({
|
||||
workspaces: [makeEntry({ workspaceId: "w1" }), makeEntry({ workspaceId: "w2" })],
|
||||
toast,
|
||||
onArchiveStarted: () => order.push("exit-selection"),
|
||||
deps,
|
||||
});
|
||||
|
||||
expect(ok).toBe(true);
|
||||
expect(errors).toEqual([]);
|
||||
expect(order).toEqual(["redirect:w1", "redirect:w2", "exit-selection", "archive:w1,w2"]);
|
||||
expect(confirmRiskyBulkArchive).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps select mode open when the user cancels a risky worktree confirmation", async () => {
|
||||
const client = createFakeClient();
|
||||
const { toast, errors } = createFakeToast();
|
||||
const onArchiveStarted = vi.fn();
|
||||
const archiveWithUndo = vi.fn(async () => ({
|
||||
failures: [],
|
||||
showPartialFailure: () => false,
|
||||
}));
|
||||
const confirmRiskyBulkArchive = vi.fn(async () => false);
|
||||
|
||||
const ok = await archiveSelectedWorkspaces({
|
||||
workspaces: [
|
||||
makeEntry({ workspaceId: "w1", workspaceKind: "worktree", name: "feat-wip" }),
|
||||
makeEntry({ workspaceId: "w2", workspaceKind: "local_checkout", name: "main" }),
|
||||
],
|
||||
toast,
|
||||
onArchiveStarted,
|
||||
deps: {
|
||||
getClient: () => client,
|
||||
supportsUndo: () => true,
|
||||
readWorktreeRisk: async () => ({ isDirty: true, aheadOfOrigin: 1 }),
|
||||
confirmRiskyBulkArchive,
|
||||
archiveWithUndo,
|
||||
archiveWithoutUndo: async () => "archived",
|
||||
hasActiveUndo: () => false,
|
||||
purgeWorkspaceState: vi.fn(),
|
||||
redirectActiveWorkspace: vi.fn(),
|
||||
},
|
||||
});
|
||||
|
||||
expect(ok).toBe(false);
|
||||
expect(errors).toEqual([]);
|
||||
expect(confirmRiskyBulkArchive).toHaveBeenCalledWith({
|
||||
totalCount: 2,
|
||||
riskyWorkspaces: [
|
||||
{
|
||||
workspaceName: "feat-wip",
|
||||
diffStat: null,
|
||||
isDirty: true,
|
||||
aheadOfOrigin: 1,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(onArchiveStarted).not.toHaveBeenCalled();
|
||||
expect(archiveWithUndo).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("shows a disconnect error and aborts before archiving when any host is offline", async () => {
|
||||
const { toast, errors } = createFakeToast();
|
||||
const onArchiveStarted = vi.fn();
|
||||
|
||||
const ok = await archiveSelectedWorkspaces({
|
||||
workspaces: [makeEntry({ workspaceId: "w1" })],
|
||||
toast,
|
||||
onArchiveStarted,
|
||||
deps: {
|
||||
getClient: () => null,
|
||||
supportsUndo: () => true,
|
||||
readWorktreeRisk: vi.fn(),
|
||||
confirmRiskyBulkArchive: vi.fn(),
|
||||
archiveWithUndo: vi.fn(),
|
||||
archiveWithoutUndo: vi.fn(),
|
||||
hasActiveUndo: () => false,
|
||||
purgeWorkspaceState: vi.fn(),
|
||||
redirectActiveWorkspace: vi.fn(),
|
||||
},
|
||||
});
|
||||
|
||||
expect(ok).toBe(false);
|
||||
expect(errors).toEqual(["Host is not connected"]);
|
||||
expect(onArchiveStarted).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reports multi-workspace failures when more than one archive fails", async () => {
|
||||
const client = createFakeClient();
|
||||
const { toast, errors } = createFakeToast();
|
||||
|
||||
const ok = await archiveSelectedWorkspaces({
|
||||
workspaces: [makeEntry({ workspaceId: "w1" }), makeEntry({ workspaceId: "w2" })],
|
||||
toast,
|
||||
onArchiveStarted: vi.fn(),
|
||||
deps: {
|
||||
getClient: () => client,
|
||||
supportsUndo: () => true,
|
||||
readWorktreeRisk: vi.fn(),
|
||||
confirmRiskyBulkArchive: vi.fn(),
|
||||
archiveWithUndo: async () => ({
|
||||
failures: [
|
||||
{ workspace: { serverId: "srv", workspaceId: "w1" }, error: new Error("boom 1") },
|
||||
{ workspace: { serverId: "srv", workspaceId: "w2" }, error: new Error("boom 2") },
|
||||
],
|
||||
showPartialFailure: () => false,
|
||||
}),
|
||||
archiveWithoutUndo: vi.fn(),
|
||||
hasActiveUndo: () => false,
|
||||
purgeWorkspaceState: vi.fn(),
|
||||
redirectActiveWorkspace: vi.fn(),
|
||||
},
|
||||
});
|
||||
|
||||
expect(ok).toBe(false);
|
||||
expect(errors).toEqual(["Failed to archive 2 workspaces"]);
|
||||
});
|
||||
|
||||
it("keeps Undo open via showPartialFailure instead of replacing it with toast.error on partial failure", async () => {
|
||||
const client = createFakeClient();
|
||||
const { toast, errors } = createFakeToast();
|
||||
const partialErrors: string[] = [];
|
||||
|
||||
const ok = await archiveSelectedWorkspaces({
|
||||
workspaces: [makeEntry({ workspaceId: "w1" }), makeEntry({ workspaceId: "w2" })],
|
||||
toast,
|
||||
onArchiveStarted: vi.fn(),
|
||||
deps: {
|
||||
getClient: () => client,
|
||||
supportsUndo: () => true,
|
||||
readWorktreeRisk: vi.fn(),
|
||||
confirmRiskyBulkArchive: vi.fn(),
|
||||
archiveWithUndo: async () => ({
|
||||
failures: [
|
||||
{ workspace: { serverId: "srv", workspaceId: "w2" }, error: new Error("Host offline") },
|
||||
],
|
||||
showPartialFailure: (message) => {
|
||||
partialErrors.push(message);
|
||||
return true;
|
||||
},
|
||||
}),
|
||||
archiveWithoutUndo: vi.fn(),
|
||||
hasActiveUndo: () => false,
|
||||
purgeWorkspaceState: vi.fn(),
|
||||
redirectActiveWorkspace: vi.fn(),
|
||||
},
|
||||
});
|
||||
|
||||
expect(ok).toBe(false);
|
||||
expect(partialErrors).toEqual(["Host offline"]);
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
|
||||
it("routes a late failure from a superseded batch to fallbackErrorToast so a newer batch keeps its Undo", async () => {
|
||||
const client = createFakeClient();
|
||||
const sidebar = createFakeToast();
|
||||
const app = createFakeToast();
|
||||
|
||||
const ok = await archiveSelectedWorkspaces({
|
||||
workspaces: [makeEntry({ workspaceId: "w1" })],
|
||||
toast: sidebar.toast,
|
||||
fallbackErrorToast: app.toast,
|
||||
onArchiveStarted: vi.fn(),
|
||||
deps: {
|
||||
getClient: () => client,
|
||||
supportsUndo: () => true,
|
||||
readWorktreeRisk: vi.fn(),
|
||||
confirmRiskyBulkArchive: vi.fn(),
|
||||
archiveWithUndo: async () => ({
|
||||
failures: [
|
||||
{
|
||||
workspace: { serverId: "srv", workspaceId: "w1" },
|
||||
error: new Error("Host timed out"),
|
||||
},
|
||||
],
|
||||
// This batch's own undo window was closed when a newer batch superseded it.
|
||||
showPartialFailure: () => false,
|
||||
}),
|
||||
archiveWithoutUndo: vi.fn(),
|
||||
hasActiveUndo: () => true,
|
||||
purgeWorkspaceState: vi.fn(),
|
||||
redirectActiveWorkspace: vi.fn(),
|
||||
},
|
||||
});
|
||||
|
||||
expect(ok).toBe(false);
|
||||
expect(sidebar.errors).toEqual([]);
|
||||
expect(app.errors).toEqual(["Host timed out"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,197 @@
|
||||
import type { ToastApi } from "@/components/toast-host";
|
||||
import type { CheckoutStatusClient } from "@/git/checkout-status-cache";
|
||||
import {
|
||||
confirmRiskyBulkWorktreeArchive,
|
||||
readWorktreeArchiveRisk,
|
||||
type WorktreeArchiveConfirmationInput,
|
||||
} from "@/git/worktree-archive-warning";
|
||||
import type { SidebarWorkspaceEntry } from "@/hooks/use-sidebar-workspaces-list";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
||||
import type { ActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store";
|
||||
import { useWorkspaceLayoutStore } from "@/stores/workspace-layout-store";
|
||||
import { redirectIfArchivingActiveWorkspace } from "@/utils/sidebar-workspace-archive-redirect";
|
||||
import { buildWorkspaceTabPersistenceKey } from "@/workspace-tabs/model";
|
||||
import {
|
||||
archiveWorkspacesWithUndo,
|
||||
hasUndoableWorkspaceArchive,
|
||||
supportsWorkspaceArchiveUndo,
|
||||
type UndoableWorkspaceArchiveClient,
|
||||
} from "@/workspace/archive-undo";
|
||||
import {
|
||||
archiveWorkspaceOptimistically,
|
||||
type WorkspaceArchiveTarget,
|
||||
} from "@/workspace/workspace-archive";
|
||||
|
||||
export interface BulkArchiveClient extends UndoableWorkspaceArchiveClient, CheckoutStatusClient {}
|
||||
|
||||
export interface BulkArchiveWorkspacesDeps {
|
||||
getClient: (serverId: string) => BulkArchiveClient | null;
|
||||
supportsUndo: (serverId: string) => boolean;
|
||||
readWorktreeRisk: typeof readWorktreeArchiveRisk;
|
||||
confirmRiskyBulkArchive: typeof confirmRiskyBulkWorktreeArchive;
|
||||
archiveWithUndo: typeof archiveWorkspacesWithUndo;
|
||||
archiveWithoutUndo: typeof archiveWorkspaceOptimistically;
|
||||
hasActiveUndo: () => boolean;
|
||||
purgeWorkspaceState: (workspace: WorkspaceArchiveTarget) => void;
|
||||
redirectActiveWorkspace: (workspace: WorkspaceArchiveTarget) => void;
|
||||
}
|
||||
|
||||
function defaultPurgeWorkspaceState(workspace: WorkspaceArchiveTarget): void {
|
||||
const workspaceKey = buildWorkspaceTabPersistenceKey(workspace);
|
||||
if (workspaceKey) {
|
||||
useWorkspaceLayoutStore.getState().purgeWorkspace(workspaceKey);
|
||||
}
|
||||
}
|
||||
|
||||
export function createDefaultBulkArchiveDeps(
|
||||
getActiveWorkspaceSelection: () => ActiveWorkspaceSelection | null,
|
||||
): BulkArchiveWorkspacesDeps {
|
||||
return {
|
||||
getClient: (serverId) => getHostRuntimeStore().getClient(serverId),
|
||||
supportsUndo: supportsWorkspaceArchiveUndo,
|
||||
readWorktreeRisk: readWorktreeArchiveRisk,
|
||||
confirmRiskyBulkArchive: confirmRiskyBulkWorktreeArchive,
|
||||
archiveWithUndo: archiveWorkspacesWithUndo,
|
||||
archiveWithoutUndo: archiveWorkspaceOptimistically,
|
||||
hasActiveUndo: hasUndoableWorkspaceArchive,
|
||||
purgeWorkspaceState: defaultPurgeWorkspaceState,
|
||||
redirectActiveWorkspace: (workspace) => {
|
||||
redirectIfArchivingActiveWorkspace({
|
||||
serverId: workspace.serverId,
|
||||
workspaceId: workspace.workspaceId,
|
||||
activeWorkspaceSelection: getActiveWorkspaceSelection(),
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function formatArchiveFailureMessage(failures: ReadonlyArray<{ error: unknown }>): string {
|
||||
if (failures.length > 1) {
|
||||
return i18n.t("sidebar.workspace.toasts.archiveMultipleFailed", { count: failures.length });
|
||||
}
|
||||
const error = failures[0]?.error;
|
||||
return error instanceof Error ? error.message : i18n.t("sidebar.workspace.toasts.archiveFailed");
|
||||
}
|
||||
|
||||
interface ResolvedWorkspaceTarget {
|
||||
entry: SidebarWorkspaceEntry;
|
||||
client: BulkArchiveClient;
|
||||
}
|
||||
|
||||
export async function archiveSelectedWorkspaces(input: {
|
||||
workspaces: readonly SidebarWorkspaceEntry[];
|
||||
toast: ToastApi;
|
||||
fallbackErrorToast?: ToastApi;
|
||||
onArchiveStarted: () => void;
|
||||
deps: BulkArchiveWorkspacesDeps;
|
||||
}): Promise<boolean> {
|
||||
const { workspaces, toast, fallbackErrorToast, onArchiveStarted, deps } = input;
|
||||
if (workspaces.length === 0) return false;
|
||||
|
||||
const resolved: ResolvedWorkspaceTarget[] = [];
|
||||
for (const entry of workspaces) {
|
||||
const client = deps.getClient(entry.serverId);
|
||||
if (!client) {
|
||||
toast.error(i18n.t("sidebar.workspace.toasts.hostDisconnected"));
|
||||
return false;
|
||||
}
|
||||
resolved.push({ entry, client });
|
||||
}
|
||||
|
||||
const riskyWorkspaces: WorktreeArchiveConfirmationInput[] = [];
|
||||
const worktrees = resolved.filter((item) => item.entry.workspaceKind === "worktree");
|
||||
if (worktrees.length > 0) {
|
||||
try {
|
||||
const risks = await Promise.all(
|
||||
worktrees.map(async ({ entry, client }) => {
|
||||
const risk = await deps.readWorktreeRisk(client, entry.workspaceDirectory);
|
||||
return {
|
||||
workspaceName: entry.name,
|
||||
diffStat: entry.diffStat,
|
||||
isDirty: risk.isDirty,
|
||||
aheadOfOrigin: risk.aheadOfOrigin,
|
||||
} satisfies WorktreeArchiveConfirmationInput;
|
||||
}),
|
||||
);
|
||||
riskyWorkspaces.push(...risks);
|
||||
} catch (error) {
|
||||
toast.error(
|
||||
error instanceof Error ? error.message : i18n.t("sidebar.workspace.toasts.archiveFailed"),
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (riskyWorkspaces.length > 0) {
|
||||
const confirmed = await deps.confirmRiskyBulkArchive({
|
||||
totalCount: resolved.length,
|
||||
riskyWorkspaces,
|
||||
});
|
||||
if (!confirmed) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Redirect before optimistic removal hides the active workspace from the session store.
|
||||
for (const { entry } of resolved) {
|
||||
deps.redirectActiveWorkspace({ serverId: entry.serverId, workspaceId: entry.workspaceId });
|
||||
}
|
||||
|
||||
onArchiveStarted();
|
||||
|
||||
const undoable: ResolvedWorkspaceTarget[] = [];
|
||||
const legacy: ResolvedWorkspaceTarget[] = [];
|
||||
for (const item of resolved) {
|
||||
if (deps.supportsUndo(item.entry.serverId)) {
|
||||
undoable.push(item);
|
||||
} else {
|
||||
legacy.push(item);
|
||||
}
|
||||
}
|
||||
|
||||
const failures: Array<{ error: unknown }> = [];
|
||||
let showPartialFailure: (message: string) => boolean = () => false;
|
||||
|
||||
await Promise.all([
|
||||
undoable.length > 0
|
||||
? (async () => {
|
||||
const result = await deps.archiveWithUndo({
|
||||
entries: undoable.map(({ entry, client }) => {
|
||||
const workspace = { serverId: entry.serverId, workspaceId: entry.workspaceId };
|
||||
return {
|
||||
client,
|
||||
workspace,
|
||||
onArchiveCommitted: () => deps.purgeWorkspaceState(workspace),
|
||||
};
|
||||
}),
|
||||
toast,
|
||||
});
|
||||
failures.push(...result.failures);
|
||||
showPartialFailure = result.showPartialFailure;
|
||||
})()
|
||||
: Promise.resolve(),
|
||||
// COMPAT(workspaceArchiveUndo): hosts before v0.15.3 cannot undo; remove after 2027-05-06.
|
||||
...legacy.map(async ({ entry, client }) => {
|
||||
const workspace = { serverId: entry.serverId, workspaceId: entry.workspaceId };
|
||||
try {
|
||||
await deps.archiveWithoutUndo({ client, workspace });
|
||||
deps.purgeWorkspaceState(workspace);
|
||||
} catch (error) {
|
||||
failures.push({ error });
|
||||
}
|
||||
}),
|
||||
]);
|
||||
|
||||
if (failures.length > 0) {
|
||||
const errorMessage = formatArchiveFailureMessage(failures);
|
||||
if (!showPartialFailure(errorMessage)) {
|
||||
// If a newer batch now owns the sidebar Undo toast, surface this older failure on the
|
||||
// app-level toast instead of displacing the active Undo window and purging its layouts.
|
||||
const errorToast = deps.hasActiveUndo() ? (fallbackErrorToast ?? toast) : toast;
|
||||
errorToast.error(errorMessage);
|
||||
}
|
||||
}
|
||||
|
||||
return failures.length === 0;
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
enterWorkspaceSelection,
|
||||
exitWorkspaceSelection,
|
||||
INITIAL_WORKSPACE_SELECTION_STATE,
|
||||
isShiftPressEvent,
|
||||
reconcileWorkspaceSelection,
|
||||
selectWorkspaceRange,
|
||||
toggleWorkspaceSelection,
|
||||
} from "./selection-state";
|
||||
|
||||
describe("sidebar workspace selection state", () => {
|
||||
it("enters selection with the clicked workspace as anchor", () => {
|
||||
const state = enterWorkspaceSelection("ws-2");
|
||||
expect({
|
||||
active: state.active,
|
||||
selected: [...state.selectedKeys],
|
||||
anchorKey: state.anchorKey,
|
||||
}).toEqual({
|
||||
active: true,
|
||||
selected: ["ws-2"],
|
||||
anchorKey: "ws-2",
|
||||
});
|
||||
});
|
||||
|
||||
it("toggles workspaces on plain click without needing Shift", () => {
|
||||
let state = enterWorkspaceSelection("ws-1");
|
||||
state = toggleWorkspaceSelection(state, "ws-3");
|
||||
expect([...state.selectedKeys]).toEqual(["ws-1", "ws-3"]);
|
||||
expect(state.anchorKey).toBe("ws-3");
|
||||
|
||||
state = toggleWorkspaceSelection(state, "ws-1");
|
||||
expect([...state.selectedKeys]).toEqual(["ws-3"]);
|
||||
expect(state.anchorKey).toBe("ws-1");
|
||||
|
||||
state = toggleWorkspaceSelection(state, "ws-3");
|
||||
expect(state.active).toBe(true);
|
||||
expect([...state.selectedKeys]).toEqual([]);
|
||||
});
|
||||
|
||||
it("selects an inclusive range on Shift+click in either direction while keeping prior picks", () => {
|
||||
const visible = ["ws-1", "ws-2", "ws-3", "ws-4", "ws-5"];
|
||||
let state = enterWorkspaceSelection("ws-1");
|
||||
state = toggleWorkspaceSelection(state, "ws-3");
|
||||
|
||||
state = selectWorkspaceRange(state, "ws-5", visible);
|
||||
expect([...state.selectedKeys]).toEqual(["ws-1", "ws-3", "ws-4", "ws-5"]);
|
||||
expect(state.anchorKey).toBe("ws-3");
|
||||
|
||||
const backward = selectWorkspaceRange(enterWorkspaceSelection("ws-4"), "ws-2", visible);
|
||||
expect([...backward.selectedKeys].sort()).toEqual(["ws-2", "ws-3", "ws-4"]);
|
||||
});
|
||||
|
||||
it("falls back to adding the target when the anchor is no longer in the visible list", () => {
|
||||
const state = selectWorkspaceRange(enterWorkspaceSelection("ws-hidden"), "ws-2", [
|
||||
"ws-1",
|
||||
"ws-2",
|
||||
]);
|
||||
expect([...state.selectedKeys]).toEqual(["ws-hidden", "ws-2"]);
|
||||
expect(state.anchorKey).toBe("ws-2");
|
||||
});
|
||||
|
||||
it("reconciles removed workspaces and clears a missing anchor", () => {
|
||||
let state = enterWorkspaceSelection("ws-1");
|
||||
state = toggleWorkspaceSelection(state, "ws-2");
|
||||
const reconciled = reconcileWorkspaceSelection(state, new Set(["ws-1"]));
|
||||
expect({
|
||||
active: reconciled.active,
|
||||
selected: [...reconciled.selectedKeys],
|
||||
anchorKey: reconciled.anchorKey,
|
||||
}).toEqual({
|
||||
active: true,
|
||||
selected: ["ws-1"],
|
||||
anchorKey: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("resets completely on exit", () => {
|
||||
expect(exitWorkspaceSelection()).toBe(INITIAL_WORKSPACE_SELECTION_STATE);
|
||||
});
|
||||
|
||||
it("detects Shift on direct, nativeEvent, or hardware modifier payloads", () => {
|
||||
expect(isShiftPressEvent({ shiftKey: true })).toBe(true);
|
||||
expect(isShiftPressEvent({ nativeEvent: { shiftKey: true } })).toBe(true);
|
||||
expect(isShiftPressEvent({ shiftKey: false, nativeEvent: { shiftKey: false } })).toBe(false);
|
||||
expect(isShiftPressEvent(null)).toBe(false);
|
||||
|
||||
// Native GestureResponderEvent omits shiftKey; falls back to hardware Shift state.
|
||||
const nativeResponderEvent = { nativeEvent: { locationX: 12, locationY: 8 } };
|
||||
expect(isShiftPressEvent(nativeResponderEvent, () => false)).toBe(false);
|
||||
expect(isShiftPressEvent(nativeResponderEvent, () => true)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,129 @@
|
||||
import { isShiftKeyDown } from "@/keyboard";
|
||||
|
||||
export interface WorkspaceSelectionState {
|
||||
active: boolean;
|
||||
selectedKeys: ReadonlySet<string>;
|
||||
anchorKey: string | null;
|
||||
}
|
||||
|
||||
const EMPTY_KEYS: ReadonlySet<string> = new Set();
|
||||
|
||||
export const INITIAL_WORKSPACE_SELECTION_STATE: WorkspaceSelectionState = {
|
||||
active: false,
|
||||
selectedKeys: EMPTY_KEYS,
|
||||
anchorKey: null,
|
||||
};
|
||||
|
||||
export function enterWorkspaceSelection(workspaceKey: string): WorkspaceSelectionState {
|
||||
return {
|
||||
active: true,
|
||||
selectedKeys: new Set([workspaceKey]),
|
||||
anchorKey: workspaceKey,
|
||||
};
|
||||
}
|
||||
|
||||
export function toggleWorkspaceSelection(
|
||||
state: WorkspaceSelectionState,
|
||||
workspaceKey: string,
|
||||
): WorkspaceSelectionState {
|
||||
if (!state.active) {
|
||||
return enterWorkspaceSelection(workspaceKey);
|
||||
}
|
||||
const next = new Set(state.selectedKeys);
|
||||
if (!next.delete(workspaceKey)) {
|
||||
next.add(workspaceKey);
|
||||
}
|
||||
return {
|
||||
active: true,
|
||||
selectedKeys: next,
|
||||
anchorKey: workspaceKey,
|
||||
};
|
||||
}
|
||||
|
||||
export function selectWorkspaceRange(
|
||||
state: WorkspaceSelectionState,
|
||||
targetKey: string,
|
||||
orderedVisibleKeys: readonly string[],
|
||||
): WorkspaceSelectionState {
|
||||
if (!state.active) {
|
||||
return enterWorkspaceSelection(targetKey);
|
||||
}
|
||||
if (!state.anchorKey) {
|
||||
const next = new Set(state.selectedKeys);
|
||||
next.add(targetKey);
|
||||
return { active: true, selectedKeys: next, anchorKey: targetKey };
|
||||
}
|
||||
|
||||
const anchorIndex = orderedVisibleKeys.indexOf(state.anchorKey);
|
||||
const targetIndex = orderedVisibleKeys.indexOf(targetKey);
|
||||
if (anchorIndex < 0 || targetIndex < 0) {
|
||||
const next = new Set(state.selectedKeys);
|
||||
next.add(targetKey);
|
||||
return { active: true, selectedKeys: next, anchorKey: targetKey };
|
||||
}
|
||||
|
||||
const start = Math.min(anchorIndex, targetIndex);
|
||||
const end = Math.max(anchorIndex, targetIndex);
|
||||
const next = new Set(state.selectedKeys);
|
||||
for (let index = start; index <= end; index += 1) {
|
||||
const key = orderedVisibleKeys[index];
|
||||
if (key !== undefined) {
|
||||
next.add(key);
|
||||
}
|
||||
}
|
||||
return {
|
||||
active: true,
|
||||
selectedKeys: next,
|
||||
anchorKey: state.anchorKey,
|
||||
};
|
||||
}
|
||||
|
||||
export function reconcileWorkspaceSelection(
|
||||
state: WorkspaceSelectionState,
|
||||
availableKeys: ReadonlySet<string>,
|
||||
): WorkspaceSelectionState {
|
||||
if (!state.active) return state;
|
||||
|
||||
let changed = false;
|
||||
const next = new Set<string>();
|
||||
for (const key of state.selectedKeys) {
|
||||
if (availableKeys.has(key)) {
|
||||
next.add(key);
|
||||
} else {
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
const nextAnchor = state.anchorKey && availableKeys.has(state.anchorKey) ? state.anchorKey : null;
|
||||
if (!changed && nextAnchor === state.anchorKey) {
|
||||
return state;
|
||||
}
|
||||
|
||||
return {
|
||||
active: true,
|
||||
selectedKeys: changed ? next : state.selectedKeys,
|
||||
anchorKey: nextAnchor,
|
||||
};
|
||||
}
|
||||
|
||||
export function exitWorkspaceSelection(): WorkspaceSelectionState {
|
||||
return INITIAL_WORKSPACE_SELECTION_STATE;
|
||||
}
|
||||
|
||||
export function isShiftPressEvent(
|
||||
event: unknown,
|
||||
isHardwareShiftDown: () => boolean = isShiftKeyDown,
|
||||
): boolean {
|
||||
if (typeof event === "object" && event !== null) {
|
||||
if (Reflect.get(event, "shiftKey") === true) return true;
|
||||
const nativeEvent = Reflect.get(event, "nativeEvent");
|
||||
if (
|
||||
typeof nativeEvent === "object" &&
|
||||
nativeEvent !== null &&
|
||||
Reflect.get(nativeEvent, "shiftKey") === true
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return isHardwareShiftDown();
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import { create } from "zustand";
|
||||
import {
|
||||
enterWorkspaceSelection,
|
||||
exitWorkspaceSelection,
|
||||
INITIAL_WORKSPACE_SELECTION_STATE,
|
||||
reconcileWorkspaceSelection,
|
||||
selectWorkspaceRange,
|
||||
toggleWorkspaceSelection,
|
||||
type WorkspaceSelectionState,
|
||||
} from "./selection-state";
|
||||
|
||||
type VisibleKeysReader = () => readonly string[];
|
||||
|
||||
let visibleKeysReader: VisibleKeysReader = () => [];
|
||||
|
||||
/**
|
||||
* Registers a synchronous reader for the currently rendered sidebar workspace order so Shift+click
|
||||
* range selection walks only rows on screen without causing re-renders when the order changes.
|
||||
*/
|
||||
export function registerSidebarVisibleWorkspaceKeysReader(reader: VisibleKeysReader): () => void {
|
||||
visibleKeysReader = reader;
|
||||
return () => {
|
||||
if (visibleKeysReader === reader) {
|
||||
visibleKeysReader = () => [];
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
interface SidebarSelectionStoreState extends WorkspaceSelectionState {
|
||||
isArchiving: boolean;
|
||||
enter: (workspaceKey: string) => void;
|
||||
pressWorkspace: (workspaceKey: string, options: { shiftKey: boolean }) => void;
|
||||
reconcile: (availableKeys: ReadonlySet<string>) => void;
|
||||
setArchiving: (archiving: boolean) => void;
|
||||
exit: () => void;
|
||||
}
|
||||
|
||||
export const useSidebarSelectionStore = create<SidebarSelectionStoreState>((set) => ({
|
||||
...INITIAL_WORKSPACE_SELECTION_STATE,
|
||||
isArchiving: false,
|
||||
enter: (workspaceKey) =>
|
||||
set(() => ({
|
||||
...enterWorkspaceSelection(workspaceKey),
|
||||
isArchiving: false,
|
||||
})),
|
||||
pressWorkspace: (workspaceKey, { shiftKey }) =>
|
||||
set((state) => {
|
||||
if (state.isArchiving) return state;
|
||||
const next = shiftKey
|
||||
? selectWorkspaceRange(state, workspaceKey, visibleKeysReader())
|
||||
: toggleWorkspaceSelection(state, workspaceKey);
|
||||
return next === state ? state : { ...next };
|
||||
}),
|
||||
reconcile: (availableKeys) =>
|
||||
set((state) => {
|
||||
const next = reconcileWorkspaceSelection(state, availableKeys);
|
||||
return next === state ? state : { ...next };
|
||||
}),
|
||||
setArchiving: (isArchiving) => set({ isArchiving }),
|
||||
exit: () =>
|
||||
set((state) =>
|
||||
state.active || state.isArchiving
|
||||
? { ...exitWorkspaceSelection(), isArchiving: false }
|
||||
: state,
|
||||
),
|
||||
}));
|
||||
|
||||
export function useIsSidebarSelectionMode(): boolean {
|
||||
return useSidebarSelectionStore((state) => state.active);
|
||||
}
|
||||
|
||||
export function useIsWorkspaceBulkSelected(workspaceKey: string): boolean {
|
||||
return useSidebarSelectionStore((state) => state.active && state.selectedKeys.has(workspaceKey));
|
||||
}
|
||||
|
||||
export function useSidebarSelectionCount(): number {
|
||||
return useSidebarSelectionStore((state) => (state.active ? state.selectedKeys.size : 0));
|
||||
}
|
||||
|
||||
export function useSidebarSelectionArchiving(): boolean {
|
||||
return useSidebarSelectionStore((state) => state.isArchiving);
|
||||
}
|
||||
@@ -0,0 +1,355 @@
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import React, { act, useCallback } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { I18nextProvider } from "react-i18next";
|
||||
import { Text } from "react-native";
|
||||
import { SafeAreaProvider } from "react-native-safe-area-context";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { SidebarToastRegion } from "@/components/sidebar/sidebar-toast-region";
|
||||
import { SidebarWorkspaceContextMenu } from "@/components/sidebar/sidebar-workspace-menu";
|
||||
import { ToastProvider, useToast } from "@/contexts/toast-context";
|
||||
import type { ToastApi } from "@/components/toast-host";
|
||||
import type { SidebarWorkspaceEntry } from "@/hooks/use-sidebar-workspaces-list";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import { dispatchTopOverlayKeyDown } from "@/keyboard";
|
||||
import {
|
||||
KeyboardActionDispatcherProvider,
|
||||
useKeyboardActionDispatcher,
|
||||
} from "@/keyboard/keyboard-action-dispatcher-context";
|
||||
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
|
||||
import {
|
||||
isShiftPressEvent,
|
||||
registerSidebarVisibleWorkspaceKeysReader,
|
||||
SidebarSelectionHost,
|
||||
useIsSidebarSelectionMode,
|
||||
useIsWorkspaceBulkSelected,
|
||||
useSidebarSelectionStore,
|
||||
} from "@/sidebar-selection";
|
||||
|
||||
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
|
||||
|
||||
let root: Root | null = null;
|
||||
let container: HTMLDivElement | null = null;
|
||||
let releaseVisibleKeys: (() => void) | null = null;
|
||||
|
||||
function makeEntry(id: string): SidebarWorkspaceEntry {
|
||||
return {
|
||||
workspaceKey: `srv:${id}`,
|
||||
workspaceId: id,
|
||||
serverId: "srv",
|
||||
projectViewKey: "prj-view",
|
||||
projectName: "Repo",
|
||||
projectRootPath: "/repo",
|
||||
workspaceDirectory: `/repo/${id}`,
|
||||
workspaceDirectoryLabel: id,
|
||||
projectKind: "git",
|
||||
workspaceKind: "local_checkout",
|
||||
name: id,
|
||||
title: null,
|
||||
currentBranch: id,
|
||||
statusBucket: "done",
|
||||
statusEnteredAt: null,
|
||||
archivingAt: null,
|
||||
diffStat: null,
|
||||
prHint: null,
|
||||
pinnedAt: null,
|
||||
background: false,
|
||||
labels: [],
|
||||
scripts: [],
|
||||
hasRunningScripts: false,
|
||||
archiveHasUncommittedChanges: null,
|
||||
archiveUnpushedCommitCount: null,
|
||||
};
|
||||
}
|
||||
|
||||
let capturedDispatcher: ReturnType<typeof useKeyboardActionDispatcher> | null = null;
|
||||
let capturedSidebarToast: ToastApi | null = null;
|
||||
let fallbackArchiveCount = 0;
|
||||
|
||||
function FallbackArchiveProbe() {
|
||||
capturedDispatcher = useKeyboardActionDispatcher();
|
||||
useKeyboardActionHandler({
|
||||
handlerId: "test-global-workspace-archive-fallback",
|
||||
actions: ["workspace.archive"],
|
||||
enabled: true,
|
||||
priority: 0,
|
||||
handle: () => {
|
||||
fallbackArchiveCount += 1;
|
||||
return true;
|
||||
},
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
function SidebarToastProbe() {
|
||||
capturedSidebarToast = useToast();
|
||||
return null;
|
||||
}
|
||||
|
||||
const noop = () => {};
|
||||
|
||||
function SelectableRowProbe({ entry }: { entry: SidebarWorkspaceEntry }) {
|
||||
const isSelectionMode = useIsSidebarSelectionMode();
|
||||
const isBulkSelected = useIsWorkspaceBulkSelected(entry.workspaceKey);
|
||||
const handlePress = useCallback(
|
||||
(event: unknown) => {
|
||||
const shiftKey = isShiftPressEvent(event);
|
||||
if (isSelectionMode || shiftKey) {
|
||||
useSidebarSelectionStore.getState().pressWorkspace(entry.workspaceKey, { shiftKey });
|
||||
}
|
||||
},
|
||||
[entry.workspaceKey, isSelectionMode],
|
||||
);
|
||||
return (
|
||||
<SidebarWorkspaceContextMenu
|
||||
contextMenuOpen={false}
|
||||
onContextMenuOpenChange={noop}
|
||||
workspace={entry}
|
||||
workspaceKey={entry.workspaceKey}
|
||||
enabled={!isSelectionMode}
|
||||
accessibilityRole={isSelectionMode ? "checkbox" : "button"}
|
||||
aria-checked={isSelectionMode ? isBulkSelected : undefined}
|
||||
highlightStyle={undefined}
|
||||
onPress={handlePress}
|
||||
testID={`sidebar-workspace-row-${entry.workspaceKey}`}
|
||||
>
|
||||
<Text>{entry.name}</Text>
|
||||
</SidebarWorkspaceContextMenu>
|
||||
);
|
||||
}
|
||||
|
||||
function mountHost(entries: readonly SidebarWorkspaceEntry[]) {
|
||||
const entriesByKey = new Map(entries.map((entry) => [entry.workspaceKey, entry]));
|
||||
releaseVisibleKeys = registerSidebarVisibleWorkspaceKeysReader(() =>
|
||||
entries.map((entry) => entry.workspaceKey),
|
||||
);
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
act(() => {
|
||||
root?.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<I18nextProvider i18n={i18n}>
|
||||
<SafeAreaProvider>
|
||||
<KeyboardActionDispatcherProvider>
|
||||
<FallbackArchiveProbe />
|
||||
<ToastProvider>
|
||||
<SidebarToastRegion active>
|
||||
<SidebarToastProbe />
|
||||
{entries.map((entry) => (
|
||||
<SelectableRowProbe key={entry.workspaceKey} entry={entry} />
|
||||
))}
|
||||
<SidebarSelectionHost active workspaceEntriesByKey={entriesByKey} />
|
||||
</SidebarToastRegion>
|
||||
</ToastProvider>
|
||||
</KeyboardActionDispatcherProvider>
|
||||
</SafeAreaProvider>
|
||||
</I18nextProvider>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
capturedDispatcher = null;
|
||||
capturedSidebarToast = null;
|
||||
fallbackArchiveCount = 0;
|
||||
act(() => {
|
||||
useSidebarSelectionStore.getState().exit();
|
||||
});
|
||||
releaseVisibleKeys?.();
|
||||
releaseVisibleKeys = null;
|
||||
act(() => root?.unmount());
|
||||
container?.remove();
|
||||
root = null;
|
||||
container = null;
|
||||
});
|
||||
|
||||
describe("SidebarSelectionHost", () => {
|
||||
it("shows a persistent sidebar toast while selecting, updates without Shift, and exits via button or Escape", async () => {
|
||||
mountHost([makeEntry("a"), makeEntry("b"), makeEntry("c")]);
|
||||
expect(document.querySelector('[data-testid="workspace-selection-toast"]')).toBeNull();
|
||||
|
||||
// Enter select mode via Shift+click on "a", then plain-click "c" without Shift.
|
||||
act(() => {
|
||||
useSidebarSelectionStore.getState().pressWorkspace("srv:a", { shiftKey: true });
|
||||
});
|
||||
expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe(
|
||||
"1 selected",
|
||||
);
|
||||
|
||||
act(() => {
|
||||
useSidebarSelectionStore.getState().pressWorkspace("srv:c", { shiftKey: false });
|
||||
});
|
||||
expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe(
|
||||
"2 selected",
|
||||
);
|
||||
|
||||
// Clicking the Exit button leaves select mode and fades the persistent toast out.
|
||||
const exitButton = document.querySelector<HTMLElement>(
|
||||
'[data-testid="workspace-selection-exit"]',
|
||||
);
|
||||
expect(exitButton).not.toBeNull();
|
||||
act(() => {
|
||||
exitButton?.click();
|
||||
});
|
||||
expect(useSidebarSelectionStore.getState().active).toBe(false);
|
||||
await expect
|
||||
.poll(() => document.querySelector('[data-testid="workspace-selection-toast"]'))
|
||||
.toBeNull();
|
||||
|
||||
// Re-enter with Shift+click, then Shift+click "c" for a range of 3, and exit with Escape.
|
||||
act(() => {
|
||||
useSidebarSelectionStore.getState().pressWorkspace("srv:a", { shiftKey: true });
|
||||
useSidebarSelectionStore.getState().pressWorkspace("srv:c", { shiftKey: true });
|
||||
});
|
||||
expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe(
|
||||
"3 selected",
|
||||
);
|
||||
|
||||
let prevented = false;
|
||||
act(() => {
|
||||
const handled = dispatchTopOverlayKeyDown({
|
||||
key: "Escape",
|
||||
code: "Escape",
|
||||
altKey: false,
|
||||
ctrlKey: false,
|
||||
metaKey: false,
|
||||
shiftKey: false,
|
||||
repeat: false,
|
||||
preventDefault: () => {
|
||||
prevented = true;
|
||||
},
|
||||
stopPropagation: () => {},
|
||||
});
|
||||
expect(handled).toBe(true);
|
||||
});
|
||||
expect(prevented).toBe(true);
|
||||
expect(useSidebarSelectionStore.getState().active).toBe(false);
|
||||
await expect
|
||||
.poll(() => document.querySelector('[data-testid="workspace-selection-toast"]'))
|
||||
.toBeNull();
|
||||
});
|
||||
|
||||
it("consumes workspace.archive while in select mode even with zero rows selected or while archiving", () => {
|
||||
mountHost([makeEntry("a"), makeEntry("b")]);
|
||||
|
||||
// Outside select mode, the global fallback receives workspace.archive.
|
||||
act(() => {
|
||||
expect(capturedDispatcher?.dispatch({ id: "workspace.archive", scope: "sidebar" })).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
expect(fallbackArchiveCount).toBe(1);
|
||||
|
||||
// Enter select mode then deselect the only row -> 0 selected.
|
||||
act(() => {
|
||||
useSidebarSelectionStore.getState().enter("srv:a");
|
||||
useSidebarSelectionStore.getState().pressWorkspace("srv:a", { shiftKey: false });
|
||||
});
|
||||
expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe(
|
||||
"0 selected",
|
||||
);
|
||||
|
||||
// The archive shortcut must be absorbed by select mode rather than archiving the open workspace.
|
||||
act(() => {
|
||||
expect(capturedDispatcher?.dispatch({ id: "workspace.archive", scope: "sidebar" })).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
expect(fallbackArchiveCount).toBe(1);
|
||||
|
||||
// Same while a worktree safety check is in progress (both archive shortcut and Escape stay owned).
|
||||
act(() => {
|
||||
useSidebarSelectionStore.getState().enter("srv:a");
|
||||
useSidebarSelectionStore.getState().setArchiving(true);
|
||||
});
|
||||
act(() => {
|
||||
expect(capturedDispatcher?.dispatch({ id: "workspace.archive", scope: "sidebar" })).toBe(
|
||||
true,
|
||||
);
|
||||
expect(
|
||||
dispatchTopOverlayKeyDown({
|
||||
key: "Escape",
|
||||
code: "Escape",
|
||||
altKey: false,
|
||||
ctrlKey: false,
|
||||
metaKey: false,
|
||||
shiftKey: false,
|
||||
repeat: false,
|
||||
preventDefault: () => {},
|
||||
stopPropagation: () => {},
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
expect(fallbackArchiveCount).toBe(1);
|
||||
expect(useSidebarSelectionStore.getState().active).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps the selection bar visible when an Undo toast is already displayed in the sidebar", () => {
|
||||
mountHost([makeEntry("a"), makeEntry("b")]);
|
||||
|
||||
let dismissUndo: (() => void) | undefined;
|
||||
act(() => {
|
||||
dismissUndo = capturedSidebarToast?.show("Workspace archived", {
|
||||
durationMs: 6000,
|
||||
testID: "workspace-archived-toast",
|
||||
});
|
||||
});
|
||||
expect(document.querySelector('[data-testid="workspace-archived-toast"]')).not.toBeNull();
|
||||
|
||||
act(() => {
|
||||
useSidebarSelectionStore.getState().enter("srv:a");
|
||||
});
|
||||
|
||||
// Both the Undo toast and the selection bar (count, Archive, Exit) must remain visible.
|
||||
expect(document.querySelector('[data-testid="workspace-archived-toast"]')).not.toBeNull();
|
||||
expect(document.querySelector('[data-testid="workspace-selection-toast"]')).not.toBeNull();
|
||||
expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe(
|
||||
"1 selected",
|
||||
);
|
||||
expect(document.querySelector('[data-testid="workspace-selection-archive"]')).not.toBeNull();
|
||||
expect(document.querySelector('[data-testid="workspace-selection-exit"]')).not.toBeNull();
|
||||
|
||||
act(() => {
|
||||
dismissUndo?.();
|
||||
});
|
||||
});
|
||||
|
||||
it("toggles focused workspace checkboxes when pressing Space in select mode", () => {
|
||||
mountHost([makeEntry("a"), makeEntry("b")]);
|
||||
|
||||
act(() => {
|
||||
useSidebarSelectionStore.getState().enter("srv:a");
|
||||
});
|
||||
|
||||
const rowB = document.querySelector<HTMLElement>('[data-testid="sidebar-workspace-row-srv:b"]');
|
||||
expect(rowB?.getAttribute("role")).toBe("checkbox");
|
||||
expect(rowB?.getAttribute("aria-checked")).toBe("false");
|
||||
|
||||
act(() => {
|
||||
rowB?.focus();
|
||||
rowB?.dispatchEvent(
|
||||
new KeyboardEvent("keydown", { key: " ", bubbles: true, cancelable: true }),
|
||||
);
|
||||
rowB?.dispatchEvent(
|
||||
new KeyboardEvent("keydown", { key: " ", repeat: true, bubbles: true, cancelable: true }),
|
||||
);
|
||||
});
|
||||
expect(rowB?.getAttribute("aria-checked")).toBe("true");
|
||||
expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe(
|
||||
"2 selected",
|
||||
);
|
||||
|
||||
act(() => {
|
||||
rowB?.dispatchEvent(
|
||||
new KeyboardEvent("keydown", { key: " ", bubbles: true, cancelable: true }),
|
||||
);
|
||||
});
|
||||
expect(rowB?.getAttribute("aria-checked")).toBe("false");
|
||||
expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe(
|
||||
"1 selected",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,157 @@
|
||||
import { useCallback, useEffect, useMemo, useRef } from "react";
|
||||
import {
|
||||
useSidebarAppToast,
|
||||
useSidebarPersistentToast,
|
||||
} from "@/components/sidebar/sidebar-toast-region";
|
||||
import type { ToastState } from "@/components/toast-host";
|
||||
import { useToast } from "@/contexts/toast-context";
|
||||
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
|
||||
import type { SidebarWorkspaceEntry } from "@/hooks/use-sidebar-workspaces-list";
|
||||
import { useOverlayRegistration } from "@/keyboard";
|
||||
import type { KeyboardActionId } from "@/keyboard/keyboard-action-dispatcher";
|
||||
import { useActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store";
|
||||
import { archiveSelectedWorkspaces, createDefaultBulkArchiveDeps } from "./archive-selected";
|
||||
import {
|
||||
useIsSidebarSelectionMode,
|
||||
useSidebarSelectionArchiving,
|
||||
useSidebarSelectionCount,
|
||||
useSidebarSelectionStore,
|
||||
} from "./selection-store";
|
||||
import { WorkspaceSelectionToast } from "./workspace-selection-toast";
|
||||
|
||||
const SELECTION_TOAST_ID = -1;
|
||||
const ESCAPE_OVERLAY_KEYS = ["Escape"] as const;
|
||||
const WORKSPACE_ARCHIVE_ACTIONS: readonly KeyboardActionId[] = ["workspace.archive"];
|
||||
|
||||
/**
|
||||
* Coordinates sidebar workspace select mode: reconciles removed workspaces, binds Escape and
|
||||
* the archive shortcut, and keeps the persistent selection bar up in `SidebarToastRegion`.
|
||||
*/
|
||||
export function SidebarSelectionHost({
|
||||
active,
|
||||
workspaceEntriesByKey,
|
||||
}: {
|
||||
active: boolean;
|
||||
workspaceEntriesByKey: ReadonlyMap<string, SidebarWorkspaceEntry>;
|
||||
}): null {
|
||||
const toast = useToast();
|
||||
const appToast = useSidebarAppToast();
|
||||
const activeWorkspaceSelection = useActiveWorkspaceSelection();
|
||||
const selectionMode = useIsSidebarSelectionMode();
|
||||
const selectedCount = useSidebarSelectionCount();
|
||||
const isArchiving = useSidebarSelectionArchiving();
|
||||
|
||||
const entriesRef = useRef(workspaceEntriesByKey);
|
||||
entriesRef.current = workspaceEntriesByKey;
|
||||
const activeSelectionRef = useRef(activeWorkspaceSelection);
|
||||
activeSelectionRef.current = activeWorkspaceSelection;
|
||||
const archiveAttemptRef = useRef(0);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectionMode) return;
|
||||
useSidebarSelectionStore.getState().reconcile(new Set(workspaceEntriesByKey.keys()));
|
||||
}, [selectionMode, workspaceEntriesByKey]);
|
||||
|
||||
useEffect(() => {
|
||||
if (active) return;
|
||||
const state = useSidebarSelectionStore.getState();
|
||||
if (state.active && !state.isArchiving) {
|
||||
state.exit();
|
||||
}
|
||||
}, [active]);
|
||||
|
||||
const handleExit = useCallback(() => {
|
||||
const state = useSidebarSelectionStore.getState();
|
||||
if (state.isArchiving) return;
|
||||
state.exit();
|
||||
}, []);
|
||||
|
||||
const handleArchiveSelected = useCallback(() => {
|
||||
const store = useSidebarSelectionStore.getState();
|
||||
if (!store.active || store.isArchiving || store.selectedKeys.size === 0) return;
|
||||
|
||||
const entries: SidebarWorkspaceEntry[] = [];
|
||||
for (const key of store.selectedKeys) {
|
||||
const entry = entriesRef.current.get(key);
|
||||
if (entry && entry.archivingAt === null) {
|
||||
entries.push(entry);
|
||||
}
|
||||
}
|
||||
if (entries.length === 0) {
|
||||
store.exit();
|
||||
return;
|
||||
}
|
||||
|
||||
const attemptId = archiveAttemptRef.current + 1;
|
||||
archiveAttemptRef.current = attemptId;
|
||||
store.setArchiving(true);
|
||||
void archiveSelectedWorkspaces({
|
||||
workspaces: entries,
|
||||
toast,
|
||||
fallbackErrorToast: appToast,
|
||||
onArchiveStarted: () => {
|
||||
useSidebarSelectionStore.getState().exit();
|
||||
},
|
||||
deps: createDefaultBulkArchiveDeps(() => activeSelectionRef.current),
|
||||
}).finally(() => {
|
||||
if (archiveAttemptRef.current !== attemptId) return;
|
||||
const current = useSidebarSelectionStore.getState();
|
||||
if (current.isArchiving) {
|
||||
current.setArchiving(false);
|
||||
}
|
||||
});
|
||||
}, [appToast, toast]);
|
||||
|
||||
useOverlayRegistration({
|
||||
keys: ESCAPE_OVERLAY_KEYS,
|
||||
// Keep Escape owned while select mode is active (including during worktree checks) so it
|
||||
// never falls through to interrupt a running agent in the open workspace; any higher-layer
|
||||
// confirmation dialog still receives Escape first.
|
||||
active: selectionMode && active,
|
||||
layer: 0,
|
||||
manageFocus: false,
|
||||
onKeyDown: (event) => {
|
||||
if (event.key !== "Escape") return false;
|
||||
event.preventDefault();
|
||||
handleExit();
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
||||
useKeyboardActionHandler({
|
||||
handlerId: "sidebar-selection-archive",
|
||||
actions: WORKSPACE_ARCHIVE_ACTIONS,
|
||||
// Keep ownership of workspace.archive for the entire lifetime of select mode so pressing it
|
||||
// at 0 selected or during a worktree check never falls through to archive the open workspace.
|
||||
enabled: selectionMode && active,
|
||||
priority: 10,
|
||||
handle: () => {
|
||||
handleArchiveSelected();
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
||||
const persistentToast = useMemo<ToastState | null>(() => {
|
||||
if (!selectionMode || !active) return null;
|
||||
return {
|
||||
id: SELECTION_TOAST_ID,
|
||||
content: (
|
||||
<WorkspaceSelectionToast
|
||||
selectedCount={selectedCount}
|
||||
isArchiving={isArchiving}
|
||||
onArchive={handleArchiveSelected}
|
||||
onExit={handleExit}
|
||||
/>
|
||||
),
|
||||
nativeMessage: null,
|
||||
variant: "default",
|
||||
layout: "action",
|
||||
durationMs: null,
|
||||
testID: "workspace-selection-toast",
|
||||
};
|
||||
}, [active, handleArchiveSelected, handleExit, isArchiving, selectedCount, selectionMode]);
|
||||
|
||||
useSidebarPersistentToast(persistentToast);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import { X } from "lucide-react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Text, View } from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { CONTROL_HEIGHTS } from "@/components/ui/control-geometry";
|
||||
import { DensityIcon } from "@/components/ui/density-icon";
|
||||
import { ToolbarButton } from "@/components/ui/pane-content-toolbar";
|
||||
import type { ShortcutKey } from "@/utils/format-shortcut";
|
||||
|
||||
const EXIT_SHORTCUT_CHORD: ShortcutKey[][] = [["Esc"]];
|
||||
|
||||
export function WorkspaceSelectionToast({
|
||||
selectedCount,
|
||||
isArchiving,
|
||||
onArchive,
|
||||
onExit,
|
||||
}: {
|
||||
selectedCount: number;
|
||||
isArchiving: boolean;
|
||||
onArchive: () => void;
|
||||
onExit: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const exitLabel = t("sidebar.workspace.selection.exit");
|
||||
|
||||
return (
|
||||
<View style={styles.row}>
|
||||
<Text style={styles.message} numberOfLines={1} testID="workspace-selection-count">
|
||||
{t("sidebar.workspace.selection.count", { count: selectedCount })}
|
||||
</Text>
|
||||
<View style={styles.actions}>
|
||||
<Button
|
||||
size="sm"
|
||||
onPress={onArchive}
|
||||
disabled={selectedCount === 0}
|
||||
loading={isArchiving}
|
||||
testID="workspace-selection-archive"
|
||||
>
|
||||
{t("sidebar.workspace.actions.archive")}
|
||||
</Button>
|
||||
<ToolbarButton
|
||||
round
|
||||
tooltipSide="top"
|
||||
label={exitLabel}
|
||||
shortcut={EXIT_SHORTCUT_CHORD}
|
||||
onPress={onExit}
|
||||
disabled={isArchiving}
|
||||
style={styles.exitButton}
|
||||
testID="workspace-selection-exit"
|
||||
>
|
||||
<DensityIcon icon={X} size="sm" color="foregroundMuted" />
|
||||
</ToolbarButton>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
row: {
|
||||
flexDirection: "row",
|
||||
flexWrap: "wrap",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[3],
|
||||
},
|
||||
message: {
|
||||
flexShrink: 1,
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.base,
|
||||
fontWeight: theme.fontWeight.normal,
|
||||
},
|
||||
actions: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[1],
|
||||
},
|
||||
// Matches the Archive button's sm pill height so the circular hover fill sits concentrically
|
||||
// in the action toast's trailing corner.
|
||||
exitButton: {
|
||||
width: CONTROL_HEIGHTS.sm,
|
||||
height: CONTROL_HEIGHTS.sm,
|
||||
},
|
||||
}));
|
||||
@@ -324,12 +324,6 @@ 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[] }
|
||||
@@ -504,7 +498,6 @@ 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>;
|
||||
@@ -624,12 +617,6 @@ 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>),
|
||||
@@ -766,7 +753,6 @@ function createInitialSessionState(
|
||||
agentTimelineUnsettledTurn: new Map(),
|
||||
agentTimelineHasOlder: new Map(),
|
||||
agentTimelineHasNewer: new Map(),
|
||||
agentTimelineLatestRewind: new Map(),
|
||||
agentTimelineOlderFetchInFlight: new Map(),
|
||||
historySyncGeneration: 0,
|
||||
agentHistorySyncGeneration: new Map(),
|
||||
@@ -1415,24 +1401,6 @@ 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, anchorSeq: seq },
|
||||
timelineCursor: { epoch: "epoch-1", seq },
|
||||
};
|
||||
}
|
||||
|
||||
@@ -579,235 +579,6 @@ 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, anchorSeq: 1 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 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, anchorSeq: 2 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 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, anchorSeq: 40 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 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, anchorSeq: 235 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 235 },
|
||||
};
|
||||
const newerLive: StreamItem = {
|
||||
...makeAssistantItem("newer live", "newer-live"),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 245, anchorSeq: 245 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 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, anchorSeq: 40 },
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42 },
|
||||
}),
|
||||
]);
|
||||
});
|
||||
@@ -745,7 +745,7 @@ describe("processTimelineResponse", () => {
|
||||
}).item,
|
||||
} as AgentStreamEventPayload,
|
||||
timestamp: new Date(2000),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2 },
|
||||
},
|
||||
],
|
||||
{ source: "canonical" },
|
||||
@@ -775,7 +775,7 @@ describe("processTimelineResponse", () => {
|
||||
|
||||
expect(getAgentToolCalls([...result.tail, ...result.head])).toEqual([
|
||||
expect.objectContaining({
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 1 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2 },
|
||||
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, anchorSeq: 2 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 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, anchorSeq: 1 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2 },
|
||||
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, anchorSeq: 2 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 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, anchorSeq: 1 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2 },
|
||||
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, anchorSeq: 101 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 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, anchorSeq: 100 });
|
||||
expect(assistants[0]?.timelineCursor).toEqual({ epoch: "epoch-1", seq: 101 });
|
||||
});
|
||||
|
||||
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, anchorSeq: 101 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 101 },
|
||||
},
|
||||
{
|
||||
event: makeAssistantTimelineEvent("after tool", messageId),
|
||||
timestamp: new Date(2102),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 102, anchorSeq: 102 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 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, anchorSeq: 101 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 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, anchorSeq: 100 });
|
||||
expect(assistants[0]?.timelineCursor).toEqual({ epoch: "epoch-1", seq: 101 });
|
||||
});
|
||||
|
||||
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, anchorSeq: 101 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 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, anchorSeq: 51 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 51 },
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2808,7 +2808,7 @@ describe("processTimelineResponse", () => {
|
||||
id: "newest",
|
||||
text: "newest",
|
||||
timestamp: new Date(1000),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 100, anchorSeq: 100 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 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, anchorSeq: 1 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1 },
|
||||
},
|
||||
{
|
||||
kind: "user_message",
|
||||
id: "newest",
|
||||
text: "newest",
|
||||
timestamp: new Date(100_000),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 100, anchorSeq: 100 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 100 },
|
||||
},
|
||||
];
|
||||
|
||||
@@ -2935,7 +2935,7 @@ describe("processTimelineResponse", () => {
|
||||
id: "newest",
|
||||
text: "newest",
|
||||
timestamp: new Date(100_000),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 100, anchorSeq: 100 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 100 },
|
||||
},
|
||||
...(lane === "tail" ? [pending] : []),
|
||||
],
|
||||
@@ -2976,13 +2976,9 @@ describe("processTimelineResponse", () => {
|
||||
{
|
||||
text: "local pending prompt",
|
||||
messageId: "canonical-message",
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
|
||||
},
|
||||
{
|
||||
text: "newest",
|
||||
messageId: undefined,
|
||||
timelineCursor: { epoch: "epoch-1", seq: 100, anchorSeq: 100 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1 },
|
||||
},
|
||||
{ text: "newest", messageId: undefined, timelineCursor: { epoch: "epoch-1", seq: 100 } },
|
||||
],
|
||||
head: [],
|
||||
acknowledgedClientMessageIds: [clientMessageId],
|
||||
@@ -2996,7 +2992,7 @@ describe("processTimelineResponse", () => {
|
||||
{
|
||||
event: makeToolCallTimelineEvent("call-1"),
|
||||
timestamp: new Date(500),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 500, anchorSeq: 500 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 500 },
|
||||
},
|
||||
],
|
||||
{ source: "canonical" },
|
||||
@@ -3042,7 +3038,7 @@ describe("processTimelineResponse", () => {
|
||||
{
|
||||
callId: "call-1",
|
||||
status: "completed",
|
||||
timelineCursor: { epoch: "epoch-1", seq: 500, anchorSeq: 1 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 500 },
|
||||
},
|
||||
]);
|
||||
});
|
||||
@@ -3054,7 +3050,7 @@ describe("processTimelineResponse", () => {
|
||||
...makeAssistantItem("projected response", "loaded-assistant"),
|
||||
messageId: "assistant-message",
|
||||
timestamp,
|
||||
timelineCursor: { epoch: "epoch-1", seq: 500, anchorSeq: 500 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 500 },
|
||||
},
|
||||
];
|
||||
const result = processTimelineResponse({
|
||||
@@ -3104,7 +3100,7 @@ describe("processTimelineResponse", () => {
|
||||
id: "loaded-assistant",
|
||||
text: "projected response",
|
||||
messageId: "assistant-message",
|
||||
timelineCursor: { epoch: "epoch-1", seq: 500, anchorSeq: 1 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 500 },
|
||||
},
|
||||
]);
|
||||
});
|
||||
@@ -3116,7 +3112,7 @@ describe("processTimelineResponse", () => {
|
||||
id: "current-200",
|
||||
text: "current-200",
|
||||
timestamp: new Date(3200),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 200, anchorSeq: 200 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 200 },
|
||||
},
|
||||
];
|
||||
const existingCursor: TimelineCursor = {
|
||||
@@ -3223,7 +3219,7 @@ describe("processTimelineResponse", () => {
|
||||
const currentTail = [
|
||||
{
|
||||
...makeAssistantItem("newer chunk", "assistant-newer"),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 3, anchorSeq: 3 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 3 },
|
||||
},
|
||||
];
|
||||
const existingCursor: TimelineCursor = {
|
||||
@@ -3250,7 +3246,7 @@ describe("processTimelineResponse", () => {
|
||||
expect(result.tail[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
id: "assistant-newer",
|
||||
timelineCursor: { epoch: "epoch-1", seq: 3, anchorSeq: 3 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 3 },
|
||||
}),
|
||||
);
|
||||
expect(result.cursor).toEqual({
|
||||
@@ -3690,7 +3686,7 @@ describe("processAgentStreamEvent", () => {
|
||||
expect.objectContaining({
|
||||
kind: "assistant_message",
|
||||
text: "[System Error] failed",
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42 },
|
||||
}),
|
||||
]);
|
||||
});
|
||||
@@ -3937,7 +3933,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, anchorSeq: 51 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 51 },
|
||||
});
|
||||
expect(result.cursorChanged).toBe(false);
|
||||
expect(result.cursor).toBeNull();
|
||||
@@ -3972,7 +3968,7 @@ describe("processAgentStreamEvent", () => {
|
||||
clientMessageId: "client-message-1",
|
||||
messageId: "provider-message-1",
|
||||
text: "submitted before bootstrap",
|
||||
timelineCursor: { epoch: "epoch-1", seq: 51, anchorSeq: 51 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 51 },
|
||||
}),
|
||||
]);
|
||||
});
|
||||
@@ -4563,279 +4559,6 @@ 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" },
|
||||
@@ -5093,30 +4816,4 @@ 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,13 +1,7 @@
|
||||
import type { AgentMetric, AgentTimelineItem } from "@getpaseo/protocol/agent-types";
|
||||
import type { AgentStreamEventPayload } from "@getpaseo/protocol/messages";
|
||||
import { selectAgentTimelineState, useSessionStore } from "@/stores/session-store";
|
||||
import {
|
||||
advanceTimelinePosition,
|
||||
type AssistantMessageItem,
|
||||
type StreamItem,
|
||||
type TimelinePosition,
|
||||
type TodoEntry,
|
||||
} from "@/types/stream";
|
||||
import type { AssistantMessageItem, StreamItem, TodoEntry } from "@/types/stream";
|
||||
import type { TurnLivenessTransition } from "@/timeline/turn-liveness";
|
||||
import { stampTimelineTurnMetrics } from "@/timeline/turn-metrics";
|
||||
import {
|
||||
@@ -78,64 +72,6 @@ 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,
|
||||
@@ -216,7 +152,6 @@ export interface ProcessTimelineResponseInput {
|
||||
hasNewer: boolean;
|
||||
hasOlder: boolean;
|
||||
mergeWindow?: boolean;
|
||||
retirements?: TimelineRetirement[];
|
||||
};
|
||||
currentTail: StreamItem[];
|
||||
currentHead: StreamItem[];
|
||||
@@ -461,7 +396,7 @@ function mergeTimelineWindow(args: {
|
||||
toHydratedEvents: (units: TimelineUnit[]) => Array<{
|
||||
event: AgentStreamEventPayload;
|
||||
timestamp: Date;
|
||||
timelineCursor: TimelinePosition;
|
||||
timelineCursor: { epoch: string; seq: number };
|
||||
}>;
|
||||
}): TimelinePathResult {
|
||||
const { timelineUnits, payload, currentTail, currentHead, currentCursor, toHydratedEvents } =
|
||||
@@ -825,7 +760,7 @@ function replaceLiveAssistantWithProjectedText(params: {
|
||||
head: StreamItem[];
|
||||
event: AgentStreamEventPayload;
|
||||
timestamp: Date;
|
||||
timelineCursor: TimelinePosition;
|
||||
timelineCursor: { epoch: string; seq: number };
|
||||
}): StreamItem[] | null {
|
||||
const { head, event, timestamp, timelineCursor } = params;
|
||||
if (event.type !== "timeline" || event.item.type !== "assistant_message") {
|
||||
@@ -844,7 +779,7 @@ function replaceLiveAssistantWithProjectedText(params: {
|
||||
...current,
|
||||
text: event.item.text,
|
||||
timestamp,
|
||||
...advanceTimelinePosition(current.timelineCursor, timelineCursor),
|
||||
timelineCursor,
|
||||
};
|
||||
return next;
|
||||
}
|
||||
@@ -894,7 +829,7 @@ function reconcileOverlappingProjectedAssistant(params: {
|
||||
...(messageId !== undefined ? { messageId } : {}),
|
||||
text: projectedText,
|
||||
timestamp: unit.timestamp,
|
||||
timelineCursor: { epoch: params.epoch, seq: unit.seqEnd, anchorSeq: unit.seq },
|
||||
timelineCursor: { epoch: params.epoch, seq: unit.seqEnd },
|
||||
};
|
||||
const replaceMatch = (items: StreamItem[], index: number) => {
|
||||
const next = [...items];
|
||||
@@ -1011,8 +946,8 @@ function applyCanonicalForwardUnit(params: {
|
||||
unit: TimelineUnit;
|
||||
epoch: string;
|
||||
}): { tail: StreamItem[]; head: StreamItem[]; acknowledgedClientMessageIds: string[] } {
|
||||
const { event, timestamp, seq, seqEnd } = params.unit;
|
||||
const timelineCursor: TimelinePosition = { epoch: params.epoch, seq: seqEnd, anchorSeq: seq };
|
||||
const { event, timestamp, seqEnd } = params.unit;
|
||||
const timelineCursor = { epoch: params.epoch, seq: seqEnd };
|
||||
if (event.type === "timeline" && event.item.type === "user_message") {
|
||||
const applied = applyStreamEvent({
|
||||
tail: params.tail,
|
||||
@@ -1211,10 +1146,10 @@ function applyAcceptedTimelinePage(input: {
|
||||
});
|
||||
}
|
||||
const olderTail = hydrateStreamState(
|
||||
acceptedUnits.map(({ event, timestamp, seq, seqEnd }) => ({
|
||||
acceptedUnits.map(({ event, timestamp, seqEnd }) => ({
|
||||
event,
|
||||
timestamp,
|
||||
timelineCursor: { epoch: payload.epoch, seq: seqEnd, anchorSeq: seq },
|
||||
timelineCursor: { epoch: payload.epoch, seq: seqEnd },
|
||||
})),
|
||||
{
|
||||
source: "canonical",
|
||||
@@ -1246,12 +1181,7 @@ function applyTimelineIncrementalPath(args: {
|
||||
let cursorChanged = false;
|
||||
const sideEffects: TimelineReducerSideEffect[] = [];
|
||||
|
||||
// A forward page of retirements alone still advances the loaded end.
|
||||
if (
|
||||
timelineUnits.length === 0 &&
|
||||
payload.direction !== "before" &&
|
||||
(payload.retirements?.length ?? 0) === 0
|
||||
) {
|
||||
if (timelineUnits.length === 0 && payload.direction !== "before") {
|
||||
return {
|
||||
tail: currentTail,
|
||||
head: currentHead,
|
||||
@@ -1309,6 +1239,8 @@ export function processTimelineResponse(
|
||||
): ProcessTimelineResponseOutput {
|
||||
const {
|
||||
payload,
|
||||
currentTail,
|
||||
currentHead,
|
||||
currentCursor,
|
||||
isInitializing,
|
||||
hasActiveInitDeferred,
|
||||
@@ -1322,8 +1254,8 @@ export function processTimelineResponse(
|
||||
if (payload.error) {
|
||||
return {
|
||||
commit: "apply",
|
||||
tail: input.currentTail,
|
||||
head: input.currentHead,
|
||||
tail: currentTail,
|
||||
head: currentHead,
|
||||
cursor: currentCursor,
|
||||
cursorChanged: false,
|
||||
older: "unchanged",
|
||||
@@ -1335,13 +1267,6 @@ 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
|
||||
// ------------------------------------------------------------------
|
||||
@@ -1367,12 +1292,12 @@ export function processTimelineResponse(
|
||||
): Array<{
|
||||
event: AgentStreamEventPayload;
|
||||
timestamp: Date;
|
||||
timelineCursor: TimelinePosition;
|
||||
timelineCursor: { epoch: string; seq: number };
|
||||
}> =>
|
||||
units.map(({ event, timestamp, seq, seqEnd }) => ({
|
||||
units.map(({ event, timestamp, seqEnd }) => ({
|
||||
event,
|
||||
timestamp,
|
||||
timelineCursor: { epoch: payload.epoch, seq: seqEnd, anchorSeq: seq },
|
||||
timelineCursor: { epoch: payload.epoch, seq: seqEnd },
|
||||
}));
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
@@ -1507,7 +1432,7 @@ export function processTimelineResponse(
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface ProcessAgentStreamEventInput {
|
||||
event: AgentStreamEventPayload | TimelineRewindEvent;
|
||||
event: AgentStreamEventPayload;
|
||||
seq: number | undefined;
|
||||
epoch: string | undefined;
|
||||
currentTail: StreamItem[];
|
||||
@@ -1530,7 +1455,7 @@ export interface ProcessAgentStreamEventOutput {
|
||||
}
|
||||
|
||||
export interface AgentStreamReducerEvent {
|
||||
event: AgentStreamEventPayload | TimelineRewindEvent;
|
||||
event: AgentStreamEventPayload;
|
||||
seq: number | undefined;
|
||||
epoch: string | undefined;
|
||||
timestamp: Date;
|
||||
@@ -1648,70 +1573,11 @@ 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,
|
||||
@@ -1730,7 +1596,7 @@ export function processAgentStreamEvent(
|
||||
});
|
||||
const timelineCursor =
|
||||
event.type === "timeline" && seq !== undefined && epoch !== undefined
|
||||
? { epoch, seq, anchorSeq: seq }
|
||||
? { epoch, seq }
|
||||
: undefined;
|
||||
// ------------------------------------------------------------------
|
||||
// Apply stream event to tail/head
|
||||
@@ -2044,10 +1910,6 @@ 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,13 +237,6 @@ 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,
|
||||
@@ -464,14 +457,8 @@ 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): TimelineResponseOutcome;
|
||||
applyTimelineResponse(payload: TimelineResponsePayload): void;
|
||||
/**
|
||||
* 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
|
||||
@@ -481,37 +468,6 @@ 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;
|
||||
@@ -521,7 +477,6 @@ export function createViewedTimelineOwner(input: {
|
||||
ports: ViewedTimelineOwnerPorts;
|
||||
}): ViewedTimelineOwner {
|
||||
const forcedTailReplacements = new Set<string>();
|
||||
const retirements = createRetirementHighWater();
|
||||
const sync = createViewedTimelineSync({
|
||||
...input.ports,
|
||||
fetchLatestTail: async (agentId) => {
|
||||
@@ -562,8 +517,6 @@ 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,
|
||||
@@ -573,12 +526,8 @@ export function createViewedTimelineOwner(input: {
|
||||
drainQueuedAgentMessage: input.drainQueuedAgentMessage,
|
||||
});
|
||||
if (accepted) input.replica.timelineUpdated(payload.agentId);
|
||||
return "applied";
|
||||
},
|
||||
applyStreamEvent(agentId, event) {
|
||||
if (event.event.type === "rewind" && event.epoch !== undefined && event.seq !== undefined) {
|
||||
retirements.note(agentId, { epoch: event.epoch, seq: event.seq });
|
||||
}
|
||||
streamQueue.enqueue(agentId, event);
|
||||
const turnLiveness = deriveAgentStreamTurnLiveness([event]);
|
||||
if (turnLiveness.length === 0) return;
|
||||
|
||||
@@ -1009,7 +1009,7 @@ describe("stream reducer canonical tool calls", () => {
|
||||
});
|
||||
|
||||
it("keeps the timeline position on the whole assistant message", () => {
|
||||
const timelineCursor = { epoch: "epoch-1", seq: 42, anchorSeq: 42 };
|
||||
const timelineCursor = { epoch: "epoch-1", seq: 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, anchorSeq: 42 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 42 },
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1902,11 +1902,7 @@ 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,
|
||||
anchorSeq: 42,
|
||||
});
|
||||
assert.deepStrictEqual(userMessage.timelineCursor, { epoch: "epoch-1", seq: 42 });
|
||||
assert.deepStrictEqual(userMessage.images, [image]);
|
||||
assert.deepStrictEqual(userMessage.attachments, [attachment]);
|
||||
});
|
||||
|
||||
@@ -266,7 +266,7 @@ function produceUserMessage(
|
||||
...presentation,
|
||||
clientMessageId: incoming.clientMessageId ?? existing.clientMessageId,
|
||||
messageId: incoming.messageId ?? existing.messageId,
|
||||
...advanceTimelinePosition(existing.timelineCursor, incoming.timelineCursor),
|
||||
timelineCursor: incoming.timelineCursor ?? existing.timelineCursor,
|
||||
});
|
||||
if (
|
||||
existing.id === merged.id &&
|
||||
@@ -482,7 +482,7 @@ function mergeRetainedLifecycleItem(tail: StreamItem[], retained: StreamItem): S
|
||||
const next = [...tail];
|
||||
next[tailIndex] = {
|
||||
...existing,
|
||||
...advanceTimelinePosition(existing.timelineCursor, retained.timelineCursor),
|
||||
timelineCursor: retained.timelineCursor,
|
||||
timestamp: retained.timestamp,
|
||||
items: retained.items,
|
||||
};
|
||||
@@ -499,7 +499,7 @@ function mergeRetainedLifecycleItem(tail: StreamItem[], retained: StreamItem): S
|
||||
const next = [...tail];
|
||||
next[tailIndex] = {
|
||||
...existing,
|
||||
...advanceTimelinePosition(existing.timelineCursor, retained.timelineCursor),
|
||||
timelineCursor: retained.timelineCursor,
|
||||
status: "completed",
|
||||
trigger: retained.trigger ?? existing.trigger,
|
||||
preTokens: retained.preTokens ?? existing.preTokens,
|
||||
@@ -519,10 +519,7 @@ function replaceTimelineIdentityItem(
|
||||
const existing = items[index];
|
||||
if (index < 0 || !existing || existing.kind !== "plugin") return null;
|
||||
const next = [...items];
|
||||
next[index] = {
|
||||
...retained,
|
||||
...advanceTimelinePosition(existing.timelineCursor, retained.timelineCursor),
|
||||
};
|
||||
next[index] = retained;
|
||||
return next;
|
||||
}
|
||||
|
||||
@@ -613,11 +610,7 @@ function preserveReplacementHead(
|
||||
: `${tailAssistant.text}${liveAssistant.text}`;
|
||||
const head = [
|
||||
...unreconciledHead.slice(0, liveAssistantIndex),
|
||||
{
|
||||
...liveAssistant,
|
||||
text,
|
||||
...advanceTimelinePosition(tailAssistant.timelineCursor, liveAssistant.timelineCursor),
|
||||
},
|
||||
{ ...liveAssistant, text },
|
||||
...unreconciledHead.slice(liveAssistantIndex + 1),
|
||||
];
|
||||
return {
|
||||
@@ -632,13 +625,7 @@ function preserveReplacementHead(
|
||||
|
||||
const head = [
|
||||
...unreconciledHead.slice(0, liveAssistantIndex),
|
||||
{
|
||||
...liveAssistant,
|
||||
text: tailAssistant.text,
|
||||
...(liveAssistant.timelineCursor
|
||||
? advanceTimelinePosition(tailAssistant.timelineCursor, liveAssistant.timelineCursor)
|
||||
: {}),
|
||||
},
|
||||
{ ...liveAssistant, text: tailAssistant.text },
|
||||
...unreconciledHead.slice(liveAssistantIndex + 1),
|
||||
];
|
||||
return {
|
||||
@@ -737,27 +724,7 @@ export interface AssistantMessageItem {
|
||||
|
||||
export interface TimelinePosition {
|
||||
epoch: string;
|
||||
/** The latest seq that changed this row. */
|
||||
seq: number;
|
||||
/** The seq the row started at. Updates never move it; rewinds retire rows by it. */
|
||||
anchorSeq: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* The position of a row after an update: it moves to the update's seq and stays anchored where it
|
||||
* started. Without an incoming position the row keeps the one it has.
|
||||
*/
|
||||
export function advanceTimelinePosition(
|
||||
existing: TimelinePosition | undefined,
|
||||
incoming: TimelinePosition | undefined,
|
||||
): { timelineCursor?: TimelinePosition } {
|
||||
if (!incoming) return existing ? { timelineCursor: existing } : {};
|
||||
if (!existing || existing.epoch !== incoming.epoch) return { timelineCursor: incoming };
|
||||
const anchorSeq = Math.min(existing.anchorSeq, incoming.anchorSeq);
|
||||
if (existing.seq === incoming.seq && existing.anchorSeq === anchorSeq) {
|
||||
return { timelineCursor: existing };
|
||||
}
|
||||
return { timelineCursor: { ...incoming, anchorSeq } };
|
||||
}
|
||||
|
||||
export type ThoughtStatus = "loading" | "ready";
|
||||
@@ -1016,7 +983,7 @@ function appendAssistantMessage(
|
||||
...last,
|
||||
text: `${last.text}${chunk}`,
|
||||
timestamp,
|
||||
...advanceTimelinePosition(last.timelineCursor, timelineCursor),
|
||||
...(timelineCursor ? { timelineCursor } : {}),
|
||||
};
|
||||
return [...state.slice(0, -1), updated];
|
||||
}
|
||||
@@ -1034,7 +1001,7 @@ function appendAssistantMessage(
|
||||
...secondLast,
|
||||
text: `${secondLast.text}${chunk}`,
|
||||
timestamp,
|
||||
...advanceTimelinePosition(secondLast.timelineCursor, timelineCursor),
|
||||
...(timelineCursor ? { timelineCursor } : {}),
|
||||
};
|
||||
return [...state.slice(0, -2), updated, last];
|
||||
}
|
||||
@@ -1072,7 +1039,7 @@ function appendThought(
|
||||
if (last && last.kind === "thought" && last.turnId === turnId) {
|
||||
const updated: ThoughtItem = {
|
||||
...last,
|
||||
...advanceTimelinePosition(last.timelineCursor, timelineCursor),
|
||||
...(timelineCursor ? { timelineCursor } : {}),
|
||||
text: `${last.text}${chunk}`,
|
||||
timestamp,
|
||||
status: "loading",
|
||||
@@ -1252,7 +1219,7 @@ export function mergeAgentToolCallItem(
|
||||
|
||||
return {
|
||||
...existing,
|
||||
...advanceTimelinePosition(existing.timelineCursor, timelineCursor),
|
||||
...(timelineCursor ? { timelineCursor } : {}),
|
||||
timestamp,
|
||||
payload: {
|
||||
source: "agent",
|
||||
@@ -1358,11 +1325,7 @@ function appendPluginTimelineItem(
|
||||
const existing = state[existingIndex];
|
||||
if (!existing || existing.kind !== "plugin") return state;
|
||||
const next = [...state];
|
||||
next[existingIndex] = {
|
||||
...nextItem,
|
||||
id: existing.id,
|
||||
...advanceTimelinePosition(existing.timelineCursor, timelineCursor),
|
||||
};
|
||||
next[existingIndex] = { ...nextItem, id: existing.id };
|
||||
return next;
|
||||
}
|
||||
|
||||
@@ -1393,7 +1356,7 @@ function appendTodoList(
|
||||
const next = [...state];
|
||||
next[previousIndex] = {
|
||||
...previous,
|
||||
...advanceTimelinePosition(previous.timelineCursor, timelineCursor),
|
||||
...(timelineCursor ? { timelineCursor } : {}),
|
||||
items: normalizedItems,
|
||||
timestamp,
|
||||
};
|
||||
@@ -1412,7 +1375,7 @@ function appendTodoList(
|
||||
const next = [...state];
|
||||
next[next.length - 1] = {
|
||||
...lastItem,
|
||||
...advanceTimelinePosition(lastItem.timelineCursor, timelineCursor),
|
||||
...(timelineCursor ? { timelineCursor } : {}),
|
||||
items: normalizedItems,
|
||||
activity: { type: "created", count: normalizedItems.length },
|
||||
timestamp,
|
||||
@@ -1557,7 +1520,7 @@ function reduceTimelineCompaction(
|
||||
if (loadingIdx >= 0 && existing && existing.kind === "compaction") {
|
||||
const updated: CompactionItem = {
|
||||
...existing,
|
||||
...advanceTimelinePosition(existing.timelineCursor, timelineCursor),
|
||||
...(timelineCursor ? { timelineCursor } : {}),
|
||||
status: "completed",
|
||||
trigger: item.trigger ?? existing.trigger,
|
||||
preTokens: item.preTokens ?? existing.preTokens,
|
||||
@@ -1682,10 +1645,7 @@ export function reduceStreamUpdate(
|
||||
),
|
||||
event,
|
||||
);
|
||||
const stamped = event.turnMetrics?.length
|
||||
? stampCompletedTurnMetrics(updated, event.turnMetrics, event.turnId)
|
||||
: updated;
|
||||
return event.item.type === "reasoning" ? stamped : finalizeActiveThoughts(stamped);
|
||||
return event.item.type === "reasoning" ? updated : finalizeActiveThoughts(updated);
|
||||
}
|
||||
case "turn_completed":
|
||||
return stampCompletedTurnMetrics(finalizeActiveThoughts(state), event.metrics, event.turnId);
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
export {
|
||||
archiveWorkspaceWithUndo,
|
||||
archiveWorkspacesWithUndo,
|
||||
hasUndoableWorkspaceArchive,
|
||||
undoLatestWorkspaceArchive,
|
||||
type UndoableWorkspaceArchiveClient,
|
||||
type UndoableWorkspaceArchiveEntryInput,
|
||||
type WorkspaceArchiveBatchFailure,
|
||||
type WorkspaceArchiveBatchResult,
|
||||
} from "./internal/undo-window";
|
||||
export { WorkspaceArchiveUndoShortcutHost } from "./internal/undo-shortcut-host";
|
||||
export { supportsWorkspaceArchiveUndo } from "./internal/capability";
|
||||
|
||||
@@ -8,6 +8,7 @@ import { useSessionStore, type WorkspaceDescriptor } from "@/stores/session-stor
|
||||
import { seedSessionHosts } from "@/test/seed-session";
|
||||
import {
|
||||
archiveWorkspaceWithUndo,
|
||||
archiveWorkspacesWithUndo,
|
||||
undoLatestWorkspaceArchive,
|
||||
type UndoableWorkspaceArchiveClient,
|
||||
} from "@/workspace/archive-undo";
|
||||
@@ -82,6 +83,9 @@ function createToastHost() {
|
||||
get shownTestID() {
|
||||
return shown?.options?.testID ?? null;
|
||||
},
|
||||
get shownVariant() {
|
||||
return shown?.options?.variant ?? null;
|
||||
},
|
||||
timeOut: () => shown?.dismiss(),
|
||||
};
|
||||
}
|
||||
@@ -299,3 +303,166 @@ describe("archiveWorkspaceWithUndo", () => {
|
||||
}).toEqual({ toast: null, undone: false, row: workspace("a") });
|
||||
});
|
||||
});
|
||||
|
||||
describe("archiveWorkspacesWithUndo", () => {
|
||||
it("hides every workspace in the batch and undoes all of them together", async () => {
|
||||
const host = createClient();
|
||||
const toast = createToastHost();
|
||||
const committed: string[] = [];
|
||||
|
||||
const batch = archiveWorkspacesWithUndo({
|
||||
entries: [
|
||||
{
|
||||
client: host.client,
|
||||
workspace: { serverId: SERVER_ID, workspaceId: "a" },
|
||||
onArchiveCommitted: () => committed.push("a"),
|
||||
},
|
||||
{
|
||||
client: host.client,
|
||||
workspace: { serverId: SERVER_ID, workspaceId: "b" },
|
||||
onArchiveCommitted: () => committed.push("b"),
|
||||
},
|
||||
],
|
||||
toast: toast.api,
|
||||
});
|
||||
|
||||
expect(storedWorkspace("a")).toBeUndefined();
|
||||
expect(storedWorkspace("b")).toBeUndefined();
|
||||
expect(toast.shownTestID).toBe("workspace-archived-toast");
|
||||
|
||||
expect(undoLatestWorkspaceArchive()).toBe(true);
|
||||
expect({
|
||||
a: storedWorkspace("a"),
|
||||
b: storedWorkspace("b"),
|
||||
undoA: host.undoRequested("a"),
|
||||
undoB: host.undoRequested("b"),
|
||||
toast: toast.shownTestID,
|
||||
}).toEqual({
|
||||
a: workspace("a"),
|
||||
b: workspace("b"),
|
||||
undoA: true,
|
||||
undoB: true,
|
||||
toast: null,
|
||||
});
|
||||
|
||||
host.finishArchive("a", { canceled: true });
|
||||
host.finishArchive("b", { canceled: true });
|
||||
await expect(batch.then((result) => result.failures)).resolves.toEqual([]);
|
||||
host.finishUndo("a");
|
||||
host.finishUndo("b");
|
||||
expect(committed).toEqual([]);
|
||||
});
|
||||
|
||||
it("commits every workspace in the batch when the toast times out", async () => {
|
||||
const host = createClient();
|
||||
const toast = createToastHost();
|
||||
const committed: string[] = [];
|
||||
|
||||
const batch = archiveWorkspacesWithUndo({
|
||||
entries: [
|
||||
{
|
||||
client: host.client,
|
||||
workspace: { serverId: SERVER_ID, workspaceId: "a" },
|
||||
onArchiveCommitted: () => committed.push("a"),
|
||||
},
|
||||
{
|
||||
client: host.client,
|
||||
workspace: { serverId: SERVER_ID, workspaceId: "b" },
|
||||
onArchiveCommitted: () => committed.push("b"),
|
||||
},
|
||||
],
|
||||
toast: toast.api,
|
||||
});
|
||||
|
||||
host.finishArchive("a");
|
||||
host.finishArchive("b");
|
||||
await expect(batch.then((result) => result.failures)).resolves.toEqual([]);
|
||||
expect(committed).toEqual([]);
|
||||
|
||||
toast.timeOut();
|
||||
expect(committed).toEqual(["a", "b"]);
|
||||
});
|
||||
|
||||
it("restores only the failed workspace on partial failure and keeps undo open when surfacing the error", async () => {
|
||||
const host = createClient();
|
||||
const toast = createToastHost();
|
||||
const committed: string[] = [];
|
||||
|
||||
const batch = archiveWorkspacesWithUndo({
|
||||
entries: [
|
||||
{
|
||||
client: host.client,
|
||||
workspace: { serverId: SERVER_ID, workspaceId: "a" },
|
||||
onArchiveCommitted: () => committed.push("a"),
|
||||
},
|
||||
{
|
||||
client: host.client,
|
||||
workspace: { serverId: SERVER_ID, workspaceId: "b" },
|
||||
onArchiveCommitted: () => committed.push("b"),
|
||||
},
|
||||
],
|
||||
toast: toast.api,
|
||||
});
|
||||
|
||||
host.finishArchive("a");
|
||||
host.finishArchive("b", { error: "busy" });
|
||||
const { failures, showPartialFailure } = await batch;
|
||||
|
||||
expect(failures).toHaveLength(1);
|
||||
expect(failures[0]?.workspace.workspaceId).toBe("b");
|
||||
expect(storedWorkspace("a")).toBeUndefined();
|
||||
expect(storedWorkspace("b")).toEqual(workspace("b"));
|
||||
|
||||
// Updating the toast with the partial-failure error must not dismiss Undo or commit "a".
|
||||
expect(showPartialFailure("busy")).toBe(true);
|
||||
expect({
|
||||
toast: toast.shownTestID,
|
||||
variant: toast.shownVariant,
|
||||
committed,
|
||||
}).toEqual({
|
||||
toast: "workspace-archived-toast",
|
||||
variant: "error",
|
||||
committed: [],
|
||||
});
|
||||
|
||||
expect(undoLatestWorkspaceArchive()).toBe(true);
|
||||
expect({ undoA: host.undoRequested("a"), undoB: host.undoRequested("b") }).toEqual({
|
||||
undoA: true,
|
||||
undoB: false,
|
||||
});
|
||||
expect(committed).toEqual([]);
|
||||
});
|
||||
|
||||
it("commits surviving workspaces once a partial-failure undo toast times out", async () => {
|
||||
const host = createClient();
|
||||
const toast = createToastHost();
|
||||
const committed: string[] = [];
|
||||
|
||||
const batch = archiveWorkspacesWithUndo({
|
||||
entries: [
|
||||
{
|
||||
client: host.client,
|
||||
workspace: { serverId: SERVER_ID, workspaceId: "a" },
|
||||
onArchiveCommitted: () => committed.push("a"),
|
||||
},
|
||||
{
|
||||
client: host.client,
|
||||
workspace: { serverId: SERVER_ID, workspaceId: "b" },
|
||||
onArchiveCommitted: () => committed.push("b"),
|
||||
},
|
||||
],
|
||||
toast: toast.api,
|
||||
});
|
||||
|
||||
host.finishArchive("a");
|
||||
host.finishArchive("b", { error: "busy" });
|
||||
const { showPartialFailure } = await batch;
|
||||
|
||||
expect(showPartialFailure("busy")).toBe(true);
|
||||
expect(committed).toEqual([]);
|
||||
|
||||
toast.timeOut();
|
||||
expect(committed).toEqual(["a"]);
|
||||
expect(undoLatestWorkspaceArchive()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -17,18 +17,28 @@ export interface UndoableWorkspaceArchiveClient {
|
||||
undoWorkspaceArchive: (workspaceId: string) => Promise<void>;
|
||||
}
|
||||
|
||||
interface UndoWindowInput {
|
||||
export interface UndoableWorkspaceArchiveEntryInput {
|
||||
client: UndoableWorkspaceArchiveClient;
|
||||
workspace: WorkspaceArchiveTarget;
|
||||
toast: ToastApi;
|
||||
hidden: WorkspaceDescriptor | null;
|
||||
onArchiveCommitted: () => void;
|
||||
}
|
||||
|
||||
interface UndoWindowEntry extends UndoableWorkspaceArchiveEntryInput {
|
||||
hidden: WorkspaceDescriptor | null;
|
||||
archived: boolean;
|
||||
failed: boolean;
|
||||
committed: boolean;
|
||||
}
|
||||
|
||||
interface UndoWindowInput {
|
||||
entries: UndoWindowEntry[];
|
||||
toast: ToastApi;
|
||||
}
|
||||
|
||||
let latest: UndoWindow | null = null;
|
||||
|
||||
/**
|
||||
* One archive's chance to be undone. It opens when the row hides and closes when its toast
|
||||
* One archive batch's chance to be undone. It opens when the row(s) hide and closes when its toast
|
||||
* leaves the screen (timeout, replaced by another toast, or undo).
|
||||
*
|
||||
* - `open`: undo is offered.
|
||||
@@ -37,40 +47,78 @@ let latest: UndoWindow | null = null;
|
||||
*/
|
||||
class UndoWindow {
|
||||
phase: "open" | "closed" | "undone" = "open";
|
||||
private archived = false;
|
||||
private readonly dismissToast: DismissToast;
|
||||
private dismissToast: DismissToast = () => {};
|
||||
private toastToken: object | null = null;
|
||||
|
||||
constructor(private readonly input: UndoWindowInput) {
|
||||
this.dismissToast = input.toast.show(<WorkspaceArchivedToast onUndo={this.undo} />, {
|
||||
durationMs: WORKSPACE_ARCHIVE_UNDO_WINDOW_MS,
|
||||
testID: "workspace-archived-toast",
|
||||
onDismiss: this.close,
|
||||
});
|
||||
this.showToast({ variant: "default" });
|
||||
}
|
||||
|
||||
/** The host finished the archive. It commits now if undo is no longer offered. */
|
||||
archiveFinished(): void {
|
||||
this.archived = true;
|
||||
if (this.phase === "closed") this.commit();
|
||||
private showToast(options: { message?: string; variant: "default" | "error" }): void {
|
||||
const token = {};
|
||||
this.toastToken = token;
|
||||
const remainingCount = this.input.entries.filter((entry) => !entry.failed).length;
|
||||
this.dismissToast = this.input.toast.show(
|
||||
<WorkspaceArchivedToast
|
||||
count={remainingCount}
|
||||
message={options.message}
|
||||
onUndo={this.undo}
|
||||
/>,
|
||||
{
|
||||
variant: options.variant,
|
||||
layout: "action",
|
||||
durationMs: WORKSPACE_ARCHIVE_UNDO_WINDOW_MS,
|
||||
testID: "workspace-archived-toast",
|
||||
onDismiss: () => {
|
||||
// Replacing our own toast in place (for example to surface a partial failure) must not
|
||||
// close the undo window or purge surviving workspaces.
|
||||
if (this.toastToken !== token) return;
|
||||
this.close();
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/** The archive failed on the host, so there is nothing left to undo. */
|
||||
archiveFailed(): void {
|
||||
this.close();
|
||||
this.dismissToast();
|
||||
/**
|
||||
* Surfaces a partial-failure message on the active undo toast without dismissing Undo for the
|
||||
* workspaces that did archive. Returns false once the window is closed, undone, or superseded.
|
||||
*/
|
||||
showPartialFailure(message: string): boolean {
|
||||
if (this.phase !== "open" || latest !== this) return false;
|
||||
this.showToast({ message, variant: "error" });
|
||||
return true;
|
||||
}
|
||||
|
||||
/** The host finished archiving this entry. It commits now if undo is no longer offered. */
|
||||
entryFinished(entry: UndoWindowEntry): void {
|
||||
entry.archived = true;
|
||||
if (this.phase === "closed") this.commitEntry(entry);
|
||||
}
|
||||
|
||||
/** The archive failed on the host. Dismisses the toast once every entry has failed. */
|
||||
entryFailed(entry: UndoWindowEntry): void {
|
||||
entry.failed = true;
|
||||
if (this.input.entries.every((item) => item.failed)) {
|
||||
this.close();
|
||||
this.dismissToast();
|
||||
}
|
||||
}
|
||||
|
||||
readonly close = (): void => {
|
||||
if (this.phase !== "open") return;
|
||||
this.phase = "closed";
|
||||
this.release();
|
||||
if (this.archived) this.commit();
|
||||
for (const entry of this.input.entries) {
|
||||
if (entry.archived) this.commitEntry(entry);
|
||||
}
|
||||
};
|
||||
|
||||
/** Commits unless the workspace is back by now, for example restored from another client. */
|
||||
private commit(): void {
|
||||
if (isWorkspaceListed(this.input.workspace)) return;
|
||||
this.input.onArchiveCommitted();
|
||||
private commitEntry(entry: UndoWindowEntry): void {
|
||||
if (entry.committed || entry.failed) return;
|
||||
if (isWorkspaceListed(entry.workspace)) return;
|
||||
entry.committed = true;
|
||||
entry.onArchiveCommitted();
|
||||
}
|
||||
|
||||
readonly undo = (): boolean => {
|
||||
@@ -78,10 +126,19 @@ class UndoWindow {
|
||||
this.phase = "undone";
|
||||
this.release();
|
||||
this.dismissToast();
|
||||
void undoWorkspaceArchiveOptimistically(this.input).catch((error: unknown) => {
|
||||
console.warn("[workspace-archive-undo] undo failed", error);
|
||||
this.input.toast.error(i18n.t("sidebar.workspace.toasts.undoArchiveFailed"));
|
||||
});
|
||||
const undoable = this.input.entries.filter((entry) => !entry.failed);
|
||||
void (async () => {
|
||||
const results = await Promise.allSettled(
|
||||
undoable.map((entry) => undoWorkspaceArchiveOptimistically(entry)),
|
||||
);
|
||||
const failed = results.filter(
|
||||
(result): result is PromiseRejectedResult => result.status === "rejected",
|
||||
);
|
||||
if (failed.length > 0) {
|
||||
console.warn("[workspace-archive-undo] undo failed", failed[0]?.reason);
|
||||
this.input.toast.error(i18n.t("sidebar.workspace.toasts.undoArchiveFailed"));
|
||||
}
|
||||
})();
|
||||
return true;
|
||||
};
|
||||
|
||||
@@ -90,6 +147,75 @@ class UndoWindow {
|
||||
}
|
||||
}
|
||||
|
||||
export interface WorkspaceArchiveBatchFailure {
|
||||
workspace: WorkspaceArchiveTarget;
|
||||
error: unknown;
|
||||
}
|
||||
|
||||
export interface WorkspaceArchiveBatchResult {
|
||||
failures: WorkspaceArchiveBatchFailure[];
|
||||
/**
|
||||
* Updates this batch's live undo toast to show a partial-failure error while keeping Undo active
|
||||
* for the workspaces that succeeded. Returns false if the undo window is no longer open.
|
||||
*/
|
||||
showPartialFailure: (message: string) => boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Archives one or more workspaces together and offers one undo until the toast goes away.
|
||||
*
|
||||
* `onArchiveCommitted` runs per workspace once that archive both finished on the host and can no
|
||||
* longer be undone, and only if the workspace is still gone then. Returns failures for any
|
||||
* workspace whose archive failed while not undone; those rows are already restored.
|
||||
*/
|
||||
export async function archiveWorkspacesWithUndo(input: {
|
||||
entries: readonly UndoableWorkspaceArchiveEntryInput[];
|
||||
toast: ToastApi;
|
||||
}): Promise<WorkspaceArchiveBatchResult> {
|
||||
if (input.entries.length === 0) {
|
||||
return { failures: [], showPartialFailure: () => false };
|
||||
}
|
||||
|
||||
const started = input.entries.map((entry) => {
|
||||
const archive = beginOptimisticWorkspaceArchive(entry);
|
||||
const windowEntry: UndoWindowEntry = {
|
||||
...entry,
|
||||
hidden: archive.hidden,
|
||||
archived: false,
|
||||
failed: false,
|
||||
committed: false,
|
||||
};
|
||||
return { windowEntry, done: archive.done };
|
||||
});
|
||||
|
||||
const window = new UndoWindow({
|
||||
entries: started.map((item) => item.windowEntry),
|
||||
toast: input.toast,
|
||||
});
|
||||
latest = window;
|
||||
|
||||
const failures: WorkspaceArchiveBatchFailure[] = [];
|
||||
await Promise.all(
|
||||
started.map(async ({ windowEntry, done }) => {
|
||||
let outcome: Awaited<typeof done>;
|
||||
try {
|
||||
outcome = await done;
|
||||
} catch (error) {
|
||||
if (window.phase === "undone") return;
|
||||
window.entryFailed(windowEntry);
|
||||
failures.push({ workspace: windowEntry.workspace, error });
|
||||
return;
|
||||
}
|
||||
if (outcome === "archived") window.entryFinished(windowEntry);
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
failures,
|
||||
showPartialFailure: (message) => window.showPartialFailure(message),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Archives a workspace and offers to undo it until the toast goes away.
|
||||
*
|
||||
@@ -104,19 +230,19 @@ export async function archiveWorkspaceWithUndo(input: {
|
||||
toast: ToastApi;
|
||||
onArchiveCommitted: () => void;
|
||||
}): Promise<void> {
|
||||
const archive = beginOptimisticWorkspaceArchive(input);
|
||||
const window = new UndoWindow({ ...input, hidden: archive.hidden });
|
||||
latest = window;
|
||||
|
||||
let outcome: Awaited<typeof archive.done>;
|
||||
try {
|
||||
outcome = await archive.done;
|
||||
} catch (error) {
|
||||
if (window.phase === "undone") return;
|
||||
window.archiveFailed();
|
||||
throw error;
|
||||
const { failures } = await archiveWorkspacesWithUndo({
|
||||
entries: [
|
||||
{
|
||||
client: input.client,
|
||||
workspace: input.workspace,
|
||||
onArchiveCommitted: input.onArchiveCommitted,
|
||||
},
|
||||
],
|
||||
toast: input.toast,
|
||||
});
|
||||
if (failures[0]) {
|
||||
throw failures[0].error;
|
||||
}
|
||||
if (outcome === "archived") window.archiveFinished();
|
||||
}
|
||||
|
||||
/** Undoes the most recent archive while its toast is up. Returns false when there is none. */
|
||||
|
||||
@@ -6,17 +6,30 @@ import { Button } from "@/components/ui/button";
|
||||
import { Shortcut } from "@/components/ui/shortcut";
|
||||
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
|
||||
|
||||
export function WorkspaceArchivedToast({ onUndo }: { onUndo: () => void }) {
|
||||
export function WorkspaceArchivedToast({
|
||||
count = 1,
|
||||
message: customMessage,
|
||||
onUndo,
|
||||
}: {
|
||||
count?: number;
|
||||
message?: string;
|
||||
onUndo: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const undoKeys = useShortcutKeys("undo-archive-workspace");
|
||||
const undoShortcut = useMemo(
|
||||
() => (undoKeys ? <Shortcut chord={undoKeys} style={styles.shortcut} /> : null),
|
||||
[undoKeys],
|
||||
);
|
||||
const message =
|
||||
customMessage ??
|
||||
(count === 1
|
||||
? t("sidebar.workspace.toasts.archived")
|
||||
: t("sidebar.workspace.toasts.archivedCount", { count }));
|
||||
|
||||
return (
|
||||
<View style={styles.row}>
|
||||
<Text style={styles.message}>{t("sidebar.workspace.toasts.archived")}</Text>
|
||||
<Text style={styles.message}>{message}</Text>
|
||||
<Button
|
||||
size="sm"
|
||||
onPress={onUndo}
|
||||
@@ -34,7 +47,7 @@ const styles = StyleSheet.create((theme) => ({
|
||||
flexDirection: "row",
|
||||
flexWrap: "wrap",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
gap: theme.spacing[3],
|
||||
},
|
||||
// Cancels the badge's own inset, which would otherwise add to the button's gap.
|
||||
shortcut: {
|
||||
|
||||
@@ -44,6 +44,7 @@ export const EyeOff = StubIcon;
|
||||
export const File = StubIcon;
|
||||
export const FileText = StubIcon;
|
||||
export const Folder = StubIcon;
|
||||
export const FolderOpen = StubIcon;
|
||||
export const FolderPlus = StubIcon;
|
||||
export const FolderTree = StubIcon;
|
||||
export const Gift = StubIcon;
|
||||
@@ -107,6 +108,7 @@ export const SquareSlash = StubIcon;
|
||||
export const SquareTerminal = StubIcon;
|
||||
export const Star = StubIcon;
|
||||
export const Sun = StubIcon;
|
||||
export const Tag = StubIcon;
|
||||
export const Terminal = StubIcon;
|
||||
export const Trash2 = StubIcon;
|
||||
export const TriangleAlert = StubIcon;
|
||||
|
||||
@@ -47,8 +47,5 @@
|
||||
"typescript": "^5.2.2",
|
||||
"vitest": "^4.1.6",
|
||||
"zx": "^8.8.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.16.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -146,10 +146,6 @@ export async function runAttachCommand(
|
||||
const unsubscribe = client.subscribeAgentTimeline(resolvedId, (message) => {
|
||||
if (message.type === "agent.timeline.replacement") {
|
||||
console.log("\n[Timeline replaced; earlier output is no longer current]");
|
||||
} else if (message.type === "agent.timeline.rewind") {
|
||||
console.log(
|
||||
"\n[Conversation rewound; output since the rewound message is no longer current]",
|
||||
);
|
||||
} else if (message.type === "agent.timeline.subscription_restored") {
|
||||
console.log("\n[Reconnected; live output resumed. Events may have been missed.]");
|
||||
} else if (message.type === "agent.timeline.error") {
|
||||
|
||||
@@ -408,6 +408,7 @@ async function runFollowMode({
|
||||
} catch (error) {
|
||||
console.warn("Warning: failed to fetch existing timeline", error);
|
||||
}
|
||||
|
||||
// Apply filter to existing items
|
||||
if (options.filter) {
|
||||
existingItems = existingItems.filter((item) => matchesFilter(item, options.filter));
|
||||
@@ -438,11 +439,6 @@ async function runFollowMode({
|
||||
notice("\n[Timeline replaced; earlier output is no longer current]");
|
||||
return;
|
||||
}
|
||||
if (message.type === "agent.timeline.rewind") {
|
||||
writer.end();
|
||||
notice("\n[Conversation rewound; output since the rewound message is no longer current]");
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.type === "agent.timeline.error") {
|
||||
writer.end();
|
||||
|
||||
@@ -210,12 +210,7 @@ try {
|
||||
console.log("Foreground SIGINT reached the supervisor. The worker and ACP processes exited.");
|
||||
|
||||
daemon = await startSupervisor();
|
||||
// The stored timeline is served without reopening the agent.
|
||||
const storedIdle = (await daemon.client.fetchAgentTimeline(idle.id)).agent;
|
||||
assert.equal(storedIdle?.status, "closed");
|
||||
assert.equal(storedIdle?.requiresAttention, false);
|
||||
await daemon.client.refreshAgent(idle.id);
|
||||
const restoredIdle = (await daemon.client.fetchAgent(idle.id))?.agent;
|
||||
const restoredIdle = (await daemon.client.fetchAgentTimeline(idle.id)).agent;
|
||||
assert.equal(restoredIdle?.status, "idle");
|
||||
assert.equal(restoredIdle?.requiresAttention, false);
|
||||
await waitFor(async () => {
|
||||
|
||||
@@ -211,37 +211,6 @@ test("SDK subscribers receive timeline replacement instead of silently losing hi
|
||||
}
|
||||
});
|
||||
|
||||
test("SDK subscribers receive a conversation rewind as a retired range", async () => {
|
||||
const { createPaseoApi } = await import("./index");
|
||||
const h = connection();
|
||||
const received: unknown[] = [];
|
||||
try {
|
||||
const ready = h.client.connect();
|
||||
h.open();
|
||||
await ready;
|
||||
const off = createPaseoApi(h.client)
|
||||
.agents.ref("agent")
|
||||
.timeline.subscribe((event) => received.push(event));
|
||||
await off.ready;
|
||||
h.receive({
|
||||
type: "agent.timeline.rewind",
|
||||
payload: {
|
||||
agentId: "agent",
|
||||
epoch: "epoch-1",
|
||||
seq: 12,
|
||||
retireFromSeq: 7,
|
||||
subscriptionId: off.subscriptionId,
|
||||
},
|
||||
});
|
||||
expect(received).toEqual([
|
||||
{ agentId: "agent", event: { type: "rewind", epoch: "epoch-1", seq: 12, retireFromSeq: 7 } },
|
||||
]);
|
||||
off();
|
||||
} finally {
|
||||
await h.client.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("local listeners create no demand before or after reconnect", async () => {
|
||||
const h = connection();
|
||||
try {
|
||||
|
||||
@@ -141,7 +141,6 @@ export const DEFAULT_CLIENT_CAPABILITIES = {
|
||||
[CLIENT_CAPS.compactProviderSnapshots]: true,
|
||||
[CLIENT_CAPS.providerSnapshotReferences]: true,
|
||||
[CLIENT_CAPS.timelineReplacementInvalidation]: true,
|
||||
[CLIENT_CAPS.timelineRewindOperations]: true,
|
||||
[CLIENT_CAPS.timelineNotifications]: true,
|
||||
[CLIENT_CAPS.pluginTimelineItems]: true,
|
||||
[CLIENT_CAPS.workspaceSetupBlocked]: true,
|
||||
|
||||
@@ -246,9 +246,7 @@ export class LegacySubscriptions {
|
||||
);
|
||||
case "agent.timeline.set_subscription.request":
|
||||
return (
|
||||
(message.type === "agent_stream" ||
|
||||
message.type === "agent.timeline.replacement" ||
|
||||
message.type === "agent.timeline.rewind") &&
|
||||
(message.type === "agent_stream" || message.type === "agent.timeline.replacement") &&
|
||||
(query.agentIds as string[]).includes(message.payload.agentId)
|
||||
);
|
||||
case "session.events.set_subscription.request":
|
||||
|
||||
@@ -1132,7 +1132,6 @@ test("advertises client capabilities in hello", async () => {
|
||||
all_providers: true,
|
||||
selective_agent_timeline: true,
|
||||
timeline_replacement_invalidation: true,
|
||||
timeline_rewind_operations: true,
|
||||
provider_snapshot_references: true,
|
||||
explicit_event_subscriptions: true,
|
||||
owned_subscriptions: true,
|
||||
|
||||
@@ -346,14 +346,6 @@ export type PaseoAgentTimelineEvent =
|
||||
agentId: string;
|
||||
event: { type: "replacement"; epoch: string };
|
||||
}
|
||||
| {
|
||||
/**
|
||||
* A conversation rewind removed the rows anchored in `[retireFromSeq, seq)` from the active
|
||||
* history. Rows after `seq` belong to the rewound conversation.
|
||||
*/
|
||||
agentId: string;
|
||||
event: { type: "rewind"; epoch: string; seq: number; retireFromSeq: number };
|
||||
}
|
||||
| {
|
||||
agentId: string;
|
||||
subscriptionId: string;
|
||||
@@ -375,9 +367,7 @@ export interface PaseoAgentTimelineHandle {
|
||||
* Delivers live events only. After reconnect, subscription_restored precedes
|
||||
* subsequent updates. History may have been missed; use refetch() to request
|
||||
* the range you need. No history is fetched automatically. A replacement event
|
||||
* invalidates the previous epoch. A rewind event removes `[retireFromSeq, seq)`
|
||||
* from the active history without changing the epoch. Subscription errors
|
||||
* release this observation.
|
||||
* invalidates the previous epoch. Subscription errors release this observation.
|
||||
* Await the returned unsubscribe function's `ready` promise before starting
|
||||
* work that must be observed. It rejects if establishment fails.
|
||||
*/
|
||||
@@ -1057,16 +1047,6 @@ function createAgentHandleFactory(
|
||||
agentId: id,
|
||||
event: { type: "replacement", epoch: message.payload.epoch },
|
||||
});
|
||||
case "agent.timeline.rewind":
|
||||
return handler({
|
||||
agentId: id,
|
||||
event: {
|
||||
type: "rewind",
|
||||
epoch: message.payload.epoch,
|
||||
seq: message.payload.seq,
|
||||
retireFromSeq: message.payload.retireFromSeq,
|
||||
},
|
||||
});
|
||||
}
|
||||
}),
|
||||
},
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { OwnedSubscription, TimelineSubscription } from "../connection/inde
|
||||
|
||||
type TimelineUpdate = Extract<
|
||||
SessionOutboundMessage,
|
||||
{ type: "agent_stream" | "agent.timeline.replacement" | "agent.timeline.rewind" }
|
||||
{ type: "agent_stream" | "agent.timeline.replacement" }
|
||||
>;
|
||||
|
||||
/** Local SDK lifecycle messages; these are not additional wire RPCs. */
|
||||
@@ -59,11 +59,7 @@ export function subscribeTimeline(
|
||||
});
|
||||
},
|
||||
update: (message) => {
|
||||
if (
|
||||
message.type === "agent_stream" ||
|
||||
message.type === "agent.timeline.replacement" ||
|
||||
message.type === "agent.timeline.rewind"
|
||||
)
|
||||
if (message.type === "agent_stream" || message.type === "agent.timeline.replacement")
|
||||
notify(message);
|
||||
},
|
||||
error: fail,
|
||||
|
||||
@@ -58,6 +58,11 @@
|
||||
"types": "./dist/server/lifecycle.d.ts",
|
||||
"source": "./src/server/lifecycle.ts",
|
||||
"default": "./dist/server/lifecycle.js"
|
||||
},
|
||||
"./internal/windows-command": {
|
||||
"types": "./dist/server/process-internal/windows-command.d.ts",
|
||||
"source": "./src/server/process-internal/windows-command.ts",
|
||||
"default": "./dist/server/process-internal/windows-command.js"
|
||||
}
|
||||
},
|
||||
"publishConfig": {
|
||||
|
||||
@@ -14,6 +14,7 @@ const entries = {
|
||||
"./server/usage": "server",
|
||||
"./server/acp": "server",
|
||||
"./internal/lifecycle": "server",
|
||||
"./internal/windows-command": "server",
|
||||
"./client": "client",
|
||||
"./client/host": "client",
|
||||
"./client/ui": "client",
|
||||
@@ -392,7 +393,7 @@ describe("lifecycle hook SDK types", () => {
|
||||
it("infers payloads and replacement requests and requires async handlers and new names", () => {
|
||||
expect(
|
||||
typeErrors(`
|
||||
import type { PluginServerContext, PluginHooks, PluginHookPayload, PluginHookResult } from "@getpaseo/plugin/server";
|
||||
import type { PluginServerContext, PluginHooks, PluginHookPayload, PluginHookResult, PluginLaunchWrap } from "@getpaseo/plugin/server";
|
||||
import type { AgentTimelineItem } from "@getpaseo/protocol/agent-types";
|
||||
export default function contribute(server: PluginServerContext) {
|
||||
server.addHook("worktree.create.before", async ({ request }) => {
|
||||
@@ -427,6 +428,38 @@ describe("lifecycle hook SDK types", () => {
|
||||
const { metadata, ...withoutMetadata } = request;
|
||||
return withoutMetadata;
|
||||
});
|
||||
server.addHook("agent.create.before", async ({ request }) => {
|
||||
const workspace: string | null = request.workspaceId;
|
||||
// @ts-expect-error The agent's workspace is read-only.
|
||||
request.workspaceId = "wks_other";
|
||||
});
|
||||
// Results built before workspaceId existed still typecheck; the daemon keeps the id.
|
||||
server.addHook("agent.create.before", async ({ request }) => ({ config: request.config, env: request.env }));
|
||||
server.before("agent.create", ({ request }) => ({ config: request.config, env: request.env }));
|
||||
server.addHook("terminal.create.before", async ({ request }) => {
|
||||
const source: "client" | "agent" | "script" | "worktree" = request.source;
|
||||
const input: string | null = request.input;
|
||||
const program: string | null = request.command;
|
||||
// @ts-expect-error The terminal's workspace is read-only.
|
||||
request.workspaceId = "wks_other";
|
||||
// @ts-expect-error The terminal's program is read-only; return a wrap instead.
|
||||
request.command = "/usr/bin/other";
|
||||
const wrap: PluginLaunchWrap = ["/usr/bin/sandbox", "--workspace", request.workspaceId];
|
||||
return { ...request, env: { A: "1" }, wrap };
|
||||
});
|
||||
server.addHook("command.run.before", async ({ request }) => {
|
||||
const workspace: string | null = request.workspaceId;
|
||||
const purpose: "setup" | "teardown" = request.purpose;
|
||||
// @ts-expect-error A command's purpose is read-only.
|
||||
request.purpose = "setup";
|
||||
// @ts-expect-error The configured command is read-only; return a wrap instead.
|
||||
request.command = "wrapper " + request.command;
|
||||
return { ...request, wrap: ["/usr/bin/sandbox"] };
|
||||
});
|
||||
server.addHook("agent.open.before", async ({ request }) => ({
|
||||
...request,
|
||||
wrap: ["/usr/bin/sandbox", "--workspace", request.workspaceId ?? "none"],
|
||||
}));
|
||||
server.addHook("agent.turn.after", async (event, { paseo, signal }) => {
|
||||
const { agent, outcome } = event;
|
||||
const kind: "completed" | "failed" | "canceled" = outcome.kind;
|
||||
|
||||
@@ -86,6 +86,8 @@ export async function createAcpProviderConnection(
|
||||
emit: () => undefined,
|
||||
});
|
||||
const supportedCapabilities: ProviderCapability[] = [...ADAPTER_CAPABILITIES];
|
||||
// A connector stream has no process of its own to wrap.
|
||||
if (options.command) supportedCapabilities.push("session.launch_wrap");
|
||||
if (probe.agentCapabilities.promptCapabilities?.image) {
|
||||
supportedCapabilities.push("prompt.image");
|
||||
}
|
||||
@@ -333,6 +335,7 @@ async function openSession(
|
||||
boundarySessionId: input.sessionId,
|
||||
cwd: input.config.cwd,
|
||||
env: input.config.env,
|
||||
wrap: input.config.wrap,
|
||||
emit: state.emit,
|
||||
onRetired: () => retireSession(state, input.sessionId),
|
||||
});
|
||||
@@ -375,6 +378,7 @@ interface StartRuntimeOptions {
|
||||
boundarySessionId: string;
|
||||
cwd?: string;
|
||||
env: Readonly<Record<string, string>>;
|
||||
wrap?: readonly [string, ...string[]];
|
||||
emit(event: ProviderEvent): void;
|
||||
onRetired?: () => void;
|
||||
}
|
||||
@@ -498,6 +502,7 @@ class AcpRuntime {
|
||||
env: process.env,
|
||||
};
|
||||
child = spawnProcess(launch.command, launch.args, {
|
||||
wrap: options.wrap,
|
||||
cwd: options.cwd,
|
||||
env: { ...launch.env, ...options.env },
|
||||
stdio: "pipe",
|
||||
@@ -511,6 +516,7 @@ class AcpRuntime {
|
||||
>[1];
|
||||
stream = ndJsonStream(output, input);
|
||||
} else {
|
||||
if (options.wrap) throw new Error("An ACP connector cannot run behind a launch wrap");
|
||||
const owned = ownConnectorStream(await options.options.connector());
|
||||
stream = owned.stream;
|
||||
closeConnector = owned.close;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user