mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-30 12:16:12 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7762ce0639 | ||
|
|
10e0a4364e |
@@ -59,7 +59,7 @@ jobs:
|
||||
filters: .github/ci-paths.yml
|
||||
|
||||
- name: Validate CI contracts
|
||||
run: node --test scripts/ci-workflow.test.mjs scripts/daemon-launch-contract.test.mjs scripts/changelog-utils.test.mjs scripts/release-version-utils.test.mjs scripts/publish-release-packages.test.mjs scripts/push-current-release-tag.test.mjs scripts/reconcile-release.test.mjs scripts/sync-fdroid-changelogs.test.mjs scripts/sync-release-notes-from-changelog.test.mjs scripts/upload-release-assets.test.mjs scripts/precompress-assets.test.mjs
|
||||
run: node --test scripts/ci-workflow.test.mjs scripts/daemon-launch-contract.test.mjs scripts/changelog-utils.test.mjs scripts/release-version-utils.test.mjs scripts/publish-release-packages.test.mjs scripts/push-current-release-tag.test.mjs scripts/reconcile-release.test.mjs scripts/sync-fdroid-changelogs.test.mjs scripts/sync-release-notes-from-changelog.test.mjs scripts/upload-release-assets.test.mjs
|
||||
|
||||
quality:
|
||||
name: quality
|
||||
|
||||
@@ -55,7 +55,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 |
|
||||
|
||||
+16
-83
@@ -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
|
||||
@@ -152,7 +152,7 @@ Users can also detach an existing subagent from the subagents track. Detach is d
|
||||
|
||||
`notifyOnFinish` defaults to `true` for agent-scoped creation and prompt follow-ups because most delegated work needs to report back to the creating agent. Set it to `false` for explicit reporting or no completion callback.
|
||||
|
||||
Agent-originated messages and automatic notifications share a recipient-daemon delivery module. The daemon saves a queued message, then acknowledges it with a receipt, before provider dispatch. The module keeps one ordered queue per recipient, and the recipient reads its prompts in the order the daemon admitted them. Nothing overtakes an older queued message. A prompt takes its place when the daemon admits it, even while the provider is still starting an earlier turn, and a message stays in the queue until the turn that carries it starts. The turn has started when the agent manager acknowledges the run start; a turn that fails after that point is not delivered again.
|
||||
Agent-originated messages and automatic notifications share a recipient-daemon delivery module. A queued receipt acknowledges admission before provider dispatch. The module keeps one ordered queue per recipient, and the recipient reads its prompts in the order the daemon admitted them. Nothing overtakes an older queued message. A prompt takes its place when the daemon admits it, even while the provider is still starting an earlier turn, and a message stays in the queue until the turn that carries it starts. The turn has started when the agent manager acknowledges the run start; a turn that fails after that point is not delivered again.
|
||||
|
||||
Any sender picks `queue`, `steer`, or `interrupt` with `activeTurnBehavior`. Agent senders default to `queue`; non-agent senders (app, CLI, plugins, Hub, top-level MCP) default to `interrupt`. Each kind of prompt is released this way:
|
||||
|
||||
@@ -170,64 +170,33 @@ A command the provider accepts out of band is the one exception to admission ord
|
||||
|
||||
One provider prompt has one session mode. A batch released by a steer, an interrupt, or a person's prompt uses the latest explicit choice in it, the person's own first. Queued messages with conflicting choices keep separate ordered dispatches.
|
||||
|
||||
A provider switch can wait in the queue too (`agent.provider.switch.request` with
|
||||
`activeTurnBehavior: "queue"`). The message carries the target provider and settings, shares a prompt
|
||||
with nothing, and divides the queue: what is ahead of it goes to the current provider, and it and
|
||||
what follows go to the target. A direct prompt therefore takes along only the queued rows ahead of
|
||||
the switch. Promoting the switch cuts the running turn once the target is known to be usable. A chat
|
||||
already on the target takes the message and its settings as a plain prompt. A switch that fails keeps
|
||||
the message and holds the queue; the reason is in the daemon log.
|
||||
|
||||
The queue is saved in `$PASEO_HOME/agent-queues/` ([data model](data-model.md#directory-layout)),
|
||||
and a message is saved before its receipt is sent. Inline images are first saved as uploads, so the
|
||||
queue file holds references. An empty message is refused, and a recipient holds at most 100
|
||||
messages.
|
||||
|
||||
A message is marked `dispatching` before the provider can receive it and removed when the provider
|
||||
admits it. A dispatch that is not admitted returns the message to its place. A refused turn start
|
||||
also holds the queue: retrying by itself would be refused again and would add the prompt to the
|
||||
history each time. A message that cannot be sent is removed so that it does not block the ones
|
||||
behind it.
|
||||
|
||||
Shutdown does not send the queue. It waits only for dispatches already in flight, and everything
|
||||
else stays saved, held messages included. Closing an idle runtime keeps the queue. Archiving or
|
||||
deleting the agent clears it.
|
||||
|
||||
Bootstrap restores queues before restart recovery resumes agents, and before finish subscriptions,
|
||||
change-request watches, and ingress start. A held queue stays held. Other queues are sent, after the
|
||||
resume prompt for an agent that restart recovery resumes. A crash can leave a message marked
|
||||
`dispatching`, so the daemon looks for it in the recipient's history: a message found there is
|
||||
removed, and one not found, or whose history cannot be read, is sent again.
|
||||
|
||||
A client that retries a queued message with the same `messageId` is acknowledged again at once. The
|
||||
completed send receipt is written after dispatch, and a different request under that `messageId`
|
||||
conflicts. Completion waits cover queued admission within their original timeout and cancellation
|
||||
scope, and return at permission checkpoints and when the queue is held.
|
||||
The pending message window is in memory. Clean shutdown flushes it, held messages included, before
|
||||
closing agents; an abrupt crash can lose queued prompts. A durable send receipt remains pending until actual dispatch
|
||||
acknowledgment, so a lost window never becomes a completed receipt. Completion waits cover queued
|
||||
admission within their original timeout and cancellation scope, and return at permission
|
||||
checkpoints and when a Stop holds the queue.
|
||||
|
||||
Finish notification intent has a separate daemon-owned lifetime. The finish-subscriptions module
|
||||
persists caller, child, host, and ownership policy through an injectable store; its JSON adapter uses
|
||||
`$PASEO_HOME/finish-subscriptions.json`. Registration must commit before creation or queued-prompt
|
||||
acknowledgment promises a notification. A pending replacement retains its predecessor until dispatch
|
||||
accepts; rejected dispatch removes only the candidate. The record keeps the prompt's `messageId`, so
|
||||
withdrawing that message removes the subscription, also after a restart. Recovery coalesces
|
||||
registrations for the same caller, child, and host into one watch.
|
||||
accepts; rejected dispatch removes only the candidate. Recovery coalesces registrations for the same
|
||||
caller, child, and host into one watch.
|
||||
|
||||
Bootstrap restores these watches after repairing stale running records to `closed` and before opening
|
||||
ingress. Reading a closed child's result does not load its provider. A finish notification reports that
|
||||
the child has settled (see below); the parent decides whether its task is complete. A child chosen for restart
|
||||
recovery is observed only after its resume was sent, so the parent never hears that it was closed
|
||||
in between. A subscription whose prompt is still queued stays pending until that prompt is
|
||||
dispatched, so a held follow-up reports nothing. Archived or deleted parents suppress delivery;
|
||||
in between. Archived or deleted parents suppress delivery;
|
||||
parent-owned creation watches also stop
|
||||
reporting after detachment.
|
||||
|
||||
Intent remains stored until the parent's notification dispatch is acknowledged. Dispatch failure
|
||||
retries the captured notification; it does not change the child's reported outcome. Remote host loss
|
||||
follows the [connected-host observation policy](connected-hosts.md#delegating-agents). Shutdown stops
|
||||
observation and retains outstanding intent. A final or permission notice has an id derived from its
|
||||
subscription, so observing the same outcome again while the notice is queued adds nothing. A crash
|
||||
after successful dispatch but before removal commits can repeat the notification. This is an
|
||||
at-least-once wakeup, without turn attribution or exactly-once delivery.
|
||||
follows the [connected-host observation policy](connected-hosts.md#delegating-agents). Shutdown stops observation before flushing message delivery, retaining
|
||||
outstanding intent. A crash after successful dispatch but before removal commits can repeat the
|
||||
notification. Clean shutdown can also flush an already queued callback while retaining its intent,
|
||||
so that callback can repeat after restart. This is an at-least-once wakeup, without turn attribution or exactly-once delivery.
|
||||
|
||||
A turn end is not always a settled child. A child can end its turn with work that will start its next
|
||||
turn by itself: a running turn, queued messages, a pending provider wake-up
|
||||
@@ -308,8 +277,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.
|
||||
|
||||
@@ -405,8 +373,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
|
||||
@@ -428,39 +394,6 @@ that leaves the lifecycle at `error`, and replaces unread `finished` attention;
|
||||
agent would show the green dot or none. Subagents track marks are the exception: they follow the
|
||||
child's lifecycle, because the track is where a failed child stays visible.
|
||||
|
||||
## The queue track
|
||||
|
||||
The queue track is the list above the composer of the messages the host holds for the open agent
|
||||
(`packages/app/src/composer/queue/`). One list covers every sender, in the order the host sends
|
||||
them: your queued prompts, agent messages, finish notifications, and change-request updates.
|
||||
|
||||
The host owns the [queue](#relationships) and the app keeps no copy of it. `packages/app/src/agent-queue/`
|
||||
reads the list on mount and after each reconnect, and replaces it on each `agent.queue.update`. A
|
||||
queued message therefore survives a reload, is sent with every client closed, and shows on every
|
||||
client that views the agent. Files upload to the host before the message is queued, so any device
|
||||
can open a row's attachments.
|
||||
|
||||
Rows take these commands:
|
||||
|
||||
- **Send now** promotes the row with your send behavior setting: `steer`, otherwise `interrupt`.
|
||||
- **Edit** is offered on your own messages only. It withdraws the row, then replaces the composer
|
||||
draft with its text and attachments, and stages the row's provider switch again. If the host
|
||||
already started sending the row, the draft stays as it is.
|
||||
- **Cancel** withdraws the row.
|
||||
|
||||
A message you send directly (`steer` or `interrupt`) takes the queued rows with it, ahead of your
|
||||
text.
|
||||
|
||||
A message sent mid-turn with a staged provider switch is queued whatever the send behavior, and its
|
||||
row names the target.
|
||||
|
||||
A row the host is `dispatching` takes no command. A held queue shows a paused notice. The notice
|
||||
does not name Stop, because a refused turn start holds the queue too.
|
||||
|
||||
A host without `server_info.features.agentMessageQueue` has no queue track. The composer offers no
|
||||
Queue action there, and a `queue` send behavior sends as `steer`, so it does not cut the running
|
||||
turn.
|
||||
|
||||
## The subagents track
|
||||
|
||||
The track is a pill at the foot of an agent's pane (`packages/app/src/subagents/track.tsx`): a count you can read at a glance, and a panel behind it — a popover on wide screens, a sheet on compact ones — holding the rows. It floats over the transcript rather than sitting in a band above the composer, so the timeline scrolls underneath it; `packages/app/src/panels/agent-tracks.tsx` owns that placement, and the pill frame is shared with the task list in `packages/app/src/composer/tracks.tsx`.
|
||||
|
||||
@@ -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
-44
@@ -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,16 +53,12 @@ $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}/
|
||||
│ └── {agentId}.json # One file per agent
|
||||
├── schedules/
|
||||
│ └── {scheduleId}.json # One file per schedule
|
||||
├── agent-queues/
|
||||
│ ├── {agentId}.json # Undelivered messages for one agent; removed when empty
|
||||
│ └── {agentId}.json.corrupt.{ms} # Unreadable queue file, set aside at startup
|
||||
├── projects/
|
||||
│ ├── projects.json # Project registry
|
||||
│ ├── workspaces.json # Workspace registry
|
||||
@@ -185,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`
|
||||
|
||||
@@ -523,8 +523,6 @@ Measured bundle size for a standard Expo web export:
|
||||
- gzip: 2.55 MiB
|
||||
- brotli: 1.93 MiB
|
||||
|
||||
`npm run build:desktop` runs the same `scripts/precompress-assets.mjs` over `packages/app/dist` before electron-builder copies it to `app-dist`, so the desktop-served UI also gets `.br`/`.gz` siblings.
|
||||
|
||||
The desktop-managed daemon disables the bundled web UI by default (`PASEO_WEB_UI_ENABLED=false`) because the desktop app already ships the renderer as `app-dist`. Shipping the same assets again inside `@getpaseo/server` would duplicate the ~10.8 MiB install. Desktop packaging also excludes `node_modules/@getpaseo/server/dist/server/web-ui/**` from the packaged app.
|
||||
|
||||
## Built workspace packages
|
||||
|
||||
@@ -36,10 +36,6 @@ ordinary `WorkspaceTab` (`SheetTab` in the store) and is an `IsolatedBottomSheet
|
||||
other sheet in the app, so it sits on the one app-wide stack: a sheet opened from any sheet lands on
|
||||
top of it, and closing the top sheet (drag, Close, backdrop, or Android Back) uncovers the one below.
|
||||
|
||||
Because that stack is app-wide and hidden workspace screens stay mounted, a sheet is not presented
|
||||
until its workspace has been on screen. A target opened in a workspace before the user gets there
|
||||
waits in the store and appears on arrival.
|
||||
|
||||
A subagent chosen from the subagents list is the exception. It opens as a page of the list's own
|
||||
sheet and replaces the list in place: Back returns to the list, Close ends both, and Open parent
|
||||
closes the list, landing on the pane the list was opened from. The store's `selectSheetTab` describes
|
||||
|
||||
+4
-11
@@ -447,17 +447,10 @@ wide layouts keep local geometry. That export is
|
||||
what `patches/@gorhom+bottom-sheet+*.patch` adds.
|
||||
|
||||
A sheet whose owner may veto the close (unsaved work) passes `enableDismissOnClose={false}`. Every
|
||||
close path then parks the sheet at index -1 with its content mounted; the owner runs its guard and
|
||||
either snaps back to 0 or drops its state, which unmounts the sheet and takes it off the stack.
|
||||
Calling `dismiss()` on such a sheet bypasses the guard and unmounts it, so its backdrop and Back
|
||||
press call `close()`.
|
||||
|
||||
Run that guard from the wrapper's `onClosed`. Gorhom only calls `onChange` when a close ends at a
|
||||
different index than the one it already recorded, and an interrupted mount animation leaves that
|
||||
record at -1, so the close that follows is invisible: the sheet parks with its backdrop still over
|
||||
the app, and every tap in the covered area is lost. `onClosed` watches the close animation settle at
|
||||
the closed detent and reports it either way. Keeping `onChange` as well is harmless as long as the
|
||||
guard is idempotent.
|
||||
close path then parks the sheet at index -1 with its content mounted; the owner hears
|
||||
`onChange(-1)`, runs its guard, and either snaps back to 0 or drops its state, which unmounts the
|
||||
sheet and takes it off the stack. Calling `dismiss()` on such a sheet bypasses the guard and
|
||||
unmounts it, so its backdrop and Back press call `close()`.
|
||||
|
||||
The wrapper must give Gorhom an object ref. Gorhom accepts a callback ref at the React boundary
|
||||
but stores it in the modal queue and later reads `.current`; provider dismissal, replacement,
|
||||
|
||||
+2
-2
@@ -57,8 +57,8 @@ Authoritative terminology. UI label wins. Don't invent synonyms; use what's here
|
||||
- **Composer toolbar** — The bottom control row inside the composer input. Contains agent controls, attachment button, voice controls, and stop/send controls. Code: `leftContent`, `beforeVoiceContent`, and `rightContent` slots in `MessageInput` (`packages/app/src/composer/input/input.tsx`). Forbidden: "Status bar".
|
||||
- **Agent controls** — Provider, model, mode, thinking, and provider-feature controls for an agent or draft agent. Code: `AgentControls` / `DraftAgentControls` (`packages/app/src/composer/agent-controls/index.tsx`). Forbidden: "Agent status bar".
|
||||
- **Composer footer** — Optional area rendered below the composer input but still inside the keyboard-shifted composer layout. Code: `Composer.footer` (`packages/app/src/composer/index.tsx`).
|
||||
- **Composer track** — A contextual lane at the foot of a pane, by the composer input. Specific tracks use the `<thing> track` form: **Queue track**, **Subagents track**, **Tasks track**. The subagents and tasks tracks are pills floating over the transcript, each opening a panel with its rows; the [queue track](agent-lifecycle.md#the-queue-track) is a lane inside the composer itself. Code: `ComposerQueueTrack` (`packages/app/src/composer/queue/track.tsx`), pill and panel frame in `packages/app/src/composer/tracks.tsx`, `SubagentsTrack` (`packages/app/src/subagents/track.tsx`), `AgentTaskList` (`packages/app/src/composer/task-list/index.tsx`).
|
||||
- **Steer** — A follow-up admitted into an agent's already-running turn instead of interrupting it. Interrupting the turn discards steers the provider has not read yet; there is no take-back short of that, and no provider offers one. The stop button and Escape both interrupt. A steer the provider never read keeps its transcript row, matching Codex. Sending while the agent waits on a permission denies that request first, so the message reaches the same turn instead of stalling behind it. UI: "Send and steer". Code: `steerActiveTurn` (`packages/server/src/server/agent/agent-sdk-types.ts`). Don't confuse with **Queue track**, which lists the messages the host holds until the turn ends. A queued message does not enter the running turn. An agent sender's `activeTurnBehavior: "steer"` (CLI `--behavior steer`) means the same as a person's steer. Agent senders default to `queue` instead: the daemon holds the message until the running turn ends, as it does for a person's queued message. Forbidden: "Delivery", "Queued prompt".
|
||||
- **Composer track** — A contextual lane at the foot of a pane, by the composer input. Specific tracks use the `<thing> track` form: **Queue track**, **Subagents track**, **Tasks track**. The subagents and tasks tracks are pills floating over the transcript, each opening a panel with its rows; the queue track is a lane inside the composer itself. Code: queue track inside `Composer` (`packages/app/src/composer/index.tsx`), pill and panel frame in `packages/app/src/composer/tracks.tsx`, `SubagentsTrack` (`packages/app/src/subagents/track.tsx`), `AgentTaskList` (`packages/app/src/composer/task-list/index.tsx`).
|
||||
- **Steer** — A follow-up admitted into an agent's already-running turn instead of interrupting it. Interrupting the turn discards steers the provider has not read yet; there is no take-back short of that, and no provider offers one. The stop button and Escape both interrupt. A steer the provider never read keeps its transcript row, matching Codex. Sending while the agent waits on a permission denies that request first, so the message reaches the same turn instead of stalling behind it. UI: "Send and steer". Code: `steerActiveTurn` (`packages/server/src/server/agent/agent-sdk-types.ts`). Don't confuse with **Queue track**, which holds messages client-side until the turn ends and never enters the running turn. An agent sender's `activeTurnBehavior: "steer"` (CLI `--behavior steer`) means the same as a person's steer. Agent senders default to `queue` instead: the daemon holds the message until the running turn ends, as the queue track does for a person. Forbidden: "Delivery", "Queued prompt".
|
||||
- **Subagent** — User-facing term for an agent session related to a parent agent session. Use **subagents** in UI copy and docs. Internal daemon/provider plumbing may say "child agent" or `child_session`, especially for provider-managed imports; do not surface "child agent" as a product term.
|
||||
- **Attachment tray** — The selected-attachments row inside the composer input, above the text input. Code: `renderAttachmentTray` (`packages/app/src/composer/index.tsx`). Forbidden: "Attachment bar".
|
||||
- **Fork** — Starting a NEW agent session seeded with a copy of another session's curated chat history. The history rides along as a `chat_history` composer attachment on a draft; the fork does **not** resume or branch the provider-side session, and the source session keeps running untouched. Two targets, one surface, one RPC (`agent.fork_context`, gated on the `agentForkContext` host feature). UI: the fork menu lives in the assistant turn footer and offers "Fork in a new tab" / "Fork in a new workspace". On a **completed** turn it sits beside the copy button and pins a boundary to that turn, so the fork stops where the turn ended. On the **in-flight** turn it sits beside the progress loader and elapsed timer, and omits the boundary entirely — `selectForkContextRows` projects the whole timeline when no boundary is given, so the fork captures everything **up to now**, including the response still streaming. That omission is what makes mid-run forking work; pinning a boundary there would silently drop the live response. Forbidden on provider-subagent (read-only) panes. Code: `useForkAgent` (`packages/app/src/hooks/use-fork-agent.ts`), `selectForkContextRows` (`packages/server/src/server/agent/activity-curator.ts`). Don't confuse with: git fork (unrelated; Paseo has no such concept), **Worktree** (filesystem isolation, not history copying).
|
||||
|
||||
+2
-6
@@ -267,10 +267,6 @@ Plugin UI runs on desktop and mobile across multiple themes: color every `Text`
|
||||
`theme.colors.foreground` or `theme.colors.foregroundMuted`, and size layout from `layout.compact`.
|
||||
See `public-docs/plugins/reference.md`.
|
||||
|
||||
A plugin reads and arranges panes and tabs through `PluginWorkspaceLayout`. Its host,
|
||||
`packages/app/src/plugins/workspace-layout/`, is a facade over the layout store and `workspace-tabs`,
|
||||
so add behavior to those owners and keep layout mechanics out of the SDK types.
|
||||
|
||||
### SDK import boundaries
|
||||
|
||||
Classify every SDK export before adding it. All client entry points and implementations live under
|
||||
@@ -1022,8 +1018,8 @@ payload that cannot be rendered intact. The daemon advertises this RPC through
|
||||
|
||||
`addSlashCommand` registers an agent- or workspace-context command in the composer. The
|
||||
callback runs in the app, receives the trimmed text after the command name as `args`, and receives
|
||||
the same `paseo`, `rpc`, `openScreen`, workspace, agent, and `workspaceLayout` capabilities as the
|
||||
matching Command Center callback.
|
||||
the same `paseo`, `rpc`, `openScreen`, workspace, agent, and `openPanel` capabilities as the matching
|
||||
Command Center callback.
|
||||
|
||||
```ts
|
||||
client.addSlashCommand({
|
||||
|
||||
+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:
|
||||
@@ -211,7 +173,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.
|
||||
|
||||
@@ -224,24 +186,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
|
||||
@@ -435,7 +379,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.
|
||||
@@ -451,7 +395,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-ZVIrRfb7oyTwx7kz6F51hs/ctT45qUdZM4v0QRLW9zA=
|
||||
sha256-34bUBmRmjekbUSp93597GLTmSWKt23TCHaK3ViXG+iU=
|
||||
|
||||
Generated
+1
-20
@@ -46,9 +46,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": {
|
||||
@@ -39724,9 +39721,6 @@
|
||||
"typescript": "^5.2.2",
|
||||
"vitest": "^4.1.6",
|
||||
"zx": "^8.8.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.16.0"
|
||||
}
|
||||
},
|
||||
"packages/cli/node_modules/@vitest/expect": {
|
||||
@@ -40655,7 +40649,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",
|
||||
@@ -40663,9 +40657,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": {
|
||||
@@ -41113,16 +41104,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",
|
||||
|
||||
+1
-4
@@ -99,7 +99,7 @@
|
||||
"web": "npm run web --workspace=@getpaseo/app",
|
||||
"dev:desktop": "cross-env PASEO_LISTEN=127.0.0.1:6768 npm run dev --workspace=@getpaseo/desktop",
|
||||
"dev:win:desktop": "npm run dev:win --workspace=@getpaseo/desktop",
|
||||
"build:desktop": "npm run build:app-deps:clean && cd packages/app && cross-env PASEO_WEB_PLATFORM=electron npx expo export --platform web && cd ../.. && node scripts/precompress-assets.mjs packages/app/dist && npm run build --workspace=@getpaseo/desktop --",
|
||||
"build:desktop": "npm run build:app-deps:clean && cd packages/app && cross-env PASEO_WEB_PLATFORM=electron npx expo export --platform web && cd ../.. && npm run build --workspace=@getpaseo/desktop --",
|
||||
"db:query": "npm run db:query --workspace=@getpaseo/server --",
|
||||
"cli": "./scripts/dev-home.sh npx tsx packages/cli/src/index.js",
|
||||
"version": "npm run version:sync-internal && npm run fdroid:changelogs && npm run release:prepare && git add -A",
|
||||
@@ -172,8 +172,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,98 +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 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,
|
||||
@@ -155,91 +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 rewound conversation", async () => {
|
||||
await reloadAgentFromTabMenu(page, agent.agentId);
|
||||
await expectToast(page, "Reloaded agent");
|
||||
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 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();
|
||||
}
|
||||
|
||||
@@ -18,7 +18,6 @@ import {
|
||||
expectComposerVisible,
|
||||
cancelAgent,
|
||||
composerLocator,
|
||||
configureComposerInterruptSend,
|
||||
expectQueuedMessageButton,
|
||||
fillComposerDraft,
|
||||
holdSendButton,
|
||||
@@ -405,6 +404,15 @@ async function queueMessage(page: Page, prompt: string): Promise<void> {
|
||||
await sendDraftToQueue(page);
|
||||
}
|
||||
|
||||
async function expectQueuedSendFailuresRestored(page: Page, prompts: string[]): Promise<void> {
|
||||
await expect(page.getByRole("button", { name: "Send queued message now" })).toHaveCount(
|
||||
prompts.length,
|
||||
);
|
||||
for (const prompt of prompts) {
|
||||
await expect(page.getByTestId("user-message").filter({ hasText: prompt })).toHaveCount(0);
|
||||
}
|
||||
}
|
||||
|
||||
async function expectFailedSubmissionRestored(page: Page, prompt: string): Promise<void> {
|
||||
await expectComposerDraft(page, prompt);
|
||||
await expectComposerEditable(page);
|
||||
@@ -423,14 +431,14 @@ async function expectInterruptedTurnOrderAfterReconnect(
|
||||
});
|
||||
const prompt = "Keep this prompt before its response.";
|
||||
try {
|
||||
await configureComposerInterruptSend(page);
|
||||
await openAgentRoute(page, { workspaceId: agent.workspaceId, agentId: agent.agentId });
|
||||
await expectComposerVisible(page);
|
||||
await agent.client.sendAgentMessage(agent.agentId, "Start the turn that will be interrupted.");
|
||||
await expect(page.getByRole("button", { name: /stop|cancel/i }).first()).toBeVisible();
|
||||
await expect(page.getByText("Cycle 1", { exact: true })).toBeVisible();
|
||||
await queueMessage(page, prompt);
|
||||
gate.setAgentStreamSuppressed(true);
|
||||
await submitMessage(page, prompt);
|
||||
await page.getByRole("button", { name: "Send queued message now" }).click();
|
||||
const promptRow = page.getByTestId("user-message").filter({ hasText: prompt });
|
||||
await expect(promptRow).toBeVisible();
|
||||
await gate.waitForServerMessage("send_agent_message_response");
|
||||
@@ -651,14 +659,14 @@ async function expectLegacyAssistantStartsAfterInterruptedPrompt(
|
||||
});
|
||||
const prompt = "Start the replacement answer after this prompt.";
|
||||
try {
|
||||
await configureComposerInterruptSend(page);
|
||||
await openAgentRoute(page, { workspaceId: agent.workspaceId, agentId: agent.agentId });
|
||||
await expectComposerVisible(page);
|
||||
await agent.client.sendAgentMessage(agent.agentId, "Start the interrupted answer.");
|
||||
await expect(page.getByText("Cycle 1", { exact: true })).toBeVisible();
|
||||
await queueMessage(page, prompt);
|
||||
gate.setAssistantMessageIdsStripped(true);
|
||||
gate.setAgentStreamEventSuppressed("turn_canceled", true);
|
||||
await submitMessage(page, prompt);
|
||||
await page.getByRole("button", { name: "Send queued message now" }).click();
|
||||
const promptRow = page.getByTestId("user-message").filter({ hasText: prompt });
|
||||
const replacementAnswer = page.getByText("(end of synthetic stream)", { exact: true }).last();
|
||||
await expect(promptRow).toBeVisible();
|
||||
@@ -1090,7 +1098,6 @@ test.describe("Agent message submission", () => {
|
||||
gate.holdNextServerMessage("cancel_agent_response");
|
||||
await page.getByRole("button", { name: "Stop agent", exact: true }).click();
|
||||
await gate.waitForHeldServerMessage();
|
||||
await page.getByRole("button", { name: "Send queued message now" }).click();
|
||||
|
||||
await expect(page.getByTestId("user-message").filter({ hasText: secondPrompt })).toHaveCount(
|
||||
1,
|
||||
@@ -1336,8 +1343,6 @@ test.describe("Agent message submission", () => {
|
||||
await test.step("holding Send queues the draft", async () => {
|
||||
await fillComposerDraft(page, queuedPrompt);
|
||||
await holdSendButton(page, "Send and steer");
|
||||
expect((await gate.waitForRequest()).activeTurnBehavior).toBe("queue");
|
||||
gate.accept();
|
||||
await expectQueuedMessageButton(page);
|
||||
await expectComposerDraft(page, "");
|
||||
await expectAgentReadyToInterrupt(page);
|
||||
@@ -1346,22 +1351,19 @@ test.describe("Agent message submission", () => {
|
||||
).toHaveCount(0);
|
||||
});
|
||||
|
||||
await test.step("tapping Send still steers and takes the queued row along", async () => {
|
||||
await test.step("tapping Send still steers", async () => {
|
||||
const steeredPrompt = "Steer this turn with a tap.";
|
||||
await fillComposerDraft(page, steeredPrompt);
|
||||
await page.getByRole("button", { name: "Send and steer", exact: true }).click();
|
||||
|
||||
const request = await gate.waitForRequest(2);
|
||||
const request = await gate.waitForRequest();
|
||||
expect(request.text).toBe(steeredPrompt);
|
||||
expect(request.activeTurnBehavior).toBe("steer");
|
||||
gate.accept(1);
|
||||
gate.accept();
|
||||
await expect(
|
||||
page.getByTestId("user-message").filter({ hasText: steeredPrompt }),
|
||||
).toHaveCount(1);
|
||||
await expect(page.getByRole("button", { name: "Send queued message now" })).toHaveCount(0);
|
||||
await expect(
|
||||
page.getByTestId("user-message").filter({ hasText: queuedPrompt }),
|
||||
).toHaveCount(1);
|
||||
await expectQueuedMessageButton(page);
|
||||
});
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
@@ -1378,21 +1380,26 @@ test.describe("Agent message submission", () => {
|
||||
await replaySteeredSleepTurnInBrowser(page, testInfo, "codex");
|
||||
});
|
||||
|
||||
test("restores the draft when queueing loses the connection", async ({ page }, testInfo) => {
|
||||
test("restores overlapping queued sends when their connection fails", async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
test.setTimeout(120_000);
|
||||
const gate = await gateNextAgentMessage(page);
|
||||
const agent = await startRunningMockAgent(page, {
|
||||
prefix: `queue-connection-lost-${testInfo.workerIndex}-`,
|
||||
prefix: `overlapping-queued-send-${testInfo.workerIndex}-`,
|
||||
model: "one-minute-stream",
|
||||
prompt: "Keep the agent running while a message queues.",
|
||||
prompt: "Keep the agent running while messages queue.",
|
||||
});
|
||||
const prompt = "Keep this draft if queueing fails.";
|
||||
const prompts = ["Restore the first queued send.", "Restore the second queued send."];
|
||||
try {
|
||||
await fillComposerDraft(page, prompt);
|
||||
await sendDraftToQueue(page);
|
||||
await gate.waitForRequest();
|
||||
await queueMessage(page, prompts[0]);
|
||||
await queueMessage(page, prompts[1]);
|
||||
await page.getByRole("button", { name: "Send queued message now" }).first().click();
|
||||
await gate.waitForRequest(1);
|
||||
await page.getByRole("button", { name: "Send queued message now" }).first().click();
|
||||
await gate.waitForRequest(2);
|
||||
await gate.disconnect();
|
||||
await expectFailedSubmissionRestored(page, prompt);
|
||||
await expectQueuedSendFailuresRestored(page, prompts);
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
|
||||
@@ -44,26 +44,6 @@ const PROFILE = {
|
||||
|
||||
const PROFILE_SUMMARY = "Mock Load Test · One minute stream · Approval test";
|
||||
|
||||
// Isolate this suite to the sole mock provider so it tests single-provider picker
|
||||
// behavior deterministically regardless of which CLIs are installed on the host.
|
||||
test.use({
|
||||
e2eDaemonConfig: {
|
||||
version: 1,
|
||||
agents: {
|
||||
providers: {
|
||||
claude: { enabled: false },
|
||||
codex: { enabled: false },
|
||||
copilot: { enabled: false },
|
||||
opencode: { enabled: false },
|
||||
pi: { enabled: false },
|
||||
omp: { enabled: false },
|
||||
antigravity: { enabled: false },
|
||||
hoplite: { enabled: false },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
test.describe("Agent profiles in the model picker", () => {
|
||||
test("an empty host still exposes agent profile settings from the picker", async ({ page }) => {
|
||||
const seed = await seedAgentProfiles([]);
|
||||
@@ -88,8 +68,8 @@ test.describe("Agent profiles in the model picker", () => {
|
||||
page,
|
||||
}) => {
|
||||
const seed = await seedAgentProfiles([PROFILE]);
|
||||
// With only the mock provider enabled on this host, the picker opens
|
||||
// directly into its models and shows its pinned profile.
|
||||
// A live agent is one provider's process, so the profile has to name that
|
||||
// same provider or the picker will not offer it at all.
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "agent-profiles-picker-",
|
||||
title: "Agent profiles picker",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { expect, test, type Page } from "../support/fixtures";
|
||||
import { expect, test } from "../support/fixtures";
|
||||
import { expectComposerVisible } from "../support/helpers/composer";
|
||||
import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate";
|
||||
import { installLocalDesktopHost } from "../support/helpers/local-desktop-host";
|
||||
@@ -282,63 +282,3 @@ test("compact opens files and subagents in a sheet, leaving the tabs for agents"
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
async function openFileAndDismissDuringAnimation(page: Page) {
|
||||
const fileLink = page.getByText(FILE_LINK, { exact: true });
|
||||
await expect(fileLink).toBeVisible({ timeout: 15_000 });
|
||||
|
||||
// Check and press in the same browser frame so automation cannot outlast the opening animation.
|
||||
await fileLink.evaluate((link) => {
|
||||
if (!(link instanceof HTMLElement)) throw new Error("Expected an HTML file link");
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const timeout = window.setTimeout(() => {
|
||||
cancelAnimationFrame(frame);
|
||||
reject(new Error("The file sheet did not pass through the opening position"));
|
||||
}, 5_000);
|
||||
const dismissDuringOpening = () => {
|
||||
const header = document.querySelector('[data-testid="sheet-tab-header"]');
|
||||
const top = header?.getBoundingClientRect().top ?? window.innerHeight;
|
||||
const pressTarget = document.elementFromPoint(10, 10);
|
||||
if (
|
||||
top > window.innerHeight / 2 &&
|
||||
top < window.innerHeight &&
|
||||
pressTarget instanceof HTMLElement &&
|
||||
pressTarget.getAttribute("aria-label") === "Bottom sheet backdrop"
|
||||
) {
|
||||
window.clearTimeout(timeout);
|
||||
pressTarget.click();
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
frame = requestAnimationFrame(dismissDuringOpening);
|
||||
};
|
||||
let frame = requestAnimationFrame(dismissDuringOpening);
|
||||
link.click();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
test("a sheet dismissed while it is still opening closes its tab", async ({ page }) => {
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "compact-sheet-opening-dismiss-",
|
||||
title: "Sheet parent",
|
||||
initialPrompt: promptMentioning(FILE_LINK),
|
||||
});
|
||||
try {
|
||||
await writeFile(path.join(workspace.cwd, "linked.ts"), "one\ntwo\nthree\n", "utf8");
|
||||
await openAgentRoute(page, { workspaceId: workspace.workspaceId, agentId: workspace.agentId });
|
||||
|
||||
await openFileAndDismissDuringAnimation(page);
|
||||
|
||||
await expectNoSheetOpen(page);
|
||||
await expectOpenTabCount(page, 1);
|
||||
await page
|
||||
.getByRole("button", { name: /Switch tabs/ })
|
||||
.filter({ visible: true })
|
||||
.click();
|
||||
await expect(page.getByText("Workspace tabs", { exact: true })).toBeVisible();
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,288 +0,0 @@
|
||||
import { expect, test } from "../support/fixtures";
|
||||
import { expectAgentIdle } from "../support/helpers/agent-stream";
|
||||
import {
|
||||
attachComposerTestImage,
|
||||
cancelAgent,
|
||||
composerLocator,
|
||||
expectAttachmentPill,
|
||||
expectComposerDraft,
|
||||
expectComposerVisible,
|
||||
fillComposerDraft,
|
||||
sendDraftToQueue,
|
||||
} from "../support/helpers/composer";
|
||||
import {
|
||||
cancelQueuedMessage,
|
||||
editQueuedMessage,
|
||||
expectDeliveredImage,
|
||||
expectComposerOnScreen,
|
||||
expectDeliveredOnce,
|
||||
expectSenderIconUnsquashed,
|
||||
openSecondClient,
|
||||
queuedRow,
|
||||
queuedRows,
|
||||
queueMessage,
|
||||
queuePausedNotice,
|
||||
queueThroughHost,
|
||||
reopenAgent,
|
||||
scrollQueueFrom,
|
||||
seedAgentWithOpenTurn,
|
||||
sendQueuedMessageNow,
|
||||
} from "../support/helpers/composer-queue";
|
||||
import { openAgentRoute } from "../support/helpers/mock-agent";
|
||||
|
||||
test.describe("Composer queue", () => {
|
||||
test("a queued image prompt can be edited, survives a reload, and is delivered once", async ({
|
||||
page,
|
||||
}) => {
|
||||
const prompt = "Describe this screenshot.";
|
||||
const revised = "Describe this screenshot in one line.";
|
||||
const agent = await seedAgentWithOpenTurn({ repoPrefix: "queue-edit-", title: "Queue edit" });
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
|
||||
await test.step("queue a prompt with an image", async () => {
|
||||
await attachComposerTestImage(page);
|
||||
await expectAttachmentPill(page, "composer-image-attachment-pill");
|
||||
await queueMessage(page, prompt);
|
||||
await expect(queuedRow(page, prompt)).toContainText("1 attachment");
|
||||
});
|
||||
|
||||
await test.step("Edit takes the text and image back into the composer", async () => {
|
||||
await editQueuedMessage(page, prompt);
|
||||
await expect(queuedRows(page)).toHaveCount(0);
|
||||
await expectComposerDraft(page, prompt);
|
||||
await expectAttachmentPill(page, "composer-image-attachment-pill");
|
||||
await expect(composerLocator(page)).toBeFocused();
|
||||
});
|
||||
|
||||
await test.step("queue the revised prompt with the same image", async () => {
|
||||
await queueMessage(page, revised);
|
||||
await expect(queuedRow(page, revised)).toContainText("1 attachment");
|
||||
});
|
||||
|
||||
await test.step("the row is still there after a reload", async () => {
|
||||
await page.reload();
|
||||
await expect(queuedRow(page, revised)).toBeVisible({ timeout: 30_000 });
|
||||
await expect(queuedRows(page)).toHaveCount(1);
|
||||
});
|
||||
|
||||
await test.step("the prompt is delivered once when the turn ends", async () => {
|
||||
await agent.finishTurn();
|
||||
await expectDeliveredOnce(page, revised);
|
||||
await expectDeliveredImage(page, revised);
|
||||
await expect(queuedRows(page)).toHaveCount(0);
|
||||
});
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("Stop pauses the queue until the user sends a row", async ({ page }) => {
|
||||
const prompt = "Run after I say so.";
|
||||
const agent = await seedAgentWithOpenTurn({ repoPrefix: "queue-held-", title: "Queue held" });
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
await queueMessage(page, prompt);
|
||||
await expect(queuePausedNotice(page)).toHaveCount(0);
|
||||
|
||||
await cancelAgent(page);
|
||||
|
||||
await expectAgentIdle(page);
|
||||
await expect(queuePausedNotice(page)).toBeVisible();
|
||||
await expect(queuedRow(page, prompt)).toBeVisible();
|
||||
|
||||
await sendQueuedMessageNow(page, prompt);
|
||||
|
||||
await expectDeliveredOnce(page, prompt);
|
||||
await expect(queuePausedNotice(page)).toHaveCount(0);
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("the host delivers a queued prompt with every client closed", async ({ page }) => {
|
||||
const prompt = "Continue while I am away.";
|
||||
const agent = await seedAgentWithOpenTurn({
|
||||
repoPrefix: "queue-closed-",
|
||||
title: "Queue closed",
|
||||
});
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
await queueMessage(page, prompt);
|
||||
|
||||
await page.close();
|
||||
await agent.finishTurn();
|
||||
await agent.client.waitForFinish(agent.agentId, 30_000);
|
||||
const reopened = await reopenAgent(page, agent);
|
||||
|
||||
await expectDeliveredOnce(reopened, prompt);
|
||||
await expect(queuedRows(reopened)).toHaveCount(0);
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("two clients share one queue", async ({ browser, page }) => {
|
||||
const unwanted = "Do not run this one.";
|
||||
const urgent = "Run this one now.";
|
||||
const agent = await seedAgentWithOpenTurn({ repoPrefix: "queue-sync-", title: "Queue sync" });
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
const second = await openSecondClient(browser, page, agent);
|
||||
try {
|
||||
await expectComposerVisible(second.page);
|
||||
|
||||
await test.step("a row queued on one client appears on the other", async () => {
|
||||
await queueMessage(page, unwanted);
|
||||
await expect(queuedRow(second.page, unwanted)).toBeVisible();
|
||||
await fillComposerDraft(second.page, urgent);
|
||||
await sendDraftToQueue(second.page);
|
||||
await expect(queuedRows(page)).toContainText([unwanted, urgent]);
|
||||
});
|
||||
|
||||
await test.step("Cancel on one client removes the row on the other", async () => {
|
||||
await cancelQueuedMessage(second.page, unwanted);
|
||||
await expect(queuedRow(page, unwanted)).toHaveCount(0);
|
||||
});
|
||||
|
||||
await test.step("Send now on one client updates the other", async () => {
|
||||
await sendQueuedMessageNow(page, urgent);
|
||||
await expectDeliveredOnce(second.page, urgent);
|
||||
await expect(
|
||||
second.page.getByTestId("user-message").filter({ hasText: unwanted }),
|
||||
).toHaveCount(0);
|
||||
});
|
||||
} finally {
|
||||
await second.close();
|
||||
}
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("a long queue scrolls without pushing the composer off screen", async ({ page }) => {
|
||||
const texts = Array.from({ length: 20 }, (_, index) => `Queued update ${index + 1}.`);
|
||||
const first = "Queued update 1.";
|
||||
const last = "Queued update 20.";
|
||||
const agent = await seedAgentWithOpenTurn({ repoPrefix: "queue-long-", title: "Queue long" });
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
await queueThroughHost(agent, texts);
|
||||
await expect(queuedRows(page)).toHaveCount(20);
|
||||
|
||||
for (const viewport of [
|
||||
{ width: 1280, height: 800 },
|
||||
{ width: 390, height: 844 },
|
||||
// A phone with its keyboard open.
|
||||
{ width: 390, height: 500 },
|
||||
]) {
|
||||
await test.step(`${viewport.width}x${viewport.height}`, async () => {
|
||||
await page.setViewportSize(viewport);
|
||||
await expect(queuedRow(page, first)).toBeVisible();
|
||||
await expectComposerOnScreen(page);
|
||||
|
||||
await scrollQueueFrom(page, first, 5000);
|
||||
// Scrolled to the end, a fractional frame height can clip a sub-pixel of the row.
|
||||
await expect(queuedRow(page, last)).toBeInViewport({ ratio: 0.99 });
|
||||
await expectComposerOnScreen(page);
|
||||
|
||||
await scrollQueueFrom(page, last, -5000);
|
||||
await expect(queuedRow(page, first)).toBeInViewport({ ratio: 1 });
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("a message queued by another agent can be cancelled but not edited", async ({ page }) => {
|
||||
const message = "The release notes are ready for review.";
|
||||
const agent = await seedAgentWithOpenTurn({
|
||||
repoPrefix: "queue-sender-",
|
||||
title: "Queue recipient",
|
||||
});
|
||||
try {
|
||||
const sender = await agent.client.createAgent({
|
||||
provider: "mock",
|
||||
cwd: agent.cwd,
|
||||
workspaceId: agent.workspaceId,
|
||||
title: "Release coordination and changelog verification helper for the mobile team",
|
||||
model: "e2e-fast-stream",
|
||||
});
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
|
||||
await agent.client.sendAgentMessage(agent.agentId, message, {
|
||||
sourceAgentId: sender.id,
|
||||
activeTurnBehavior: "queue",
|
||||
});
|
||||
|
||||
const row = queuedRow(page, message);
|
||||
await expect(row).toContainText("Sent by Release coordination");
|
||||
await expect(row.getByRole("button", { name: "Send queued message now" })).toBeEnabled();
|
||||
await expect(row.getByRole("button", { name: "Cancel queued message" })).toBeEnabled();
|
||||
await expect(row.getByRole("button", { name: "Edit queued message" })).toHaveCount(0);
|
||||
|
||||
await test.step("a long sender name truncates without squashing its icon", async () => {
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await expect(row).toBeInViewport();
|
||||
await expectSenderIconUnsquashed(row);
|
||||
});
|
||||
|
||||
await cancelQueuedMessage(page, message);
|
||||
|
||||
await expect(queuedRows(page)).toHaveCount(0);
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("editing a queued image prompt on a short phone viewport keeps remaining queued rows visible", async ({
|
||||
page,
|
||||
}) => {
|
||||
const withImage = "Describe this screenshot.";
|
||||
const remaining = Array.from({ length: 4 }, (_, index) => `Remaining update ${index + 1}.`);
|
||||
const agent = await seedAgentWithOpenTurn({
|
||||
repoPrefix: "queue-compact-edit-",
|
||||
title: "Queue compact edit",
|
||||
});
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
|
||||
await attachComposerTestImage(page);
|
||||
await expectAttachmentPill(page, "composer-image-attachment-pill");
|
||||
await queueMessage(page, withImage);
|
||||
await queueThroughHost(agent, remaining);
|
||||
await expect(queuedRows(page)).toHaveCount(5);
|
||||
|
||||
await page.setViewportSize({ width: 390, height: 500 });
|
||||
await editQueuedMessage(page, withImage);
|
||||
await expectComposerDraft(page, withImage);
|
||||
await expectAttachmentPill(page, "composer-image-attachment-pill");
|
||||
await expect(composerLocator(page)).toBeInViewport({ ratio: 1 });
|
||||
await expect(
|
||||
page.getByRole("button", { name: "Send and steer", exact: true }),
|
||||
).toBeInViewport({
|
||||
ratio: 1,
|
||||
});
|
||||
|
||||
// The queue scroll viewport must keep a readable slice (>= 90px) above the restored image pill,
|
||||
// not collapse to a sliver inside a 0.6*viewport slot clamp.
|
||||
const scrollFrameHeight = await page
|
||||
.getByRole("list", { name: "Queued messages" })
|
||||
.evaluate((list) => {
|
||||
const scrollView = list.parentElement?.parentElement;
|
||||
return scrollView ? scrollView.getBoundingClientRect().height : 0;
|
||||
});
|
||||
expect(scrollFrameHeight).toBeGreaterThanOrEqual(90);
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,324 +0,0 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import type { Locator } from "@playwright/test";
|
||||
import { expect, test, type Page } from "../support/fixtures";
|
||||
import { openCommandCenter } from "../support/helpers/command-center";
|
||||
import { runWorkspaceActionFromCommandCenter } from "../support/helpers/command-center-workspace-actions";
|
||||
import { submitMessageWithButton } from "../support/helpers/composer";
|
||||
import { openFileExplorer, openFileFromExplorer } from "../support/helpers/file-explorer";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
|
||||
import { copyPluginExample } from "../support/helpers/plugin-fixture";
|
||||
import { runCommand } from "../support/helpers/plugin-sidebar-items";
|
||||
import {
|
||||
closeSheet,
|
||||
expectNoSheetOpen,
|
||||
expectOneSheetOpen,
|
||||
promptMentioning,
|
||||
sheet,
|
||||
} from "../support/helpers/sheet";
|
||||
import {
|
||||
closeMobileExplorer,
|
||||
expectMobileExplorerHidden,
|
||||
expectMobileExplorerVisible,
|
||||
openMobileAgentSidebar,
|
||||
selectWorkspaceInSidebar,
|
||||
} from "../support/helpers/sidebar";
|
||||
import { getServerId } from "../support/helpers/server-id";
|
||||
|
||||
const WIDE = { width: 1600, height: 900 };
|
||||
const COMPACT = { width: 390, height: 844 };
|
||||
const AGENT_TITLE = "Layout agent";
|
||||
const FILE_LINK = "README.md:1";
|
||||
const NO_FILE = "Focus a file to see its outline";
|
||||
|
||||
const REPO_FILES = [
|
||||
{ path: "README.md", content: "# Guide\n\n## Install\n" },
|
||||
{ path: "notes.md", content: "# Notes\n\n## Open questions\n" },
|
||||
{ path: "src/app.ts", content: "// TODO: handle errors\nexport const ready = true;\n" },
|
||||
];
|
||||
|
||||
const REVIEW_TAB = "workspace-tab-plugin_agent_16_workspace-layout_6_review_";
|
||||
const FINDINGS_TAB = "workspace-tab-plugin_workspace_16_workspace-layout_8_findings";
|
||||
const OUTLINE_TAB = "workspace-tab-plugin_workspace_16_workspace-layout_7_outline";
|
||||
|
||||
async function withLayoutExample(
|
||||
initialPrompt: string | undefined,
|
||||
run: (agent: { agentId: string; workspaceId: string }) => Promise<void>,
|
||||
): Promise<void> {
|
||||
const example = await copyPluginExample("workspace-layout");
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "plugin-workspace-layout-",
|
||||
title: AGENT_TITLE,
|
||||
repo: { files: REPO_FILES },
|
||||
initialPrompt,
|
||||
});
|
||||
try {
|
||||
await withPluginInstalled(example.directory, () => run(workspace));
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
await example.cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
async function withPluginInstalled(directory: string, run: () => Promise<void>): Promise<void> {
|
||||
const client = await connectNewWorkspaceDaemonClient({ ownProjects: false });
|
||||
const previous = await client.getDaemonConfig();
|
||||
try {
|
||||
await client.patchDaemonConfig({ pluginsEnabled: true });
|
||||
await client.installDirectoryPlugin(directory);
|
||||
await run();
|
||||
} finally {
|
||||
await client.removePlugin("workspace-layout").catch(() => undefined);
|
||||
await client.patchDaemonConfig({ pluginsEnabled: previous.config.pluginsEnabled ?? false });
|
||||
await client.close();
|
||||
}
|
||||
}
|
||||
|
||||
/** `/open-elsewhere <id>` opens a file in that workspace, then one where the command ran. */
|
||||
const OPEN_ELSEWHERE_ENTRY = `import type { PluginClientContext } from "@getpaseo/plugin/client";
|
||||
|
||||
export default function contribute(client: PluginClientContext) {
|
||||
client.addSlashCommand({
|
||||
name: "open-elsewhere",
|
||||
description: "Open a file there, then one here",
|
||||
argumentHint: "<workspaceId>",
|
||||
context: "agent",
|
||||
onSubmit({ args, workspaceLayout }) {
|
||||
const there = client.workspaceLayout(args.trim());
|
||||
there.open({ panelId: "paseo/file", params: { path: "README.md" } });
|
||||
workspaceLayout.open({ panelId: "paseo/file", params: { path: "notes.md" } });
|
||||
},
|
||||
});
|
||||
return () => {};
|
||||
}
|
||||
`;
|
||||
|
||||
async function withTwoWorkspaces(
|
||||
run: (workspaces: {
|
||||
first: { agentId: string; workspaceId: string };
|
||||
second: { agentId: string; workspaceId: string };
|
||||
}) => Promise<void>,
|
||||
): Promise<void> {
|
||||
const example = await copyPluginExample("workspace-layout");
|
||||
await writeFile(path.join(example.directory, "index.client.tsx"), OPEN_ELSEWHERE_ENTRY);
|
||||
const seed = (title: string) =>
|
||||
seedMockAgentWorkspace({
|
||||
repoPrefix: "plugin-workspace-layout-",
|
||||
title,
|
||||
repo: { files: REPO_FILES },
|
||||
});
|
||||
const first = await seed("First agent");
|
||||
const second = await seed("Second agent");
|
||||
try {
|
||||
await withPluginInstalled(example.directory, () => run({ first, second }));
|
||||
} finally {
|
||||
await second.cleanup();
|
||||
await first.cleanup();
|
||||
await example.cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
/** Picks a workspace in a phone's agent list. */
|
||||
async function switchToWorkspace(page: Page, workspaceId: string): Promise<void> {
|
||||
await openMobileAgentSidebar(page);
|
||||
await selectWorkspaceInSidebar(page, workspaceId);
|
||||
await expect(
|
||||
page.getByTestId(`workspace-deck-entry-${getServerId()}:${workspaceId}`),
|
||||
).toBeVisible();
|
||||
await expect(composerIn(page.locator("body"))).toBeEditable({ timeout: 30_000 });
|
||||
}
|
||||
|
||||
function mainPanes(page: Page): Locator {
|
||||
return page.locator('[data-testid^="workspace-pane-"]').filter({ visible: true });
|
||||
}
|
||||
|
||||
function explorer(page: Page): Locator {
|
||||
return page.getByTestId("workspace-explorer-sidebar");
|
||||
}
|
||||
|
||||
function agentTabs(scope: Locator): Locator {
|
||||
return scope.locator('[data-testid^="workspace-tab-agent_"]');
|
||||
}
|
||||
|
||||
function composerIn(scope: Locator): Locator {
|
||||
return scope.getByRole("textbox", { name: "Message agent..." }).filter({ visible: true });
|
||||
}
|
||||
|
||||
async function sendToMainChat(page: Page, text: string): Promise<void> {
|
||||
const composer = composerIn(mainPanes(page).first());
|
||||
await expect(composer).toBeEditable({ timeout: 30_000 });
|
||||
await composer.fill(text);
|
||||
await composer.press("Enter");
|
||||
}
|
||||
|
||||
async function expectAsideChat(page: Page, input: { message: string; tabs: number }) {
|
||||
const chats = agentTabs(explorer(page));
|
||||
await expect(chats).toHaveCount(input.tabs, { timeout: 30_000 });
|
||||
await expect(chats.last()).toHaveAttribute("aria-selected", "true");
|
||||
await expect(
|
||||
explorer(page).getByTestId("user-message").getByText(input.message, { exact: true }),
|
||||
).toBeVisible();
|
||||
await expect(composerIn(explorer(page))).toBeEditable();
|
||||
}
|
||||
|
||||
/** Every visible tab chip, pane by pane, to compare the arrangement before and after. */
|
||||
async function tabsByPane(page: Page): Promise<string[][]> {
|
||||
const scopes = [...(await mainPanes(page).all()), explorer(page)];
|
||||
return Promise.all(
|
||||
scopes.map((scope) =>
|
||||
scope
|
||||
.getByTestId("workspace-tabs-row")
|
||||
.locator('[data-testid^="workspace-tab-"]:not([data-testid^="workspace-tab-tooltip"])')
|
||||
.evaluateAll((chips) => chips.map((chip) => chip.getAttribute("data-testid") ?? "")),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
async function expectReviewLayout(page: Page, agentId: string): Promise<void> {
|
||||
await expect(mainPanes(page)).toHaveCount(2);
|
||||
const left = mainPanes(page).first();
|
||||
const right = mainPanes(page).last();
|
||||
await expect(left.getByTestId(`workspace-tab-agent_${agentId}`)).toBeVisible();
|
||||
|
||||
const review = right.getByTestId(`${REVIEW_TAB}${agentId.length}_${agentId}`);
|
||||
await expect(review).toHaveAttribute("aria-selected", "true");
|
||||
await expect(right.getByText(`Reviewing ${AGENT_TITLE}`, { exact: true })).toBeVisible();
|
||||
await expect(right.getByTestId("workspace-tab-working_diff")).toHaveAttribute(
|
||||
"aria-selected",
|
||||
"false",
|
||||
);
|
||||
await expect(explorer(page).getByTestId(FINDINGS_TAB)).toBeVisible();
|
||||
|
||||
const [leftBox, rightBox] = [await left.boundingBox(), await right.boundingBox()];
|
||||
if (!leftBox || !rightBox) throw new Error("Review layout panes have no bounds");
|
||||
expect(rightBox.x).toBeGreaterThan(leftBox.x);
|
||||
expect(rightBox.width / (leftBox.width + rightBox.width)).toBeCloseTo(0.4, 1);
|
||||
}
|
||||
|
||||
async function openFileInFocusedPane(page: Page, name: string): Promise<void> {
|
||||
await openFileExplorer(page);
|
||||
await openFileFromExplorer(page, name);
|
||||
await expect(mainPanes(page).getByTestId(`workspace-tab-file_${name}`)).toBeVisible();
|
||||
}
|
||||
|
||||
async function expectOutline(page: Page, lines: string[]): Promise<void> {
|
||||
const outline = page.getByTestId("workspace-layout-outline");
|
||||
for (const line of lines) {
|
||||
await expect(outline.getByText(line, { exact: true })).toHaveCount(1);
|
||||
}
|
||||
}
|
||||
|
||||
test("the workspace layout example arranges a wide workspace", async ({ page }) => {
|
||||
test.setTimeout(180_000);
|
||||
await withLayoutExample(undefined, async ({ agentId, workspaceId }) => {
|
||||
await page.setViewportSize(WIDE);
|
||||
await openAgentRoute(page, { workspaceId, agentId });
|
||||
|
||||
await test.step("/aside opens the child agent's chat in the Explorer", async () => {
|
||||
await sendToMainChat(page, "/aside hey");
|
||||
await expectAsideChat(page, { message: "hey", tabs: 1 });
|
||||
await expect(agentTabs(mainPanes(page))).toHaveCount(1);
|
||||
});
|
||||
|
||||
await test.step("a second /aside adds a second tab", async () => {
|
||||
await sendToMainChat(page, "/aside again");
|
||||
await expectAsideChat(page, { message: "again", tabs: 2 });
|
||||
await expect(agentTabs(mainPanes(page))).toHaveCount(1);
|
||||
});
|
||||
|
||||
await test.step("Review layout splits the workspace, and running it again changes nothing", async () => {
|
||||
await runCommand(page, "Review layout");
|
||||
await expectReviewLayout(page, agentId);
|
||||
const arranged = await tabsByPane(page);
|
||||
|
||||
await mainPanes(page).first().getByTestId(`workspace-tab-agent_${agentId}`).click();
|
||||
await runCommand(page, "Review layout");
|
||||
await expectReviewLayout(page, agentId);
|
||||
expect(await tabsByPane(page)).toEqual(arranged);
|
||||
});
|
||||
|
||||
await test.step("the outline follows the focused file across split panes", async () => {
|
||||
await mainPanes(page).first().getByTestId(`workspace-tab-agent_${agentId}`).click();
|
||||
await runCommand(page, "Show outline");
|
||||
await expectOutline(page, [NO_FILE]);
|
||||
|
||||
await openFileInFocusedPane(page, "README.md");
|
||||
await explorer(page).getByTestId(OUTLINE_TAB).click();
|
||||
await expectOutline(page, ["README.md", "Guide", "Install"]);
|
||||
|
||||
await runWorkspaceActionFromCommandCenter(page, "Split pane right");
|
||||
await expect(mainPanes(page)).toHaveCount(3);
|
||||
await openFileInFocusedPane(page, "notes.md");
|
||||
await explorer(page).getByTestId(OUTLINE_TAB).click();
|
||||
await expectOutline(page, ["notes.md", "Notes", "Open questions"]);
|
||||
|
||||
await mainPanes(page).getByTestId("workspace-tab-file_README.md").click();
|
||||
await expectOutline(page, ["README.md", "Guide", "Install"]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test("the workspace layout example opens over a phone's chat", async ({ page }) => {
|
||||
test.setTimeout(180_000);
|
||||
await withLayoutExample(promptMentioning(FILE_LINK), async ({ agentId, workspaceId }) => {
|
||||
await page.setViewportSize(COMPACT);
|
||||
await openAgentRoute(page, { workspaceId, agentId });
|
||||
|
||||
await test.step("/aside opens the Explorer over the chat", async () => {
|
||||
await submitMessageWithButton(page, "/aside hey");
|
||||
await expectMobileExplorerVisible(page);
|
||||
await expectAsideChat(page, { message: "hey", tabs: 1 });
|
||||
await closeMobileExplorer(page);
|
||||
await expectMobileExplorerHidden(page);
|
||||
await expect(
|
||||
page.getByRole("button", { name: "Switch tabs (1 open)" }).filter({ visible: true }),
|
||||
).toBeVisible();
|
||||
});
|
||||
|
||||
await test.step("a file sheet updates the outline, and closing it restores it", async () => {
|
||||
await openMobileAgentSidebar(page);
|
||||
const commandCenter = await openCommandCenter(page);
|
||||
await commandCenter.getByTestId("command-center-input").fill("Show outline");
|
||||
await commandCenter.getByRole("button", { name: "Show outline", exact: true }).click();
|
||||
await expectMobileExplorerVisible(page);
|
||||
await expectOutline(page, [NO_FILE]);
|
||||
await closeMobileExplorer(page);
|
||||
await expectMobileExplorerHidden(page);
|
||||
|
||||
await page.getByText(FILE_LINK, { exact: true }).first().click();
|
||||
await expect(sheet(page, "README.md")).toBeVisible();
|
||||
// The sheet covers the Explorer, so the outline can only be read, not seen.
|
||||
await expectOutline(page, ["README.md", "Guide", "Install"]);
|
||||
await closeSheet(page, "README.md");
|
||||
await expectOutline(page, [NO_FILE]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test("a file a plugin opens in another workspace waits there on a phone", async ({ page }) => {
|
||||
test.setTimeout(180_000);
|
||||
await withTwoWorkspaces(async ({ first, second }) => {
|
||||
await page.setViewportSize(COMPACT);
|
||||
// Visiting the first workspace leaves its screen mounted behind the second.
|
||||
await openAgentRoute(page, first);
|
||||
await expect(composerIn(page.locator("body"))).toBeEditable({ timeout: 30_000 });
|
||||
await switchToWorkspace(page, second.workspaceId);
|
||||
|
||||
await test.step("only the sheet of the workspace on screen is shown", async () => {
|
||||
await submitMessageWithButton(page, `/open-elsewhere ${first.workspaceId}`);
|
||||
await expect(sheet(page, "notes.md")).toBeVisible();
|
||||
await expectOneSheetOpen(page);
|
||||
await closeSheet(page, "notes.md");
|
||||
await expectNoSheetOpen(page);
|
||||
});
|
||||
|
||||
await test.step("the other sheet is there when the user goes to its workspace", async () => {
|
||||
await switchToWorkspace(page, first.workspaceId);
|
||||
await expect(sheet(page, "README.md")).toBeVisible();
|
||||
await expectOneSheetOpen(page);
|
||||
await closeSheet(page, "README.md");
|
||||
await expectNoSheetOpen(page);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,605 +0,0 @@
|
||||
import { mkdir } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import type { Locator } from "@playwright/test";
|
||||
import { expect, test, type Page } from "../support/fixtures";
|
||||
import { expectAgentIdle, expectAgentReadyToInterrupt } from "../support/helpers/agent-stream";
|
||||
import {
|
||||
drillIntoProvider,
|
||||
expectComposerMode,
|
||||
expectComposerModel,
|
||||
openModelPicker,
|
||||
selectModelRow,
|
||||
} from "../support/helpers/agent-profiles";
|
||||
import { expectWorkspaceAgentConfiguration } from "../support/helpers/command-center-agent-controls";
|
||||
import {
|
||||
expectComposerVisible,
|
||||
expectQueuedMessageButton,
|
||||
submitMessage,
|
||||
submitMessageWithButton,
|
||||
} from "../support/helpers/composer";
|
||||
import { connectDaemonClient } from "../support/helpers/daemon-client-loader";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
import { copyPluginExample } from "../support/helpers/plugin-fixture";
|
||||
import { userScrollsTimelineToHistoryStart } from "../support/helpers/timeline-pagination";
|
||||
|
||||
const DIRECT_PROVIDER = {
|
||||
id: "direct-example",
|
||||
label: "Direct provider example",
|
||||
pluginId: "provider-direct-example",
|
||||
modelId: "example-1",
|
||||
modelLabel: "Example 1",
|
||||
modeLabel: "Build",
|
||||
} as const;
|
||||
|
||||
// Disable external CLIs so the E2E host deterministically exposes only Mock +
|
||||
// the installed Direct provider plugin on both developer machines and CI.
|
||||
test.use({
|
||||
e2eDaemonConfig: {
|
||||
version: 1,
|
||||
agents: {
|
||||
providers: {
|
||||
claude: { enabled: false },
|
||||
codex: { enabled: false },
|
||||
copilot: { enabled: false },
|
||||
opencode: { enabled: false },
|
||||
pi: { enabled: false },
|
||||
omp: { enabled: false },
|
||||
antigravity: { enabled: false },
|
||||
hoplite: { enabled: false },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
interface PluginInstallDaemonClient {
|
||||
connect(): Promise<void>;
|
||||
close(): Promise<void>;
|
||||
getDaemonConfig(): Promise<{ config: { pluginsEnabled?: boolean } }>;
|
||||
patchDaemonConfig(config: { pluginsEnabled?: boolean }): Promise<unknown>;
|
||||
installDirectoryPlugin(directory: string): Promise<unknown>;
|
||||
removePlugin(pluginId: string): Promise<void>;
|
||||
getProvidersSnapshot(): Promise<{
|
||||
entries: Array<{ provider: string; available?: boolean }>;
|
||||
}>;
|
||||
}
|
||||
|
||||
async function hasDirectProvider(client: PluginInstallDaemonClient): Promise<boolean> {
|
||||
const snapshot = await client.getProvidersSnapshot();
|
||||
return snapshot.entries.some((entry) => entry.provider === DIRECT_PROVIDER.id);
|
||||
}
|
||||
|
||||
async function expectSwitchMarkerCountAfterScroll(page: Page, expected: number): Promise<void> {
|
||||
await expect
|
||||
.poll(
|
||||
async () => {
|
||||
await userScrollsTimelineToHistoryStart(page);
|
||||
return await page.getByTestId("provider-switch-marker").count();
|
||||
},
|
||||
{ timeout: 30_000 },
|
||||
)
|
||||
.toBe(expected);
|
||||
}
|
||||
|
||||
async function captureQaScreenshot(page: Page, fileName: string): Promise<void> {
|
||||
const dir = process.env.PASEO_QA_SCREENSHOT_DIR?.trim();
|
||||
if (!dir) return;
|
||||
await mkdir(dir, { recursive: true });
|
||||
await page.screenshot({ path: path.join(dir, fileName), fullPage: false });
|
||||
}
|
||||
|
||||
async function expectNoHorizontalOverflow(page: Page): Promise<void> {
|
||||
const overflow = await page.evaluate(() => {
|
||||
const doc = document.documentElement;
|
||||
return Math.ceil(doc.scrollWidth - doc.clientWidth);
|
||||
});
|
||||
expect(overflow).toBeLessThanOrEqual(1);
|
||||
}
|
||||
|
||||
async function startSwitchOrderGuard(page: Page): Promise<void> {
|
||||
await page.evaluate(() => {
|
||||
const violations: string[] = [];
|
||||
let stopped = false;
|
||||
const step = () => {
|
||||
const msgs = Array.from(document.querySelectorAll('[data-testid="user-message"]'));
|
||||
const markers = Array.from(
|
||||
document.querySelectorAll('[data-testid="provider-switch-marker"]'),
|
||||
);
|
||||
const banner = document.querySelector('[data-testid="staged-provider-switch-banner"]');
|
||||
if (msgs.length >= 2) {
|
||||
const secondMsg = msgs[msgs.length - 1];
|
||||
const lastMarker = markers[markers.length - 1];
|
||||
if (!lastMarker) {
|
||||
violations.push("user-message painted without switch marker");
|
||||
} else {
|
||||
const msgRect = secondMsg.getBoundingClientRect();
|
||||
const markerRect = lastMarker.getBoundingClientRect();
|
||||
if (markerRect.top > msgRect.top) {
|
||||
violations.push(
|
||||
`switch marker painted below user-message (${Math.round(markerRect.top)} > ${Math.round(msgRect.top)})`,
|
||||
);
|
||||
}
|
||||
}
|
||||
if (banner && banner.getBoundingClientRect().height > 0) {
|
||||
violations.push("staged-provider-switch-banner stayed visible after submit");
|
||||
}
|
||||
}
|
||||
if (!stopped) requestAnimationFrame(step);
|
||||
};
|
||||
requestAnimationFrame(step);
|
||||
(window as unknown as { __stopSwitchOrderGuard?: () => string[] }).__stopSwitchOrderGuard =
|
||||
() => {
|
||||
stopped = true;
|
||||
return violations;
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async function stopSwitchOrderGuard(page: Page): Promise<string[]> {
|
||||
return await page.evaluate(
|
||||
() =>
|
||||
(
|
||||
window as unknown as { __stopSwitchOrderGuard?: () => string[] }
|
||||
).__stopSwitchOrderGuard?.() ?? [],
|
||||
);
|
||||
}
|
||||
|
||||
async function completeMockTurn(
|
||||
page: Page,
|
||||
agent: Awaited<ReturnType<typeof seedMockAgentWorkspace>>,
|
||||
prompt: string,
|
||||
): Promise<Locator> {
|
||||
await submitMessage(page, prompt);
|
||||
const userMessage = page.getByTestId("user-message").filter({ hasText: prompt });
|
||||
await expect(userMessage).toBeVisible({ timeout: 30_000 });
|
||||
const finish = await agent.client.waitForFinish(agent.agentId, 30_000);
|
||||
expect(finish.status).toBe("idle");
|
||||
await expectAgentIdle(page);
|
||||
await expect(userMessage).toHaveAttribute("aria-busy", "false");
|
||||
return userMessage;
|
||||
}
|
||||
|
||||
async function completeDirectTurn(
|
||||
page: Page,
|
||||
agent: Awaited<ReturnType<typeof seedMockAgentWorkspace>>,
|
||||
prompt: string,
|
||||
options?: { useSendButton?: boolean },
|
||||
): Promise<Locator> {
|
||||
if (options?.useSendButton) {
|
||||
await submitMessageWithButton(page, prompt);
|
||||
} else {
|
||||
await submitMessage(page, prompt);
|
||||
}
|
||||
const userMessage = page.getByTestId("user-message").filter({ hasText: prompt });
|
||||
await expect(userMessage).toBeVisible({ timeout: 30_000 });
|
||||
const finish = await agent.client.waitForFinish(agent.agentId, 30_000);
|
||||
expect(finish.status).toBe("idle");
|
||||
await expectAgentIdle(page);
|
||||
await expect(userMessage).toHaveAttribute("aria-busy", "false");
|
||||
return userMessage;
|
||||
}
|
||||
|
||||
async function stageProviderDesktop(
|
||||
page: Page,
|
||||
providerId: string,
|
||||
modelId: string,
|
||||
): Promise<void> {
|
||||
await openModelPicker(page);
|
||||
const picker = page.getByTestId("combobox-desktop-container");
|
||||
const backButton = picker.getByTestId("sheet-header-back");
|
||||
if (await backButton.isVisible()) {
|
||||
await backButton.click();
|
||||
}
|
||||
await drillIntoProvider(page, providerId);
|
||||
await selectModelRow(page, { provider: providerId, modelId });
|
||||
await expect(page.getByTestId("staged-provider-switch-banner")).toBeVisible({ timeout: 30_000 });
|
||||
}
|
||||
|
||||
async function stageDirectProviderDesktop(page: Page): Promise<void> {
|
||||
await stageProviderDesktop(page, DIRECT_PROVIDER.id, DIRECT_PROVIDER.modelId);
|
||||
}
|
||||
|
||||
async function stageDirectProviderCompact(page: Page): Promise<void> {
|
||||
await page.getByTestId("combined-model-selector").filter({ visible: true }).first().click();
|
||||
await expect(page.getByTestId("agent-controls-model")).toBeVisible({ timeout: 30_000 });
|
||||
await page.getByTestId("agent-controls-model").click();
|
||||
const modelPage = page.getByTestId("mobile-model-page");
|
||||
await expect(modelPage).toBeVisible({ timeout: 30_000 });
|
||||
const collapsedProvider = modelPage.getByTestId(`model-provider-${DIRECT_PROVIDER.id}`);
|
||||
if (await collapsedProvider.isVisible()) {
|
||||
await collapsedProvider.click();
|
||||
}
|
||||
await modelPage.getByTestId(`model-row-${DIRECT_PROVIDER.id}-${DIRECT_PROVIDER.modelId}`).click();
|
||||
await expect(page.getByTestId("agent-controls-settings-list")).toBeVisible({ timeout: 30_000 });
|
||||
// Dismiss the agent-controls sheet so the composer and banner are ready to submit.
|
||||
await page.getByRole("button", { name: "Close", exact: true }).last().click();
|
||||
await expect(page.getByTestId("agent-controls-model")).toHaveCount(0, { timeout: 30_000 });
|
||||
await expect(page.getByTestId("staged-provider-switch-banner")).toBeVisible({ timeout: 30_000 });
|
||||
}
|
||||
|
||||
async function rewindConversation(page: Page, userMessage: Locator, prompt: string): Promise<void> {
|
||||
await userMessage.getByText(prompt, { exact: true }).hover();
|
||||
await userMessage.getByRole("button", { name: "Rewind to this message", exact: true }).click();
|
||||
await page.getByRole("menuitem", { name: "Rewind conversation", exact: true }).click();
|
||||
}
|
||||
|
||||
test.describe.serial("Provider switching in chat", () => {
|
||||
let pluginClient: PluginInstallDaemonClient;
|
||||
let pluginFixture: Awaited<ReturnType<typeof copyPluginExample>>;
|
||||
let previousPluginsEnabled: boolean | undefined;
|
||||
|
||||
test.beforeAll(async () => {
|
||||
pluginClient = await connectDaemonClient<PluginInstallDaemonClient>({
|
||||
clientIdPrefix: "provider-switching-e2e",
|
||||
});
|
||||
pluginFixture = await copyPluginExample("provider-direct");
|
||||
previousPluginsEnabled = (await pluginClient.getDaemonConfig()).config.pluginsEnabled;
|
||||
await pluginClient.patchDaemonConfig({ pluginsEnabled: true });
|
||||
await pluginClient.installDirectoryPlugin(pluginFixture.directory);
|
||||
await expect.poll(() => hasDirectProvider(pluginClient), { timeout: 30_000 }).toBe(true);
|
||||
});
|
||||
|
||||
test.afterAll(async () => {
|
||||
await pluginClient?.removePlugin(DIRECT_PROVIDER.pluginId).catch(() => undefined);
|
||||
await pluginClient
|
||||
?.patchDaemonConfig({ pluginsEnabled: previousPluginsEnabled })
|
||||
.catch(() => undefined);
|
||||
await pluginClient?.close().catch(() => undefined);
|
||||
await pluginFixture?.cleanup().catch(() => undefined);
|
||||
});
|
||||
|
||||
test("stages, cancels, switches providers, inspects marker, scopes rewind, and survives reload", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(150_000);
|
||||
await page.setViewportSize({ width: 1280, height: 800 });
|
||||
|
||||
const preSwitchPrompt = "First prompt on Mock before switching.";
|
||||
const postSwitchPrompt = "Follow up on Direct provider after switching.";
|
||||
const postRewindPrompt = "Continue on Direct provider after rewinding.";
|
||||
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "provider-switch-desktop-",
|
||||
title: "Provider switch desktop",
|
||||
model: "e2e-fast-stream",
|
||||
modeId: "load-test",
|
||||
});
|
||||
|
||||
try {
|
||||
await openAgentRoute(page, workspace);
|
||||
await expectComposerVisible(page);
|
||||
await expectComposerMode(page, "Load test");
|
||||
|
||||
const initialUrl = page.url();
|
||||
await completeMockTurn(page, workspace, preSwitchPrompt);
|
||||
|
||||
await test.step("staging updates only draft state and Cancel restores the live provider", async () => {
|
||||
await stageDirectProviderDesktop(page);
|
||||
await expectComposerModel(page, DIRECT_PROVIDER.modelLabel);
|
||||
await expectComposerMode(page, DIRECT_PROVIDER.modeLabel);
|
||||
await expect(page.getByTestId("staged-provider-switch-banner")).toContainText(
|
||||
DIRECT_PROVIDER.label,
|
||||
);
|
||||
await expectWorkspaceAgentConfiguration(workspace, {
|
||||
id: workspace.agentId,
|
||||
provider: "mock",
|
||||
model: "e2e-fast-stream",
|
||||
modeId: "load-test",
|
||||
});
|
||||
// Editing a staged provider option must keep all staged option controls visible.
|
||||
const conciseToggle = page.getByRole("button", { name: /Concise responses/i }).first();
|
||||
const voiceSelect = page.getByRole("button", { name: /Voice/i }).first();
|
||||
await expect(conciseToggle).toBeVisible();
|
||||
await expect(voiceSelect).toBeVisible();
|
||||
await conciseToggle.click();
|
||||
await expect(conciseToggle).toBeVisible();
|
||||
await expect(voiceSelect).toBeVisible();
|
||||
await expectNoHorizontalOverflow(page);
|
||||
await captureQaScreenshot(page, "desktop-staged-switch.png");
|
||||
|
||||
await page.getByTestId("cancel-staged-provider-switch").click();
|
||||
await expect(page.getByTestId("staged-provider-switch-banner")).toHaveCount(0);
|
||||
await expectComposerMode(page, "Load test");
|
||||
|
||||
// Returning to the live provider by choosing a different model clears the staged switch
|
||||
// and applies the newly chosen model directly to the live provider.
|
||||
await stageDirectProviderDesktop(page);
|
||||
await openModelPicker(page);
|
||||
const picker = page.getByTestId("combobox-desktop-container");
|
||||
const backButton = picker.getByTestId("sheet-header-back");
|
||||
if (await backButton.isVisible()) {
|
||||
await backButton.click();
|
||||
}
|
||||
await drillIntoProvider(page, "mock");
|
||||
await selectModelRow(page, { provider: "mock", modelId: "one-minute-stream" });
|
||||
await expect(page.getByTestId("staged-provider-switch-banner")).toHaveCount(0);
|
||||
await expectComposerModel(page, "One minute stream");
|
||||
await expectWorkspaceAgentConfiguration(workspace, {
|
||||
id: workspace.agentId,
|
||||
provider: "mock",
|
||||
model: "one-minute-stream",
|
||||
modeId: "load-test",
|
||||
});
|
||||
});
|
||||
|
||||
await test.step("submitting commits the switch in place with clean user display text and inspectable marker", async () => {
|
||||
await stageDirectProviderDesktop(page);
|
||||
await startSwitchOrderGuard(page);
|
||||
const switchedMessage = await completeDirectTurn(page, workspace, postSwitchPrompt);
|
||||
expect(await stopSwitchOrderGuard(page)).toEqual([]);
|
||||
|
||||
expect(page.url()).toBe(initialUrl);
|
||||
await expect(page.getByTestId("staged-provider-switch-banner")).toHaveCount(0);
|
||||
await expectWorkspaceAgentConfiguration(workspace, {
|
||||
id: workspace.agentId,
|
||||
provider: DIRECT_PROVIDER.id,
|
||||
model: DIRECT_PROVIDER.modelId,
|
||||
modeId: "build",
|
||||
});
|
||||
|
||||
// Clean display text: handoff summary must never leak into the visible user bubble.
|
||||
await expect(switchedMessage).toContainText(postSwitchPrompt);
|
||||
await expect(switchedMessage).not.toContainText("<chat-history-summary>");
|
||||
|
||||
// Direct provider echoes its prompt, proving bounded pre-switch context was attached.
|
||||
const directReply = page
|
||||
.getByTestId("assistant-message")
|
||||
.filter({ hasText: "Echo:" })
|
||||
.last();
|
||||
await expect(directReply).toContainText(preSwitchPrompt);
|
||||
await expect(directReply).toContainText(postSwitchPrompt);
|
||||
|
||||
// Switch marker is visible and expands to show context handoff details.
|
||||
const marker = page.getByTestId("provider-switch-marker");
|
||||
await expect(marker).toBeVisible({ timeout: 30_000 });
|
||||
await marker.scrollIntoViewIfNeeded();
|
||||
await marker.getByTestId("provider-switch-marker-toggle").click();
|
||||
const details = marker.getByTestId("provider-switch-marker-details");
|
||||
await expect(details).toBeVisible();
|
||||
await expect(details).toContainText("Mock");
|
||||
await expect(details).toContainText(DIRECT_PROVIDER.label);
|
||||
await marker.scrollIntoViewIfNeeded();
|
||||
await expectNoHorizontalOverflow(page);
|
||||
await captureQaScreenshot(page, "desktop-switched-expanded.png");
|
||||
await marker.getByTestId("provider-switch-marker-toggle").click();
|
||||
await expect(details).toHaveCount(0);
|
||||
});
|
||||
|
||||
await test.step("switching back to Mock enforces segment-scoped rewind and preserves pre-switch turns", async () => {
|
||||
const backToMockPrompt = "Switch back to Mock for segment-scoped rewind.";
|
||||
await stageProviderDesktop(page, "mock", "ten-second-stream");
|
||||
await expect(page.getByTestId("staged-provider-switch-banner")).toContainText("Mock");
|
||||
|
||||
const backToMockMessage = await completeMockTurn(page, workspace, backToMockPrompt);
|
||||
await expect(backToMockMessage).not.toContainText("<chat-history-summary>");
|
||||
await expect(page.getByTestId("provider-switch-marker")).toHaveCount(2, {
|
||||
timeout: 30_000,
|
||||
});
|
||||
await expectWorkspaceAgentConfiguration(workspace, {
|
||||
id: workspace.agentId,
|
||||
provider: "mock",
|
||||
model: "ten-second-stream",
|
||||
modeId: "load-test",
|
||||
});
|
||||
|
||||
// Pre-switch prompts from earlier segments must not expose rewind even though Mock supports it.
|
||||
const preSwitchMessage = page
|
||||
.getByTestId("user-message")
|
||||
.filter({ hasText: preSwitchPrompt });
|
||||
await preSwitchMessage.scrollIntoViewIfNeeded();
|
||||
await preSwitchMessage.getByText(preSwitchPrompt, { exact: true }).hover();
|
||||
await expect(
|
||||
preSwitchMessage.getByRole("button", { name: "Rewind to this message", exact: true }),
|
||||
).toHaveCount(0);
|
||||
|
||||
const directMessage = page
|
||||
.getByTestId("user-message")
|
||||
.filter({ hasText: postSwitchPrompt });
|
||||
await directMessage.scrollIntoViewIfNeeded();
|
||||
await directMessage.getByText(postSwitchPrompt, { exact: true }).hover();
|
||||
await expect(
|
||||
directMessage.getByRole("button", { name: "Rewind to this message", exact: true }),
|
||||
).toHaveCount(0);
|
||||
|
||||
// Post-switch prompt on Mock CAN rewind without retiring earlier segments or markers.
|
||||
await backToMockMessage.scrollIntoViewIfNeeded();
|
||||
await rewindConversation(page, backToMockMessage, backToMockPrompt);
|
||||
await expect(
|
||||
page.getByTestId("user-message").filter({ hasText: backToMockPrompt }),
|
||||
).toHaveCount(0, { timeout: 30_000 });
|
||||
await expect(
|
||||
page.getByTestId("user-message").filter({ hasText: preSwitchPrompt }),
|
||||
).toBeVisible();
|
||||
await expect(
|
||||
page.getByTestId("user-message").filter({ hasText: postSwitchPrompt }),
|
||||
).toBeVisible();
|
||||
await expect(page.getByTestId("provider-switch-marker")).toHaveCount(2);
|
||||
|
||||
// Continuing in the now-empty active segment completes cleanly.
|
||||
const retriedMessage = await completeMockTurn(page, workspace, postRewindPrompt);
|
||||
await expect(retriedMessage).not.toContainText("<chat-history-summary>");
|
||||
});
|
||||
|
||||
await test.step("reload preserves the switched provider, markers, and rewind boundary", async () => {
|
||||
await page.reload();
|
||||
await expectComposerVisible(page);
|
||||
await expectComposerModel(page, "Ten second stream");
|
||||
await expectSwitchMarkerCountAfterScroll(page, 2);
|
||||
const reloadedDirect = page
|
||||
.getByTestId("user-message")
|
||||
.filter({ hasText: postSwitchPrompt });
|
||||
await expect(reloadedDirect).toBeVisible();
|
||||
await expect(
|
||||
page.getByTestId("user-message").filter({ hasText: postRewindPrompt }),
|
||||
).toBeVisible();
|
||||
|
||||
await reloadedDirect.scrollIntoViewIfNeeded();
|
||||
await reloadedDirect.getByText(postSwitchPrompt, { exact: true }).hover();
|
||||
await expect(
|
||||
reloadedDirect.getByRole("button", { name: "Rewind to this message", exact: true }),
|
||||
).toHaveCount(0);
|
||||
});
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("stages a switch mid-turn, queues the prompt, and switches cleanly between turns", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(150_000);
|
||||
await page.setViewportSize({ width: 1280, height: 800 });
|
||||
|
||||
const runningPrompt = "Run a ten-second mock turn first.";
|
||||
const queuedPrompt = "Queued handoff prompt for Direct provider.";
|
||||
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "provider-switch-midturn-",
|
||||
title: "Provider switch midturn",
|
||||
model: "ten-second-stream",
|
||||
modeId: "load-test",
|
||||
});
|
||||
|
||||
try {
|
||||
await openAgentRoute(page, workspace);
|
||||
await expectComposerVisible(page);
|
||||
|
||||
await submitMessage(page, runningPrompt);
|
||||
await expectAgentReadyToInterrupt(page);
|
||||
|
||||
// Stage Direct provider while Mock is actively streaming.
|
||||
await stageDirectProviderDesktop(page);
|
||||
await expectWorkspaceAgentConfiguration(workspace, {
|
||||
id: workspace.agentId,
|
||||
provider: "mock",
|
||||
model: "ten-second-stream",
|
||||
modeId: "load-test",
|
||||
});
|
||||
|
||||
// Submitting queues the prompt instead of racing the live turn.
|
||||
await submitMessage(page, queuedPrompt);
|
||||
await expectQueuedMessageButton(page);
|
||||
|
||||
// Once the mock turn completes, the queue drains and commits the switch.
|
||||
await expect(page.getByTestId("provider-switch-marker")).toBeVisible({ timeout: 45_000 });
|
||||
await expect(page.getByTestId("staged-provider-switch-banner")).toHaveCount(0, {
|
||||
timeout: 30_000,
|
||||
});
|
||||
await expect(
|
||||
page.getByTestId("assistant-message").filter({ hasText: queuedPrompt }).last(),
|
||||
).toBeVisible({ timeout: 30_000 });
|
||||
await expectAgentIdle(page);
|
||||
await expectWorkspaceAgentConfiguration(workspace, {
|
||||
id: workspace.agentId,
|
||||
provider: DIRECT_PROVIDER.id,
|
||||
model: DIRECT_PROVIDER.modelId,
|
||||
modeId: "build",
|
||||
});
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("edits a queued switch and sends it now, cutting the running turn", async ({ page }) => {
|
||||
test.setTimeout(150_000);
|
||||
await page.setViewportSize({ width: 1280, height: 800 });
|
||||
|
||||
const queuedPrompt = "Take over now on the Direct provider.";
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "provider-switch-queued-edit-",
|
||||
title: "Provider switch queued edit",
|
||||
model: "one-minute-stream",
|
||||
modeId: "load-test",
|
||||
});
|
||||
|
||||
try {
|
||||
await openAgentRoute(page, workspace);
|
||||
await expectComposerVisible(page);
|
||||
await submitMessage(page, "Run a one-minute mock turn first.");
|
||||
await expectAgentReadyToInterrupt(page);
|
||||
await stageDirectProviderDesktop(page);
|
||||
|
||||
const banner = page.getByTestId("staged-provider-switch-banner");
|
||||
const queuedRow = page.getByRole("listitem").filter({ hasText: queuedPrompt });
|
||||
await submitMessage(page, queuedPrompt);
|
||||
await expect(queuedRow).toContainText(`Switches to ${DIRECT_PROVIDER.label}`);
|
||||
await expect(banner).toHaveCount(0);
|
||||
await captureQaScreenshot(page, "queued-provider-switch.png");
|
||||
|
||||
await queuedRow.getByRole("button", { name: "Edit queued message" }).click();
|
||||
await expect(queuedRow).toHaveCount(0);
|
||||
await expect(banner).toBeVisible();
|
||||
|
||||
await submitMessage(page, queuedPrompt);
|
||||
await expect(queuedRow).toContainText(`Switches to ${DIRECT_PROVIDER.label}`);
|
||||
await queuedRow.getByRole("button", { name: "Send queued message now" }).click();
|
||||
|
||||
await expect(page.getByTestId("provider-switch-marker")).toBeVisible({ timeout: 30_000 });
|
||||
await expect(
|
||||
page.getByTestId("assistant-message").filter({ hasText: queuedPrompt }).last(),
|
||||
).toBeVisible({ timeout: 30_000 });
|
||||
await expectAgentIdle(page);
|
||||
await expectWorkspaceAgentConfiguration(workspace, {
|
||||
id: workspace.agentId,
|
||||
provider: DIRECT_PROVIDER.id,
|
||||
model: DIRECT_PROVIDER.modelId,
|
||||
modeId: "build",
|
||||
});
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("switches providers cleanly on a compact viewport with zero horizontal overflow", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(150_000);
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
|
||||
const preSwitchPrompt = "Compact turn on Mock.";
|
||||
const postSwitchPrompt = "Compact handoff on Direct.";
|
||||
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "provider-switch-compact-",
|
||||
title: "Provider switch compact",
|
||||
model: "e2e-fast-stream",
|
||||
modeId: "load-test",
|
||||
});
|
||||
|
||||
try {
|
||||
await openAgentRoute(page, workspace);
|
||||
await expectComposerVisible(page);
|
||||
|
||||
await submitMessageWithButton(page, preSwitchPrompt);
|
||||
await expect(
|
||||
page.getByTestId("user-message").filter({ hasText: preSwitchPrompt }),
|
||||
).toBeVisible({ timeout: 30_000 });
|
||||
const firstFinish = await workspace.client.waitForFinish(workspace.agentId, 30_000);
|
||||
expect(firstFinish.status).toBe("idle");
|
||||
await expectAgentIdle(page);
|
||||
|
||||
await stageDirectProviderCompact(page);
|
||||
await expectNoHorizontalOverflow(page);
|
||||
await captureQaScreenshot(page, "compact-staged-switch.png");
|
||||
|
||||
const switchedMessage = await completeDirectTurn(page, workspace, postSwitchPrompt, {
|
||||
useSendButton: true,
|
||||
});
|
||||
await expect(switchedMessage).not.toContainText("<chat-history-summary>");
|
||||
|
||||
const marker = page.getByTestId("provider-switch-marker");
|
||||
await expect(marker).toBeVisible({ timeout: 30_000 });
|
||||
await marker.scrollIntoViewIfNeeded();
|
||||
const toggle = marker.getByTestId("provider-switch-marker-toggle");
|
||||
const toggleBox = await toggle.boundingBox();
|
||||
expect(toggleBox).not.toBeNull();
|
||||
expect((toggleBox?.x ?? 0) + (toggleBox?.width ?? 0)).toBeLessThanOrEqual(390);
|
||||
await toggle.click();
|
||||
await expect(marker.getByTestId("provider-switch-marker-details")).toBeVisible();
|
||||
await marker.scrollIntoViewIfNeeded();
|
||||
await expectNoHorizontalOverflow(page);
|
||||
await captureQaScreenshot(page, "compact-switched-expanded.png");
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
@@ -35,13 +35,7 @@ import {
|
||||
expectSettingsHeader,
|
||||
openAddHostFlow,
|
||||
selectHostConnectionType,
|
||||
selectDirectConnectionMode,
|
||||
expectDirectConnectionMode,
|
||||
expectDirectFormModeDisabled,
|
||||
connectDirectHost,
|
||||
connectDirectHostExpectingPassword,
|
||||
pasteIntoDirectHost,
|
||||
fillDirectHostPromptPassword,
|
||||
toggleHostAdvanced,
|
||||
openCompactSettings,
|
||||
expectCompactSettingsList,
|
||||
expectSettingsSidebarVisible,
|
||||
@@ -56,11 +50,11 @@ import {
|
||||
fillDirectHostUri,
|
||||
expectDirectHostFormValues,
|
||||
expectDirectHostSslEnabled,
|
||||
expectDirectHostSslDisabled,
|
||||
fillDirectHostAddress,
|
||||
toggleDirectHostSsl,
|
||||
expectDirectHostUriValue,
|
||||
expectDirectHostUriHidden,
|
||||
expectDirectFormFullyVisible,
|
||||
expectDiagnosticsContent,
|
||||
expectAboutContent,
|
||||
expectGeneralContent,
|
||||
@@ -77,7 +71,6 @@ import {
|
||||
bindCommandCenterToEnter,
|
||||
} from "../support/helpers/settings";
|
||||
import { getServerId } from "../support/helpers/server-id";
|
||||
import { startIsolatedHostDaemon } from "../support/helpers/isolated-host-daemon";
|
||||
import { expectAppRoute } from "../support/helpers/route-assertions";
|
||||
import { clickNewChat, gotoWorkspace } from "../support/helpers/launcher";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
@@ -334,105 +327,44 @@ test.describe("Settings sidebar navigation", () => {
|
||||
await verifyLegacyHostSettingsRedirect(page);
|
||||
});
|
||||
|
||||
test("direct connection converts between Form and URI modes", async ({ page }) => {
|
||||
test("direct connection advanced URI round-trips SSL and password into the form", async ({
|
||||
page,
|
||||
}) => {
|
||||
await gotoAppShell(page);
|
||||
await openSettings(page);
|
||||
await openAddHostFlow(page);
|
||||
await expectAddHostMethodOptions(page);
|
||||
await selectHostConnectionType(page, "direct");
|
||||
await expectDirectConnectionMode(page, "Form");
|
||||
|
||||
await test.step("Form fields become a URI", async () => {
|
||||
await fillDirectHostAddress(page, "example.paseo.test", "7443");
|
||||
await toggleDirectHostSsl(page);
|
||||
await selectDirectConnectionMode(page, "URI");
|
||||
await expectDirectHostUriValue(page, "tcp://example.paseo.test:7443?ssl=true");
|
||||
await fillDirectHostAddress(page, "example.paseo.test", "7443");
|
||||
await expectDirectHostSslDisabled(page);
|
||||
await toggleDirectHostSsl(page);
|
||||
await expectDirectHostSslEnabled(page);
|
||||
await toggleHostAdvanced(page);
|
||||
await expectDirectHostUriValue(page, "tcp://example.paseo.test:7443?ssl=true");
|
||||
await toggleHostAdvanced(page);
|
||||
await toggleDirectHostSsl(page);
|
||||
await expectDirectHostSslDisabled(page);
|
||||
|
||||
await toggleHostAdvanced(page);
|
||||
await fillDirectHostUri(page, "tcp://example.paseo.test:7443?ssl=true&password=shared-secret");
|
||||
await toggleHostAdvanced(page);
|
||||
|
||||
await expectDirectHostFormValues(page, {
|
||||
host: "example.paseo.test",
|
||||
port: "7443",
|
||||
password: "shared-secret",
|
||||
});
|
||||
await expectDirectHostSslEnabled(page);
|
||||
await expectDirectHostUriHidden(page);
|
||||
|
||||
await test.step("a URI becomes Form fields", async () => {
|
||||
await fillDirectHostUri(
|
||||
page,
|
||||
"tcp://example.paseo.test:7443?ssl=true&password=shared-secret",
|
||||
);
|
||||
await selectDirectConnectionMode(page, "Form");
|
||||
await expectDirectHostFormValues(page, {
|
||||
host: "example.paseo.test",
|
||||
port: "7443",
|
||||
password: "shared-secret",
|
||||
});
|
||||
await expectDirectHostSslEnabled(page);
|
||||
await expectDirectHostUriHidden(page);
|
||||
});
|
||||
|
||||
await test.step("a pairing link pasted into Host stays a URI", async () => {
|
||||
const link = "relay://relay.paseo.test:443/srv_e2e_pairing?key=daemon-key&ssl=true";
|
||||
await pasteIntoDirectHost(page, link);
|
||||
await expectDirectConnectionMode(page, "URI");
|
||||
await expectDirectHostUriValue(page, link);
|
||||
await expectDirectFormModeDisabled(page);
|
||||
});
|
||||
});
|
||||
|
||||
test("direct connection connects to a URI with Host blank", async ({ page }) => {
|
||||
await gotoAppShell(page);
|
||||
await openSettings(page);
|
||||
await openAddHostFlow(page);
|
||||
await selectHostConnectionType(page, "direct");
|
||||
|
||||
await selectDirectConnectionMode(page, "URI");
|
||||
await fillDirectHostUri(page, `tcp://127.0.0.1:${getE2EDaemonPort()}`);
|
||||
|
||||
await connectDirectHost(page);
|
||||
});
|
||||
|
||||
test("direct connection connects to an edited URI instead of the form", async ({ page }) => {
|
||||
await gotoAppShell(page);
|
||||
await openSettings(page);
|
||||
await openAddHostFlow(page);
|
||||
await selectHostConnectionType(page, "direct");
|
||||
|
||||
await fillDirectHostAddress(page, "127.0.0.1", "9");
|
||||
await selectDirectConnectionMode(page, "URI");
|
||||
await expectDirectHostUriValue(page, "tcp://127.0.0.1:9");
|
||||
await fillDirectHostUri(page, `tcp://127.0.0.1:${getE2EDaemonPort()}`);
|
||||
|
||||
await connectDirectHost(page);
|
||||
});
|
||||
|
||||
test("direct connection sends the password in a URI and asks again when it is wrong", async ({
|
||||
page,
|
||||
}) => {
|
||||
const password = "e2e uri password";
|
||||
const daemon = await startIsolatedHostDaemon("srv_e2e_uri_password_host", {
|
||||
environment: { ...process.env, PASEO_PASSWORD: password },
|
||||
});
|
||||
try {
|
||||
await gotoAppShell(page);
|
||||
await openSettings(page);
|
||||
|
||||
await test.step("a URI with the password connects with one tap", async () => {
|
||||
await openAddHostFlow(page);
|
||||
await selectHostConnectionType(page, "direct");
|
||||
await selectDirectConnectionMode(page, "URI");
|
||||
await fillDirectHostUri(
|
||||
page,
|
||||
`tcp://127.0.0.1:${daemon.port}?password=${encodeURIComponent(password)}`,
|
||||
);
|
||||
await connectDirectHost(page);
|
||||
});
|
||||
|
||||
await test.step("a wrong password asks for the host's password inline", async () => {
|
||||
await openAddHostFlow(page);
|
||||
await selectHostConnectionType(page, "direct");
|
||||
await selectDirectConnectionMode(page, "URI");
|
||||
await fillDirectHostUri(page, `tcp://127.0.0.1:${daemon.port}?password=wrong`);
|
||||
await connectDirectHostExpectingPassword(page, `127.0.0.1:${daemon.port}`);
|
||||
await fillDirectHostPromptPassword(page, password);
|
||||
await connectDirectHost(page);
|
||||
});
|
||||
} finally {
|
||||
await daemon.close();
|
||||
}
|
||||
await toggleHostAdvanced(page);
|
||||
await expectDirectHostUriValue(
|
||||
page,
|
||||
"tcp://example.paseo.test:7443?ssl=true&password=shared-secret",
|
||||
);
|
||||
await toggleHostAdvanced(page);
|
||||
await expectDirectHostUriHidden(page);
|
||||
});
|
||||
|
||||
test("Escape lets settings dropdowns and modals close before leaving settings", async ({
|
||||
@@ -765,16 +697,3 @@ test("docked navigation keeps its density and Settings preserves reading width",
|
||||
await expectSettingsSidebarHidden(page);
|
||||
await expectAppearanceContent(page);
|
||||
});
|
||||
|
||||
test.describe("Settings — small phone", () => {
|
||||
test.use({ viewport: { width: 360, height: 640 } });
|
||||
|
||||
test("direct connection shows the whole form above Cancel and Connect", async ({ page }) => {
|
||||
await gotoAppShell(page);
|
||||
await openCompactSidebar(page);
|
||||
await openSettingsFromCompactSidebar(page);
|
||||
await openAddHostFlow(page);
|
||||
await selectHostConnectionType(page, "direct");
|
||||
await expectDirectFormFullyVisible(page);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -111,7 +111,7 @@ Keep generated screenshots, recordings, and run logs outside the repository.
|
||||
confirmation. It first types without tapping the input to verify autofocus, then cancels the
|
||||
confirmation, closes and reopens the underlying sheet, confirms again,
|
||||
and completes the password retry. `stacked-settings.ad` checks the same return and retry through
|
||||
Settings → add host → Direct connection → URI. Run both on phones and tablets so both the
|
||||
Settings → add host → Direct connection → Advanced. Run both on phones and tablets so both the
|
||||
bottom sheet and centered dialog are exercised.
|
||||
|
||||
These integration journeys require the host-confirmation flow in the test app. Include both the
|
||||
@@ -146,7 +146,7 @@ Android uses the same journeys: copy each script outside the repository, change
|
||||
artifacts, and sessions separate from other runs. These host-dependent journeys remain outside the
|
||||
default mobile suite, alongside the existing modal-sheet scripts.
|
||||
|
||||
On iPhone, bulk replacement or bulk keyboard entry of the Connection URI field triggers a
|
||||
On iPhone, bulk replacement or bulk keyboard entry of the advanced URI field triggers a
|
||||
repeated-update error with both the parent and stacked-sheet implementations. Entering the complete
|
||||
URI one character at a time passed with both implementations; faster typing remains unverified.
|
||||
On iPad, replacing the field a second time appends text. For this Settings journey, use the
|
||||
|
||||
@@ -10,7 +10,7 @@ wait "id=\"add-host-method-direct\"" 10000
|
||||
screenshot "${OUT}/10-add-host-methods.png"
|
||||
press "id=\"add-host-method-direct\""
|
||||
wait stable
|
||||
press "id=\"direct-mode-uri\""
|
||||
press "id=\"direct-host-advanced-toggle\""
|
||||
wait stable
|
||||
fill "id=\"direct-host-uri-input\"" "${PAIRING_LINK}"
|
||||
wait stable
|
||||
@@ -32,9 +32,9 @@ wait "id=\"host-confirmation-connect\"" 10000
|
||||
screenshot "${OUT}/14-add-host-confirmation-reopens.png"
|
||||
press "id=\"host-confirmation-connect\""
|
||||
wait stable
|
||||
wait "id=\"direct-uri-password-input\"" 20000
|
||||
wait "id=\"direct-password-input\"" 20000
|
||||
screenshot "${OUT}/15-add-host-password.png"
|
||||
fill "id=\"direct-uri-password-input\"" "${PASSWORD}"
|
||||
fill "id=\"direct-password-input\"" "${PASSWORD}"
|
||||
wait stable
|
||||
press "id=\"direct-host-submit\""
|
||||
wait stable
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { expect, type Page } from "@playwright/test";
|
||||
import { readScrollMetrics, waitForContentGrowth, expectNearBottom } from "./agent-bottom-anchor";
|
||||
import { agentStopButton } from "./composer";
|
||||
|
||||
export async function awaitAssistantMessage(page: Page, hasText?: string | RegExp): Promise<void> {
|
||||
const messages = page.getByTestId("assistant-message");
|
||||
@@ -15,7 +14,7 @@ export async function awaitToolCall(page: Page, toolName: string | RegExp): Prom
|
||||
}
|
||||
|
||||
export async function expectAgentIdle(page: Page, timeout = 30_000): Promise<void> {
|
||||
await expect(agentStopButton(page)).toHaveCount(0, { timeout });
|
||||
await expect(page.getByRole("button", { name: /stop|cancel/i })).toHaveCount(0, { timeout });
|
||||
}
|
||||
|
||||
// The working indicator is an animated spinner View — no semantic ARIA role, testId is correct.
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,141 +0,0 @@
|
||||
import { expect, type Browser, type Locator, type Page } from "@playwright/test";
|
||||
import { hideDeveloperToasts } from "../developer-ui.mjs";
|
||||
import {
|
||||
agentStopButton,
|
||||
composerLocator,
|
||||
expectComposerDraft,
|
||||
fillComposerDraft,
|
||||
sendDraftToQueue,
|
||||
} from "./composer";
|
||||
import { openAgentRoute, seedMockAgentWorkspace, type MockAgentWorkspace } from "./mock-agent";
|
||||
|
||||
export interface AgentWithOpenTurn extends MockAgentWorkspace {
|
||||
/** Ends the open turn from outside the app, so it also works with every page closed. */
|
||||
finishTurn(): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* A mock agent whose first turn stays open on a plan approval. The turn ends when the test
|
||||
* answers it, so nothing here depends on how long a stream runs.
|
||||
*/
|
||||
export async function seedAgentWithOpenTurn(input: {
|
||||
repoPrefix: string;
|
||||
title: string;
|
||||
}): Promise<AgentWithOpenTurn> {
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
...input,
|
||||
initialPrompt: "Emit synthetic plan approval.",
|
||||
});
|
||||
await agent.client.waitForFinish(agent.agentId, 30_000);
|
||||
return {
|
||||
...agent,
|
||||
async finishTurn() {
|
||||
const fetched = await agent.client.fetchAgent({ agentId: agent.agentId });
|
||||
const request = fetched?.agent.pendingPermissions[0];
|
||||
if (!request) throw new Error("The agent has no open turn to finish");
|
||||
await agent.client.respondToPermission(agent.agentId, request.id, { behavior: "allow" });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function queuedRows(page: Page): Locator {
|
||||
return page.getByRole("list", { name: "Queued messages" }).getByRole("listitem");
|
||||
}
|
||||
|
||||
export function queuedRow(page: Page, text: string): Locator {
|
||||
return queuedRows(page).filter({ hasText: text });
|
||||
}
|
||||
|
||||
export async function queueMessage(page: Page, text: string): Promise<void> {
|
||||
await fillComposerDraft(page, text);
|
||||
await sendDraftToQueue(page);
|
||||
await expect(queuedRow(page, text)).toBeVisible();
|
||||
await expectComposerDraft(page, "");
|
||||
}
|
||||
|
||||
export async function editQueuedMessage(page: Page, text: string): Promise<void> {
|
||||
await queuedRow(page, text)
|
||||
.getByRole("button", { name: "Edit queued message", exact: true })
|
||||
.click();
|
||||
}
|
||||
|
||||
export async function cancelQueuedMessage(page: Page, text: string): Promise<void> {
|
||||
await queuedRow(page, text)
|
||||
.getByRole("button", { name: "Cancel queued message", exact: true })
|
||||
.click();
|
||||
}
|
||||
|
||||
export async function sendQueuedMessageNow(page: Page, text: string): Promise<void> {
|
||||
await queuedRow(page, text)
|
||||
.getByRole("button", { name: "Send queued message now", exact: true })
|
||||
.click();
|
||||
}
|
||||
|
||||
export function queuePausedNotice(page: Page): Locator {
|
||||
return page.getByText("Queue paused until you send a message", { exact: true });
|
||||
}
|
||||
|
||||
/** Queues through the host, for tests that need more rows than are worth typing. */
|
||||
export async function queueThroughHost(agent: AgentWithOpenTurn, texts: string[]): Promise<void> {
|
||||
for (const text of texts) {
|
||||
await agent.client.sendAgentMessage(agent.agentId, text, { activeTurnBehavior: "queue" });
|
||||
}
|
||||
}
|
||||
|
||||
/** The composer input and Stop are both fully on screen. */
|
||||
export async function expectComposerOnScreen(page: Page): Promise<void> {
|
||||
await expect(composerLocator(page)).toBeInViewport({ ratio: 1 });
|
||||
await expect(agentStopButton(page)).toBeInViewport({ ratio: 1 });
|
||||
}
|
||||
|
||||
/** Turns the mouse wheel over one row, as a user does to move through the queue. */
|
||||
export async function scrollQueueFrom(page: Page, text: string, deltaY: number): Promise<void> {
|
||||
await queuedRow(page, text).hover();
|
||||
await page.mouse.wheel(0, deltaY);
|
||||
}
|
||||
|
||||
/** The icon leading a row's "Sent by" line is drawn at its full width. */
|
||||
export async function expectSenderIconUnsquashed(row: Locator): Promise<void> {
|
||||
const icon = await row.locator("svg").first().boundingBox();
|
||||
if (!icon) throw new Error("The row has no visible sender icon");
|
||||
expect(icon.width).toBeGreaterThanOrEqual(icon.height);
|
||||
}
|
||||
|
||||
/** The queued prompt reached the transcript exactly once and left the queue. */
|
||||
export async function expectDeliveredOnce(page: Page, text: string): Promise<void> {
|
||||
await expect(page.getByTestId("user-message").filter({ hasText: text })).toHaveCount(1, {
|
||||
timeout: 30_000,
|
||||
});
|
||||
await expect(queuedRow(page, text)).toHaveCount(0);
|
||||
}
|
||||
|
||||
export async function expectDeliveredImage(page: Page, text: string): Promise<void> {
|
||||
await expect(
|
||||
page
|
||||
.getByTestId("user-message")
|
||||
.filter({ hasText: text })
|
||||
.getByRole("button", { name: "Open image attachment" }),
|
||||
).toHaveCount(1);
|
||||
}
|
||||
|
||||
/** A page opened after the first one was closed, with the same stored app data. */
|
||||
export async function reopenAgent(page: Page, agent: AgentWithOpenTurn): Promise<Page> {
|
||||
const reopened = await page.context().newPage();
|
||||
await hideDeveloperToasts(reopened);
|
||||
await openAgentRoute(reopened, agent);
|
||||
return reopened;
|
||||
}
|
||||
|
||||
/** A second client of the same host: its own browser context and its own client id. */
|
||||
export async function openSecondClient(
|
||||
browser: Browser,
|
||||
page: Page,
|
||||
agent: AgentWithOpenTurn,
|
||||
): Promise<{ page: Page; close(): Promise<void> }> {
|
||||
const context = await browser.newContext({ storageState: await page.context().storageState() });
|
||||
const second = await context.newPage();
|
||||
await second.addInitScript(() => localStorage.removeItem("@paseo:client-id-v1"));
|
||||
await hideDeveloperToasts(second);
|
||||
await openAgentRoute(second, agent);
|
||||
return { page: second, close: () => context.close() };
|
||||
}
|
||||
@@ -103,13 +103,8 @@ export async function expectQueuedMessageButton(page: Page): Promise<void> {
|
||||
});
|
||||
}
|
||||
|
||||
/** The composer's Stop button. Queued rows also have a Cancel button, so match the whole name. */
|
||||
export function agentStopButton(page: Page) {
|
||||
return page.getByRole("button", { name: /^(stop|canceling) agent$/i });
|
||||
}
|
||||
|
||||
export async function cancelAgent(page: Page): Promise<void> {
|
||||
const stopButton = agentStopButton(page).first();
|
||||
const stopButton = page.getByRole("button", { name: /stop|cancel/i }).first();
|
||||
await expect(stopButton).toBeVisible({ timeout: 10_000 });
|
||||
await stopButton.click();
|
||||
}
|
||||
@@ -305,7 +300,9 @@ export async function startRunningMockAgent(
|
||||
await page.goto(agentUrl);
|
||||
await expectComposerVisible(page);
|
||||
await client.sendAgentMessage(agent.id, opts.prompt);
|
||||
await expect(agentStopButton(page).first()).toBeVisible({ timeout: 30_000 });
|
||||
await expect(page.getByRole("button", { name: /stop|cancel/i }).first()).toBeVisible({
|
||||
timeout: 30_000,
|
||||
});
|
||||
return {
|
||||
client,
|
||||
repo,
|
||||
@@ -470,12 +467,6 @@ export async function configureComposerQueueSend(page: Page): Promise<void> {
|
||||
);
|
||||
}
|
||||
|
||||
export async function configureComposerInterruptSend(page: Page): Promise<void> {
|
||||
await page.addInitScript(() =>
|
||||
localStorage.setItem("@paseo:app-settings", JSON.stringify({ sendBehavior: "interrupt" })),
|
||||
);
|
||||
}
|
||||
|
||||
/** Drive the real tab chooser's commands even when fullscreen covers its pointer surface.
|
||||
* This exercises retained activity changes, not a claim that covered chrome is clickable.
|
||||
*/
|
||||
|
||||
@@ -168,11 +168,6 @@ export interface SeedDaemonClient {
|
||||
timeout?: number,
|
||||
): Promise<{ status: string }>;
|
||||
cancelAgent(agentId: string): Promise<void>;
|
||||
respondToPermission(
|
||||
agentId: string,
|
||||
requestId: string,
|
||||
response: { behavior: "allow" },
|
||||
): Promise<void>;
|
||||
sendAgentMessage(
|
||||
agentId: string,
|
||||
text: string,
|
||||
@@ -187,9 +182,9 @@ export interface SeedDaemonClient {
|
||||
): Promise<{ status: string; final?: { lastError?: string | null } | null }>;
|
||||
archiveAgent(agentId: string): Promise<{ archivedAt: string }>;
|
||||
refreshAgent(agentId: string): Promise<unknown>;
|
||||
fetchAgent(options: { agentId: string }): Promise<{
|
||||
agent: { id: string; archivedAt?: string | null; pendingPermissions: Array<{ id: string }> };
|
||||
} | null>;
|
||||
fetchAgent(options: {
|
||||
agentId: string;
|
||||
}): Promise<{ agent: { id: string; archivedAt?: string | null } } | null>;
|
||||
getLastServerInfoMessage(): {
|
||||
features?: {
|
||||
projectAdd?: boolean;
|
||||
|
||||
@@ -258,37 +258,8 @@ export async function expectAddHostFieldDrawnAsInput(page: Page, testId: string)
|
||||
await expect(field).not.toHaveCSS("background-color", "rgba(0, 0, 0, 0)");
|
||||
}
|
||||
|
||||
function directConnectionModeSegment(page: Page, mode: "Form" | "URI") {
|
||||
return page.getByTestId("direct-mode").getByRole("button", { name: mode, exact: true });
|
||||
}
|
||||
|
||||
export async function selectDirectConnectionMode(page: Page, mode: "Form" | "URI"): Promise<void> {
|
||||
await directConnectionModeSegment(page, mode).click();
|
||||
await expectDirectConnectionMode(page, mode);
|
||||
}
|
||||
|
||||
export async function expectDirectConnectionMode(page: Page, mode: "Form" | "URI"): Promise<void> {
|
||||
await expect(directConnectionModeSegment(page, mode)).toHaveAttribute("aria-selected", "true");
|
||||
}
|
||||
|
||||
export async function expectDirectFormModeDisabled(page: Page): Promise<void> {
|
||||
await expect(directConnectionModeSegment(page, "Form")).toBeDisabled();
|
||||
}
|
||||
|
||||
export async function connectDirectHost(page: Page): Promise<void> {
|
||||
await page.getByTestId("direct-host-submit").click();
|
||||
await expect(page.getByTestId("add-host-modal")).toHaveCount(0, { timeout: 30_000 });
|
||||
}
|
||||
|
||||
export async function connectDirectHostExpectingPassword(page: Page, host: string): Promise<void> {
|
||||
await page.getByTestId("direct-host-submit").click();
|
||||
await expect(page.getByText(`Password for ${host}`, { exact: true })).toBeVisible({
|
||||
timeout: 30_000,
|
||||
});
|
||||
}
|
||||
|
||||
export async function fillDirectHostPromptPassword(page: Page, password: string): Promise<void> {
|
||||
await page.getByRole("textbox", { name: "Host password", exact: true }).fill(password);
|
||||
export async function toggleHostAdvanced(page: Page): Promise<void> {
|
||||
await page.getByTestId("direct-host-advanced-toggle").click();
|
||||
}
|
||||
|
||||
export async function openCompactSettings(page: Page, expectedStartRoute: string): Promise<void> {
|
||||
@@ -451,10 +422,6 @@ export async function fillDirectHostAddress(page: Page, host: string, port: stri
|
||||
await page.getByRole("textbox", { name: "Port", exact: true }).fill(port);
|
||||
}
|
||||
|
||||
export async function pasteIntoDirectHost(page: Page, text: string): Promise<void> {
|
||||
await page.getByRole("textbox", { name: "Host", exact: true }).fill(text);
|
||||
}
|
||||
|
||||
export async function toggleDirectHostSsl(page: Page): Promise<void> {
|
||||
await page.getByRole("checkbox", { name: "Use SSL", exact: true }).click();
|
||||
}
|
||||
@@ -472,12 +439,6 @@ export async function expectDirectHostUriHidden(page: Page): Promise<void> {
|
||||
await expect(page.getByTestId("direct-host-uri-input")).toHaveCount(0);
|
||||
}
|
||||
|
||||
/** The whole form shows above Cancel and Connect, with nothing cut off by the footer. */
|
||||
export async function expectDirectFormFullyVisible(page: Page): Promise<void> {
|
||||
await expect(page.getByTestId("direct-password-input")).toBeInViewport({ ratio: 1 });
|
||||
await expect(page.getByTestId("direct-password-visibility-toggle")).toBeInViewport({ ratio: 1 });
|
||||
}
|
||||
|
||||
export async function expectDiagnosticsContent(page: Page): Promise<void> {
|
||||
await expect(page.getByRole("button", { name: "Run" })).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: "Play test" })).toBeVisible();
|
||||
|
||||
@@ -63,8 +63,6 @@ using namespace facebook::react;
|
||||
- (instancetype)initWithFrame:(CGRect)frame
|
||||
{
|
||||
if (self = [super initWithFrame:frame]) {
|
||||
// The iOS status-bar tap region can overlap app header buttons (#11027).
|
||||
self.scrollView.scrollsToTop = NO;
|
||||
#if defined(__IPHONE_26_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_26_0
|
||||
if (@available(iOS 26.0, *)) {
|
||||
UIScrollView *scrollView = self.scrollView;
|
||||
|
||||
@@ -3,12 +3,9 @@ import { useTranslation } from "react-i18next";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import { useProviderIcon } from "@/components/provider-icons";
|
||||
import type { PanelDescriptor } from "@/panels/panel-registry";
|
||||
import { resolveAgentLabel } from "@/panels/tab-labels";
|
||||
import { useSessionStore, selectAgentTurnPresentation, type Agent } from "@/stores/session-store";
|
||||
import { deriveSidebarStateBucket } from "@/utils/sidebar-agent-state";
|
||||
|
||||
export { resolveAgentLabel };
|
||||
|
||||
function formatProviderLabel(provider: Agent["provider"]): string {
|
||||
if (!provider) {
|
||||
return "Agent";
|
||||
@@ -20,6 +17,20 @@ function formatProviderLabel(provider: Agent["provider"]): string {
|
||||
.join(" ");
|
||||
}
|
||||
|
||||
export function resolveAgentLabel(title: string | null | undefined): string | null {
|
||||
if (typeof title !== "string") {
|
||||
return null;
|
||||
}
|
||||
const normalized = title.trim();
|
||||
if (!normalized) {
|
||||
return null;
|
||||
}
|
||||
if (normalized.toLowerCase() === "new agent") {
|
||||
return null;
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
export function useAgentDescriptor(
|
||||
target: { kind: "agent"; agentId: string },
|
||||
context: { serverId: string },
|
||||
|
||||
@@ -23,15 +23,7 @@ export interface DraftAgentProfileControls {
|
||||
}
|
||||
|
||||
export type AgentProfileApplyTarget =
|
||||
| {
|
||||
kind: "agent";
|
||||
agentId: string;
|
||||
availableModeIds: readonly string[] | null;
|
||||
currentProvider?: string | null;
|
||||
isSwitchInFlight?: () => boolean;
|
||||
onApplySameProvider?: () => void;
|
||||
onStageProviderSwitch?: (profile: MaterializedAgentProfile) => void;
|
||||
}
|
||||
| { kind: "agent"; agentId: string; availableModeIds: readonly string[] | null }
|
||||
| { kind: "draft"; controls: DraftAgentProfileControls };
|
||||
|
||||
/** Everything the model picker renders for one profile. It never sees the profile itself. */
|
||||
@@ -156,16 +148,6 @@ export function useAgentProfilePicker(
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
target.onStageProviderSwitch &&
|
||||
(target.isSwitchInFlight?.() ||
|
||||
(target.currentProvider && resolved.provider !== target.currentProvider))
|
||||
) {
|
||||
target.onStageProviderSwitch(resolved);
|
||||
return;
|
||||
}
|
||||
|
||||
target.onApplySameProvider?.();
|
||||
const reconciled = reconcileMaterializedProfileMode(resolved, target.availableModeIds);
|
||||
if (!reconciled) {
|
||||
return;
|
||||
@@ -175,11 +157,7 @@ export function useAgentProfilePicker(
|
||||
return;
|
||||
}
|
||||
void client
|
||||
.applyAgentConfig(
|
||||
target.agentId,
|
||||
toAgentConfigApply(reconciled),
|
||||
target.currentProvider ? { expectedProvider: target.currentProvider } : undefined,
|
||||
)
|
||||
.applyAgentConfig(target.agentId, toAgentConfigApply(reconciled))
|
||||
.then((notice) => showProviderNoticeToast(toast, notice))
|
||||
.catch((error) => {
|
||||
console.warn("[useAgentProfilePicker] applyAgentConfig failed", error);
|
||||
|
||||
@@ -1,161 +0,0 @@
|
||||
import { expect, test } from "vitest";
|
||||
import type { PaseoAgentQueueItem } from "@getpaseo/client";
|
||||
import type { SessionOutboundMessage } from "@getpaseo/protocol/messages";
|
||||
import { createHostAgentQueueModel } from "./host";
|
||||
|
||||
interface Observer {
|
||||
snapshot(): void;
|
||||
update(message: SessionOutboundMessage): void;
|
||||
error(error: unknown): void;
|
||||
}
|
||||
|
||||
function item(id: string): PaseoAgentQueueItem {
|
||||
return {
|
||||
id,
|
||||
seq: 1,
|
||||
enqueuedAt: "2026-11-30T00:00:00.000Z",
|
||||
text: `message ${id}`,
|
||||
sender: { kind: "user" },
|
||||
held: false,
|
||||
state: "queued",
|
||||
};
|
||||
}
|
||||
|
||||
/** A host runtime plus the daemon client it hands out. */
|
||||
function fakeHost(options: { supportsQueue: boolean }) {
|
||||
let connected = false;
|
||||
let notify = () => {};
|
||||
const observers: Observer[] = [];
|
||||
const calls: unknown[][] = [];
|
||||
let releases = 0;
|
||||
let queue = [item("a")];
|
||||
const client = {
|
||||
getLastServerInfoMessage: () =>
|
||||
connected ? { features: { agentMessageQueue: options.supportsQueue } } : null,
|
||||
listAgentQueue: async (agentId: string) => {
|
||||
calls.push(["list", agentId]);
|
||||
return { held: false, items: queue };
|
||||
},
|
||||
withdrawAgentQueueItem: async (agentId: string, messageId: string) => {
|
||||
calls.push(["withdraw", agentId, messageId]);
|
||||
return { withdrawn: true as const, item: item(messageId) };
|
||||
},
|
||||
promoteAgentQueueItem: async (agentId: string, messageId: string, behavior: string) => {
|
||||
calls.push(["promote", agentId, messageId, behavior]);
|
||||
return { promoted: true as const };
|
||||
},
|
||||
observeAgentQueue: () => ({
|
||||
subscribe: (observer: Observer) => {
|
||||
observers.push(observer);
|
||||
},
|
||||
release: async () => {
|
||||
releases++;
|
||||
},
|
||||
}),
|
||||
};
|
||||
return {
|
||||
host: {
|
||||
getClient: () => client,
|
||||
subscribe: (listener: () => void) => {
|
||||
notify = listener;
|
||||
return () => {};
|
||||
},
|
||||
},
|
||||
observers,
|
||||
calls,
|
||||
releases: () => releases,
|
||||
setQueue: (next: PaseoAgentQueueItem[]) => {
|
||||
queue = next;
|
||||
},
|
||||
connect: () => {
|
||||
connected = true;
|
||||
notify();
|
||||
},
|
||||
disconnect: () => {
|
||||
connected = false;
|
||||
notify();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function settle(): Promise<void> {
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
}
|
||||
|
||||
function queueUpdate(agentId: string, items: PaseoAgentQueueItem[]): SessionOutboundMessage {
|
||||
return { type: "agent.queue.update", payload: { agentId, held: false, items } };
|
||||
}
|
||||
|
||||
test("lists on connect, follows its own agent's updates, and lists again on reconnect", async () => {
|
||||
const runtime = fakeHost({ supportsQueue: true });
|
||||
const model = createHostAgentQueueModel("host", "agent", runtime.host);
|
||||
const unsubscribe = model.subscribe(() => {});
|
||||
expect(runtime.observers).toHaveLength(0);
|
||||
|
||||
runtime.connect();
|
||||
runtime.observers[0].snapshot();
|
||||
await settle();
|
||||
expect(model.getSnapshot()).toMatchObject({ status: "ready", items: [item("a")] });
|
||||
|
||||
runtime.observers[0].update(queueUpdate("other-agent", []));
|
||||
expect(model.getSnapshot().items).toEqual([item("a")]);
|
||||
runtime.observers[0].update(queueUpdate("agent", [item("a"), item("b")]));
|
||||
expect(model.getSnapshot().items).toEqual([item("a"), item("b")]);
|
||||
|
||||
runtime.disconnect();
|
||||
expect(model.getSnapshot()).toMatchObject({ status: "stale", items: [item("a"), item("b")] });
|
||||
expect(runtime.releases()).toBe(1);
|
||||
|
||||
runtime.setQueue([]);
|
||||
runtime.connect();
|
||||
runtime.observers[1].snapshot();
|
||||
await settle();
|
||||
expect(model.getSnapshot()).toMatchObject({ status: "ready", items: [] });
|
||||
runtime.observers[0].update(queueUpdate("agent", [item("late")]));
|
||||
expect(model.getSnapshot().items).toEqual([]);
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
test("sends withdraw and promote for the observed agent", async () => {
|
||||
const runtime = fakeHost({ supportsQueue: true });
|
||||
const model = createHostAgentQueueModel("host", "agent", runtime.host);
|
||||
const unsubscribe = model.subscribe(() => {});
|
||||
runtime.connect();
|
||||
runtime.observers[0].update(queueUpdate("agent", [item("a"), item("b")]));
|
||||
|
||||
await model.promote("b", "interrupt");
|
||||
await model.withdraw("a");
|
||||
|
||||
expect(runtime.calls).toEqual([
|
||||
["promote", "agent", "b", "interrupt"],
|
||||
["withdraw", "agent", "a"],
|
||||
]);
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
test("rejects a command while the host is disconnected", async () => {
|
||||
const runtime = fakeHost({ supportsQueue: true });
|
||||
const model = createHostAgentQueueModel("host", "agent", runtime.host);
|
||||
const unsubscribe = model.subscribe(() => {});
|
||||
runtime.connect();
|
||||
runtime.observers[0].update(queueUpdate("agent", [item("a")]));
|
||||
runtime.disconnect();
|
||||
|
||||
await expect(model.withdraw("a")).rejects.toThrow("Host disconnected");
|
||||
expect(runtime.calls).toEqual([]);
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
test("has no queue and asks nothing of a host without the feature", async () => {
|
||||
const runtime = fakeHost({ supportsQueue: false });
|
||||
const model = createHostAgentQueueModel("host", "agent", runtime.host);
|
||||
const unsubscribe = model.subscribe(() => {});
|
||||
|
||||
runtime.connect();
|
||||
await settle();
|
||||
|
||||
expect(model.getSnapshot()).toMatchObject({ status: "ready", items: [] });
|
||||
expect(runtime.observers).toHaveLength(0);
|
||||
expect(runtime.calls).toEqual([]);
|
||||
unsubscribe();
|
||||
});
|
||||
@@ -1,118 +0,0 @@
|
||||
import type {
|
||||
PaseoAgentQueuePromoteResult,
|
||||
PaseoAgentQueueState,
|
||||
PaseoAgentQueueWithdrawResult,
|
||||
} from "@getpaseo/client";
|
||||
import type { ActiveTurnBehavior, SessionOutboundMessage } from "@getpaseo/protocol/messages";
|
||||
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
||||
import { createAgentQueueModel, type AgentQueueModel } from "./model";
|
||||
|
||||
interface AgentQueueClient {
|
||||
getLastServerInfoMessage(): { features?: { agentMessageQueue?: boolean } | null } | null;
|
||||
listAgentQueue(agentId: string): Promise<PaseoAgentQueueState>;
|
||||
withdrawAgentQueueItem(
|
||||
agentId: string,
|
||||
messageId: string,
|
||||
): Promise<PaseoAgentQueueWithdrawResult>;
|
||||
promoteAgentQueueItem(
|
||||
agentId: string,
|
||||
messageId: string,
|
||||
activeTurnBehavior: ActiveTurnBehavior,
|
||||
): Promise<PaseoAgentQueuePromoteResult>;
|
||||
observeAgentQueue(): {
|
||||
subscribe(observer: {
|
||||
snapshot(): void;
|
||||
update(message: SessionOutboundMessage): void;
|
||||
error(error: unknown): void;
|
||||
}): unknown;
|
||||
release(): Promise<void>;
|
||||
};
|
||||
}
|
||||
|
||||
interface AgentQueueHost {
|
||||
getClient(): AgentQueueClient | null;
|
||||
subscribe(listener: () => void): () => void;
|
||||
}
|
||||
|
||||
function hostFor(serverId: string): AgentQueueHost {
|
||||
const host = getHostRuntimeStore();
|
||||
return {
|
||||
getClient: () => host.getSnapshot(serverId)?.client ?? null,
|
||||
subscribe: (listener) => host.subscribe(serverId, listener),
|
||||
};
|
||||
}
|
||||
|
||||
export function createHostAgentQueueModel(
|
||||
serverId: string,
|
||||
agentId: string,
|
||||
host: AgentQueueHost = hostFor(serverId),
|
||||
): AgentQueueModel {
|
||||
let client: AgentQueueClient | null = null;
|
||||
const connected = () => {
|
||||
if (!client) throw new Error("Host disconnected");
|
||||
return client;
|
||||
};
|
||||
return createAgentQueueModel({
|
||||
list: async () => connected().listAgentQueue(agentId),
|
||||
withdraw: async (messageId) => connected().withdrawAgentQueueItem(agentId, messageId),
|
||||
promote: async (messageId, activeTurnBehavior) =>
|
||||
connected().promoteAgentQueueItem(agentId, messageId, activeTurnBehavior),
|
||||
observe: ({ snapshot, update, disconnected, failed }) => {
|
||||
let release: (() => void) | undefined;
|
||||
let currentObservation: ReturnType<AgentQueueClient["observeAgentQueue"]> | undefined;
|
||||
const sync = () => {
|
||||
const candidate = host.getClient();
|
||||
// The runtime keeps the client across reconnects, but clears server info until handshake.
|
||||
const next = candidate?.getLastServerInfoMessage() ? candidate : null;
|
||||
if (next === client) return;
|
||||
const previousRelease = release;
|
||||
client = next;
|
||||
release = undefined;
|
||||
disconnected();
|
||||
previousRelease?.();
|
||||
if (!client) return;
|
||||
// COMPAT(agentMessageQueue): added in v0.18.2, remove gate after 2027-06-01.
|
||||
if (client.getLastServerInfoMessage()?.features?.agentMessageQueue !== true) {
|
||||
update({ held: false, items: [] });
|
||||
return;
|
||||
}
|
||||
const observedClient = client;
|
||||
const observation = client.observeAgentQueue();
|
||||
currentObservation = observation;
|
||||
const isCurrent = () => client === observedClient && currentObservation === observation;
|
||||
observation.subscribe({
|
||||
snapshot: () => {
|
||||
if (isCurrent()) snapshot();
|
||||
},
|
||||
update: (message) => {
|
||||
if (
|
||||
isCurrent() &&
|
||||
message.type === "agent.queue.update" &&
|
||||
message.payload.agentId === agentId
|
||||
) {
|
||||
update({ held: message.payload.held, items: message.payload.items });
|
||||
}
|
||||
},
|
||||
error: () => {
|
||||
if (isCurrent()) failed();
|
||||
},
|
||||
});
|
||||
release = () => {
|
||||
if (currentObservation === observation) currentObservation = undefined;
|
||||
void observation
|
||||
.release()
|
||||
.catch((error: unknown) =>
|
||||
console.error("Agent queue subscription cleanup failed", error),
|
||||
);
|
||||
};
|
||||
};
|
||||
const unsubscribe = host.subscribe(sync);
|
||||
sync();
|
||||
return () => {
|
||||
unsubscribe();
|
||||
client = null;
|
||||
release?.();
|
||||
};
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
import { useMemo, useSyncExternalStore } from "react";
|
||||
import { createHostAgentQueueModel } from "./host";
|
||||
import type { AgentQueueModel, AgentQueueSnapshot } from "./model";
|
||||
|
||||
export type { AgentQueueModel, AgentQueueSnapshot } from "./model";
|
||||
|
||||
/** Observes one agent's queue for as long as the caller is mounted. */
|
||||
export function useAgentQueue(
|
||||
serverId: string,
|
||||
agentId: string,
|
||||
): { model: AgentQueueModel; queue: AgentQueueSnapshot } {
|
||||
const model = useMemo(() => createHostAgentQueueModel(serverId, agentId), [serverId, agentId]);
|
||||
const queue = useSyncExternalStore(model.subscribe, model.getSnapshot, model.getSnapshot);
|
||||
return { model, queue };
|
||||
}
|
||||
@@ -1,210 +0,0 @@
|
||||
import { expect, test } from "vitest";
|
||||
import type {
|
||||
PaseoAgentQueueItem,
|
||||
PaseoAgentQueueState,
|
||||
PaseoAgentQueueWithdrawResult,
|
||||
} from "@getpaseo/client";
|
||||
import { createAgentQueueModel, type AgentQueuePort } from "./model";
|
||||
|
||||
function item(id: string, patch: Partial<PaseoAgentQueueItem> = {}): PaseoAgentQueueItem {
|
||||
return {
|
||||
id,
|
||||
seq: 1,
|
||||
enqueuedAt: "2026-11-30T00:00:00.000Z",
|
||||
text: `message ${id}`,
|
||||
sender: { kind: "user" },
|
||||
held: false,
|
||||
state: "queued",
|
||||
...patch,
|
||||
};
|
||||
}
|
||||
|
||||
interface Deferred<T> {
|
||||
promise: Promise<T>;
|
||||
resolve(value: T): void;
|
||||
reject(error: Error): void;
|
||||
}
|
||||
|
||||
function deferred<T>(): Deferred<T> {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (error: Error) => void;
|
||||
const promise = new Promise<T>((done, fail) => {
|
||||
resolve = done;
|
||||
reject = fail;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
/** A host queue the test drives: it records commands and answers them when told to. */
|
||||
function fakeQueueHost() {
|
||||
const lists: Deferred<PaseoAgentQueueState>[] = [];
|
||||
const withdrawals: Array<{ messageId: string } & Deferred<PaseoAgentQueueWithdrawResult>> = [];
|
||||
const promotions: Array<{ messageId: string; behavior: string }> = [];
|
||||
let callbacks: Parameters<AgentQueuePort["observe"]>[0] | null = null;
|
||||
const port: AgentQueuePort = {
|
||||
list: () => {
|
||||
const read = deferred<PaseoAgentQueueState>();
|
||||
lists.push(read);
|
||||
return read.promise;
|
||||
},
|
||||
withdraw: (messageId) => {
|
||||
const request = deferred<PaseoAgentQueueWithdrawResult>();
|
||||
withdrawals.push({ messageId, ...request });
|
||||
return request.promise;
|
||||
},
|
||||
promote: async (messageId, behavior) => {
|
||||
promotions.push({ messageId, behavior });
|
||||
return { promoted: true };
|
||||
},
|
||||
observe: (next) => {
|
||||
callbacks = next;
|
||||
return () => {
|
||||
callbacks = null;
|
||||
};
|
||||
},
|
||||
};
|
||||
return {
|
||||
port,
|
||||
lists,
|
||||
withdrawals,
|
||||
promotions,
|
||||
isObserved: () => callbacks !== null,
|
||||
connect: () => callbacks?.snapshot(),
|
||||
disconnect: () => callbacks?.disconnected(),
|
||||
fail: () => callbacks?.failed(),
|
||||
publish: (queue: PaseoAgentQueueState) => callbacks?.update(queue),
|
||||
};
|
||||
}
|
||||
|
||||
async function settle(): Promise<void> {
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
}
|
||||
|
||||
test("hydrates the queue the host holds when observation starts", async () => {
|
||||
const host = fakeQueueHost();
|
||||
const model = createAgentQueueModel(host.port);
|
||||
const unsubscribe = model.subscribe(() => {});
|
||||
expect(model.getSnapshot()).toMatchObject({ status: "loading", held: false, items: [] });
|
||||
|
||||
host.connect();
|
||||
host.lists[0].resolve({ held: true, items: [item("a", { held: true })] });
|
||||
await settle();
|
||||
|
||||
expect(model.getSnapshot()).toMatchObject({
|
||||
status: "ready",
|
||||
held: true,
|
||||
items: [item("a", { held: true })],
|
||||
});
|
||||
unsubscribe();
|
||||
expect(host.isObserved()).toBe(false);
|
||||
});
|
||||
|
||||
test("replaces the whole queue with each live update, ahead of a slower list", async () => {
|
||||
const host = fakeQueueHost();
|
||||
const model = createAgentQueueModel(host.port);
|
||||
const unsubscribe = model.subscribe(() => {});
|
||||
host.connect();
|
||||
|
||||
host.publish({ held: false, items: [item("a"), item("b", { seq: 2 })] });
|
||||
host.lists[0].resolve({ held: false, items: [] });
|
||||
await settle();
|
||||
|
||||
expect(model.getSnapshot().items.map((entry) => entry.id)).toEqual(["a", "b"]);
|
||||
host.publish({ held: false, items: [item("b", { seq: 2 })] });
|
||||
expect(model.getSnapshot().items.map((entry) => entry.id)).toEqual(["b"]);
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
test("keeps the last rows while disconnected and reads the queue again on reconnect", async () => {
|
||||
const host = fakeQueueHost();
|
||||
const model = createAgentQueueModel(host.port);
|
||||
const unsubscribe = model.subscribe(() => {});
|
||||
host.connect();
|
||||
host.lists[0].resolve({ held: false, items: [item("a")] });
|
||||
await settle();
|
||||
|
||||
host.disconnect();
|
||||
expect(model.getSnapshot()).toMatchObject({ status: "stale", items: [item("a")] });
|
||||
host.connect();
|
||||
host.lists[1].resolve({ held: false, items: [] });
|
||||
await settle();
|
||||
|
||||
expect(model.getSnapshot()).toMatchObject({ status: "ready", items: [] });
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
test("offers a retry when the queue cannot be read", async () => {
|
||||
const host = fakeQueueHost();
|
||||
const model = createAgentQueueModel(host.port);
|
||||
const unsubscribe = model.subscribe(() => {});
|
||||
host.connect();
|
||||
host.lists[0].reject(new Error("timeout"));
|
||||
await settle();
|
||||
expect(model.getSnapshot().status).toBe("error");
|
||||
|
||||
model.retry();
|
||||
host.lists[1].resolve({ held: false, items: [item("a")] });
|
||||
await settle();
|
||||
|
||||
expect(model.getSnapshot()).toMatchObject({ status: "ready", items: [item("a")] });
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
test("marks a row busy while it is withdrawn and returns the withdrawn message", async () => {
|
||||
const host = fakeQueueHost();
|
||||
const model = createAgentQueueModel(host.port);
|
||||
const unsubscribe = model.subscribe(() => {});
|
||||
host.publish({ held: false, items: [item("a"), item("b", { seq: 2 })] });
|
||||
|
||||
const first = model.withdraw("a");
|
||||
const second = model.withdraw("a");
|
||||
expect(model.getSnapshot().busy).toEqual(new Set(["a"]));
|
||||
host.withdrawals[0].resolve({ withdrawn: true, item: item("a") });
|
||||
|
||||
expect(await first).toEqual({ withdrawn: true, item: item("a") });
|
||||
expect(await second).toBeNull();
|
||||
expect(host.withdrawals).toHaveLength(1);
|
||||
expect(model.getSnapshot().busy).toEqual(new Set());
|
||||
expect(model.getSnapshot().items.map((entry) => entry.id)).toEqual(["b"]);
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
test("keeps the row when the host already started sending it", async () => {
|
||||
const host = fakeQueueHost();
|
||||
const model = createAgentQueueModel(host.port);
|
||||
const unsubscribe = model.subscribe(() => {});
|
||||
host.publish({ held: false, items: [item("a")] });
|
||||
|
||||
const result = model.withdraw("a");
|
||||
host.withdrawals[0].resolve({ withdrawn: false, reason: "already_dispatching" });
|
||||
|
||||
expect(await result).toEqual({ withdrawn: false, reason: "already_dispatching" });
|
||||
expect(model.getSnapshot().items.map((entry) => entry.id)).toEqual(["a"]);
|
||||
expect(model.getSnapshot().busy).toEqual(new Set());
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
test("releases the row and reports the error when a command fails", async () => {
|
||||
const host = fakeQueueHost();
|
||||
const model = createAgentQueueModel(host.port);
|
||||
const unsubscribe = model.subscribe(() => {});
|
||||
host.publish({ held: false, items: [item("a")] });
|
||||
|
||||
const result = model.withdraw("a");
|
||||
host.withdrawals[0].reject(new Error("Host disconnected"));
|
||||
|
||||
await expect(result).rejects.toThrow("Host disconnected");
|
||||
expect(model.getSnapshot().busy).toEqual(new Set());
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
test("promotes a row with the chosen send behavior", async () => {
|
||||
const host = fakeQueueHost();
|
||||
const model = createAgentQueueModel(host.port);
|
||||
const unsubscribe = model.subscribe(() => {});
|
||||
host.publish({ held: true, items: [item("a", { held: true })] });
|
||||
|
||||
expect(await model.promote("a", "steer")).toEqual({ promoted: true });
|
||||
expect(host.promotions).toEqual([{ messageId: "a", behavior: "steer" }]);
|
||||
unsubscribe();
|
||||
});
|
||||
@@ -1,145 +0,0 @@
|
||||
import type {
|
||||
PaseoAgentQueueItem,
|
||||
PaseoAgentQueuePromoteResult,
|
||||
PaseoAgentQueueState,
|
||||
PaseoAgentQueueWithdrawResult,
|
||||
} from "@getpaseo/client";
|
||||
import type { ActiveTurnBehavior } from "@getpaseo/protocol/messages";
|
||||
|
||||
export interface AgentQueuePort {
|
||||
list(): Promise<PaseoAgentQueueState>;
|
||||
withdraw(messageId: string): Promise<PaseoAgentQueueWithdrawResult>;
|
||||
promote(
|
||||
messageId: string,
|
||||
activeTurnBehavior: ActiveTurnBehavior,
|
||||
): Promise<PaseoAgentQueuePromoteResult>;
|
||||
observe(callbacks: {
|
||||
snapshot(): void;
|
||||
disconnected(): void;
|
||||
failed(): void;
|
||||
update(queue: PaseoAgentQueueState): void;
|
||||
}): () => void;
|
||||
}
|
||||
|
||||
export interface AgentQueueSnapshot {
|
||||
status: "loading" | "stale" | "ready" | "error";
|
||||
/** The host waits for Send now or the next prompt before it sends these. */
|
||||
held: boolean;
|
||||
/** Admission order. The first row is sent next. */
|
||||
items: PaseoAgentQueueItem[];
|
||||
/** Rows with a command in flight. */
|
||||
busy: ReadonlySet<string>;
|
||||
}
|
||||
|
||||
/**
|
||||
* One agent's queue as the host holds it. The host is the only writer: every update replaces
|
||||
* the rows, and a command changes nothing here until the host answers it.
|
||||
*/
|
||||
export function createAgentQueueModel(port: AgentQueuePort) {
|
||||
let state: AgentQueueSnapshot = {
|
||||
status: "loading",
|
||||
held: false,
|
||||
items: [],
|
||||
busy: new Set(),
|
||||
};
|
||||
let hasRead = false;
|
||||
let sequence = 0;
|
||||
let stop: (() => void) | undefined;
|
||||
let observationFailed = false;
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
const publish = (patch: Partial<AgentQueueSnapshot>) => {
|
||||
state = { ...state, ...patch };
|
||||
for (const listener of listeners) listener();
|
||||
};
|
||||
const replace = (queue: PaseoAgentQueueState) => {
|
||||
hasRead = true;
|
||||
publish({ status: "ready", held: queue.held, items: queue.items });
|
||||
};
|
||||
const pending = () => (hasRead ? "stale" : "loading");
|
||||
const refresh = async () => {
|
||||
const request = ++sequence;
|
||||
publish({ status: pending() });
|
||||
try {
|
||||
const queue = await port.list();
|
||||
if (request === sequence) replace(queue);
|
||||
} catch {
|
||||
if (request === sequence) publish({ status: "error" });
|
||||
}
|
||||
};
|
||||
const start = () => {
|
||||
observationFailed = false;
|
||||
stop = port.observe({
|
||||
snapshot: () => {
|
||||
void refresh();
|
||||
},
|
||||
disconnected: () => {
|
||||
sequence++;
|
||||
publish({ status: pending() });
|
||||
},
|
||||
failed: () => {
|
||||
observationFailed = true;
|
||||
sequence++;
|
||||
publish({ status: "error" });
|
||||
},
|
||||
update: (queue) => {
|
||||
sequence++;
|
||||
replace(queue);
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
/** Runs one command per row at a time. Returns null when the row cannot take one. */
|
||||
const command = async <T>(messageId: string, run: () => Promise<T>): Promise<T | null> => {
|
||||
const row = state.items.find((entry) => entry.id === messageId);
|
||||
if (!row || row.state === "dispatching" || state.busy.has(messageId)) return null;
|
||||
publish({ busy: new Set(state.busy).add(messageId) });
|
||||
try {
|
||||
return await run();
|
||||
} finally {
|
||||
const busy = new Set(state.busy);
|
||||
busy.delete(messageId);
|
||||
publish({ busy });
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
getSnapshot: () => state,
|
||||
withdraw: (messageId: string) =>
|
||||
command(messageId, async () => {
|
||||
const result = await port.withdraw(messageId);
|
||||
// The host confirmed the removal. Drop the row now so it is not pressable again
|
||||
// between this answer and the next update.
|
||||
if (result.withdrawn) {
|
||||
publish({ items: state.items.filter((entry) => entry.id !== messageId) });
|
||||
}
|
||||
return result;
|
||||
}),
|
||||
promote: (messageId: string, activeTurnBehavior: ActiveTurnBehavior) =>
|
||||
command(messageId, () => port.promote(messageId, activeTurnBehavior)),
|
||||
retry: () => {
|
||||
if (observationFailed) {
|
||||
stop?.();
|
||||
stop = undefined;
|
||||
publish({ status: pending() });
|
||||
start();
|
||||
} else {
|
||||
void refresh();
|
||||
}
|
||||
},
|
||||
subscribe(listener: () => void) {
|
||||
listeners.add(listener);
|
||||
if (!stop) start();
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
if (!listeners.size) {
|
||||
sequence++;
|
||||
stop?.();
|
||||
stop = undefined;
|
||||
}
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export type AgentQueueModel = ReturnType<typeof createAgentQueueModel>;
|
||||
@@ -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);
|
||||
|
||||
@@ -58,11 +58,7 @@ function installProbe(
|
||||
return function() {};
|
||||
} };
|
||||
})`;
|
||||
const evaluated = runPluginClientBundle(
|
||||
{ serverId: "test-host", pluginId: "probe-plugin" },
|
||||
clientBundle,
|
||||
runtime,
|
||||
);
|
||||
const evaluated = runPluginClientBundle("probe-plugin", clientBundle, runtime);
|
||||
return {
|
||||
...evaluated,
|
||||
serverId: "host-1",
|
||||
@@ -326,7 +322,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(
|
||||
@@ -336,7 +332,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 },
|
||||
},
|
||||
]);
|
||||
});
|
||||
@@ -523,7 +519,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({
|
||||
|
||||
@@ -7,7 +7,7 @@ import { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { RetainedPanelActivity } from "@/components/retained-panel";
|
||||
import { hydrateStreamState, reduceStreamUpdate, type StreamItem } from "@/types/stream";
|
||||
import { reduceStreamUpdate, type StreamItem } from "@/types/stream";
|
||||
import type { StreamRenderInput, StreamSegmentRenderers, StreamViewportHandle } from "./strategy";
|
||||
import { createWebStreamStrategy } from "./strategy-web";
|
||||
|
||||
@@ -1660,86 +1660,4 @@ describe("createWebStreamStrategy", () => {
|
||||
expect(container.querySelector('[data-testid="agent-chat-scroll"]')).toBe(scrollContainer);
|
||||
expect(scrollTo).toHaveBeenCalledWith({ top: 2200, behavior: "auto" });
|
||||
});
|
||||
|
||||
it("renders batched user messages sharing a provider messageId without duplicate React keys", () => {
|
||||
const sharedProviderMessageId = "9ffc3d6e-f0ff-4005-8675-e76e9c5eb5a8";
|
||||
const historyMounted = hydrateStreamState(
|
||||
[
|
||||
{
|
||||
event: {
|
||||
type: "timeline",
|
||||
provider: "claude",
|
||||
item: {
|
||||
type: "user_message",
|
||||
text: "first queued prompt",
|
||||
messageId: sharedProviderMessageId,
|
||||
clientMessageId: "client-queued-1",
|
||||
},
|
||||
},
|
||||
timestamp: new Date("2026-11-29T13:00:00.000Z"),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
|
||||
},
|
||||
{
|
||||
event: {
|
||||
type: "timeline",
|
||||
provider: "claude",
|
||||
item: {
|
||||
type: "user_message",
|
||||
text: "second direct prompt",
|
||||
messageId: sharedProviderMessageId,
|
||||
clientMessageId: "client-direct-2",
|
||||
},
|
||||
},
|
||||
timestamp: new Date("2026-11-29T13:00:01.000Z"),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
|
||||
},
|
||||
],
|
||||
{ source: "canonical" },
|
||||
);
|
||||
const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
const renderers = createRenderers(() => {});
|
||||
const strategy = createWebStreamStrategy({ isMobileBreakpoint: false });
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
|
||||
const rendered = strategy.render({
|
||||
agentId: "agent",
|
||||
segments: { historyVirtualized: [], historyMounted, liveHead: [] },
|
||||
boundary: {
|
||||
hasVirtualizedHistory: false,
|
||||
hasMountedHistory: true,
|
||||
hasLiveHead: false,
|
||||
},
|
||||
renderers,
|
||||
listEmptyComponent: null,
|
||||
viewportRef: React.createRef<StreamViewportHandle>(),
|
||||
routeBottomAnchorRequest: null,
|
||||
isAuthoritativeHistoryReady: true,
|
||||
onNearBottomChange: () => {},
|
||||
onNearHistoryStart: async () => true,
|
||||
isLoadingOlderHistory: false,
|
||||
hasOlderHistory: false,
|
||||
olderHistoryProgressKey: null,
|
||||
scrollEnabled: true,
|
||||
listStyle: null,
|
||||
baseListContentContainerStyle: null,
|
||||
forwardListContentContainerStyle: null,
|
||||
contentMaxWidth: DEFAULT_CONTENT_MAX_WIDTH,
|
||||
});
|
||||
act(() => {
|
||||
root?.render(rendered);
|
||||
});
|
||||
|
||||
const isSameKeyMessage = (arg: unknown) => typeof arg === "string" && arg.includes("same key");
|
||||
const duplicateKeyErrors = consoleError.mock.calls.filter((args) =>
|
||||
args.some(isSameKeyMessage),
|
||||
);
|
||||
expect(duplicateKeyErrors).toEqual([]);
|
||||
expect(
|
||||
Array.from(container.querySelectorAll("[data-history-row-id]")).map((node) =>
|
||||
node.getAttribute("data-history-row-id"),
|
||||
),
|
||||
).toEqual(["client-queued-1", "client-direct-2"]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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"));
|
||||
|
||||
@@ -101,7 +101,7 @@ function summaryRow(
|
||||
}
|
||||
|
||||
function staysVisibleWhenCollapsed(item: StreamItem): boolean {
|
||||
return isTurnTrigger(item) || item.kind === "compaction" || item.kind === "provider_switch";
|
||||
return isTurnTrigger(item) || item.kind === "compaction";
|
||||
}
|
||||
|
||||
function findLastReplyIndex(tail: StreamItem[], start: number, end: number): number {
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -37,7 +37,6 @@ import {
|
||||
ToolCall,
|
||||
TodoListCard,
|
||||
CompactionMarker,
|
||||
ProviderSwitchMarker,
|
||||
MessageOuterSpacingProvider,
|
||||
type InlinePathTarget,
|
||||
} from "@/components/message";
|
||||
@@ -58,7 +57,6 @@ import { useFileExplorerActions } from "@/hooks/use-file-explorer-actions";
|
||||
import { useLoadOlderAgentHistory } from "@/hooks/use-load-older-agent-history";
|
||||
import { resolveContentMaxWidth, useSettings } from "@/hooks/use-settings";
|
||||
import type { ToastApi } from "@/components/toast-host";
|
||||
import { isPromptInActiveSegment } from "@/components/rewind/use-rewind-capabilities";
|
||||
import { returnToTimelineTail } from "./timeline-tail-navigation";
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import { ToolCallDetailsContent } from "@/components/tool-call-details";
|
||||
@@ -410,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,
|
||||
);
|
||||
@@ -717,15 +711,8 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
|
||||
const setToolCallGroupExpanded = toolCallExpansion.setGroupExpanded;
|
||||
|
||||
const activeSegmentStartSeq = useSessionStore(
|
||||
(state) =>
|
||||
state.sessions[resolvedServerId]?.agentTimelineCursor.get(agentId)?.activeSegmentStartSeq ??
|
||||
0,
|
||||
);
|
||||
|
||||
const renderUserMessageItem = useCallback(
|
||||
(layoutItem: StreamLayoutItem, item: Extract<StreamItem, { kind: "user_message" }>) => {
|
||||
const canRewindPrompt = isPromptInActiveSegment(item.timelineCursor, activeSegmentStartSeq);
|
||||
return (
|
||||
<UserMessage
|
||||
itemId={item.id}
|
||||
@@ -737,7 +724,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
images={item.images}
|
||||
attachments={item.attachments}
|
||||
timestamp={item.timestamp.getTime()}
|
||||
capabilities={canRewindPrompt ? context.capabilities : undefined}
|
||||
capabilities={context.capabilities}
|
||||
client={client}
|
||||
isFirstInGroup={layoutItem.isFirstInUserGroup}
|
||||
isLastInGroup={layoutItem.isLastInUserGroup}
|
||||
@@ -748,14 +735,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
/>
|
||||
);
|
||||
},
|
||||
[
|
||||
activeSegmentStartSeq,
|
||||
context.capabilities,
|
||||
agentId,
|
||||
client,
|
||||
pendingClientMessageIds,
|
||||
resolvedServerId,
|
||||
],
|
||||
[context.capabilities, agentId, client, pendingClientMessageIds, resolvedServerId],
|
||||
);
|
||||
|
||||
const renderAssistantMessageItem = useCallback(
|
||||
@@ -969,18 +949,6 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
/>
|
||||
);
|
||||
|
||||
case "provider_switch":
|
||||
return (
|
||||
<ProviderSwitchMarker
|
||||
serverId={resolvedServerId}
|
||||
fromProvider={item.fromProvider}
|
||||
toProvider={item.toProvider}
|
||||
fromModel={item.fromModel}
|
||||
toModel={item.toModel}
|
||||
context={item.context}
|
||||
/>
|
||||
);
|
||||
|
||||
case "plugin":
|
||||
return (
|
||||
<PluginTimelineItemView agentId={agentId} item={item} serverId={resolvedServerId} />
|
||||
@@ -1206,7 +1174,6 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
agentId={agentId}
|
||||
serverId={resolvedServerId}
|
||||
epoch={timelineEpoch}
|
||||
rewindSeq={timelineRewindSeq}
|
||||
items={findItems}
|
||||
viewportRef={viewportRef}
|
||||
revealLoadedMessage={revealLoadedMessage}
|
||||
|
||||
@@ -75,7 +75,6 @@ export function estimateStreamItemHeight({
|
||||
case "notification":
|
||||
return 88;
|
||||
case "compaction":
|
||||
case "provider_switch":
|
||||
return 72;
|
||||
default:
|
||||
return 120;
|
||||
|
||||
@@ -79,7 +79,6 @@ import { HorizontalScrollProvider } from "@/contexts/horizontal-scroll-context";
|
||||
import { SessionProvider } from "@/contexts/session-context";
|
||||
import { SidebarCalloutProvider } from "@/contexts/sidebar-callout-context";
|
||||
import { ToastProvider } from "@/contexts/toast-context";
|
||||
import { WorkspaceTabCloseErrorToasts } from "@/workspace-tabs/close";
|
||||
import { VoiceProvider } from "@/contexts/voice-context";
|
||||
import {
|
||||
resolveStartupBlocker,
|
||||
@@ -995,7 +994,6 @@ function RootOverlayProviders({ children }: { children: ReactNode }) {
|
||||
<BottomSheetModalProvider>
|
||||
{children}
|
||||
<WindowLayoutActionsHost />
|
||||
<WorkspaceTabCloseErrorToasts />
|
||||
</BottomSheetModalProvider>
|
||||
</PortalProvider>
|
||||
</ToastProvider>
|
||||
|
||||
@@ -108,8 +108,6 @@ export type UserComposerAttachment =
|
||||
| { kind: "file"; attachment: UploadedFileAttachment }
|
||||
| WorkspaceFileComposerAttachment
|
||||
| PluginResourceComposerAttachment
|
||||
// An attachment taken back from a queued message. The host already holds it in wire form.
|
||||
| { kind: "agent_attachment"; attachment: AgentAttachment }
|
||||
| { kind: "forge_issue"; item: ForgeSearchItem }
|
||||
| { kind: "forge_change_request"; item: ForgeSearchItem }
|
||||
// COMPAT(githubAttachmentKinds): legacy persisted attachment kinds retained
|
||||
|
||||
@@ -4,7 +4,6 @@ import type {
|
||||
CommandCenterRegistration,
|
||||
CommandCenterRegistrationOwner,
|
||||
} from "./contributions";
|
||||
import { compareText } from "@/utils/collation";
|
||||
|
||||
export interface CommandCenterRegistry {
|
||||
getSnapshot(): CommandCenterContributionSnapshot;
|
||||
@@ -29,10 +28,10 @@ function compareContributions(
|
||||
right: CommandCenterContribution,
|
||||
): number {
|
||||
if (left.groupRank !== right.groupRank) return left.groupRank - right.groupRank;
|
||||
const groupDelta = compareText(left.group, right.group);
|
||||
const groupDelta = left.group.localeCompare(right.group);
|
||||
if (groupDelta !== 0) return groupDelta;
|
||||
if (left.rank !== right.rank) return left.rank - right.rank;
|
||||
return compareText(left.id, right.id);
|
||||
return left.id.localeCompare(right.id);
|
||||
}
|
||||
|
||||
function sameContributions(
|
||||
|
||||
@@ -205,7 +205,6 @@ export function useWorkspaceCommandCenterActions(): void {
|
||||
const { overrides } = useKeyboardShortcutOverrides();
|
||||
const { gitActions, isGit, archiveWorkspace } = useGitActions({
|
||||
serverId: serverId ?? "",
|
||||
workspaceId,
|
||||
cwd: cwd ?? "",
|
||||
icons: GIT_ACTION_ICONS,
|
||||
});
|
||||
|
||||
@@ -81,7 +81,6 @@ export function ArchivedAgentCallout({
|
||||
agentId,
|
||||
isWorkspaceRestoring = false,
|
||||
}: ArchivedAgentCalloutProps) {
|
||||
const { t } = useTranslation();
|
||||
const targetKey = `${serverId}:${agentId}`;
|
||||
const toast = useToast();
|
||||
const { unarchive, isUnarchiving, canUnarchive } = useUnarchiveAgent({ serverId, agentId });
|
||||
@@ -111,15 +110,7 @@ export function ArchivedAgentCallout({
|
||||
const attemptKey = targetKey;
|
||||
setUnarchiveErrorState(null);
|
||||
try {
|
||||
await unarchive({
|
||||
onRefreshed: (refreshed) => {
|
||||
if (refreshed.historyDiverged) {
|
||||
toast.show(t("workspace.tabs.toasts.reloadedAgentHistoryDiverged"), {
|
||||
variant: "warning",
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
await unarchive();
|
||||
} catch (error) {
|
||||
deliverUnarchiveError({
|
||||
error,
|
||||
@@ -130,7 +121,7 @@ export function ArchivedAgentCallout({
|
||||
onToastError: toast.error,
|
||||
});
|
||||
}
|
||||
}, [canUnarchive, t, targetKey, toast, unarchive]);
|
||||
}, [canUnarchive, targetKey, toast, unarchive]);
|
||||
|
||||
return (
|
||||
<KeyboardTranslateView style={styles.container}>
|
||||
|
||||
@@ -131,18 +131,13 @@ export function AttachmentLabel({ icon, title, subtitle }: AttachmentLabelProps)
|
||||
);
|
||||
}
|
||||
|
||||
/** Holds a thumbnail's space while its image loads. */
|
||||
export function AttachmentThumbnailPlaceholder() {
|
||||
return <View style={styles.thumbnailPlaceholder} />;
|
||||
}
|
||||
|
||||
/** Square image preview pill body. */
|
||||
export function AttachmentThumbnail({ metadata }: { metadata: AttachmentMetadata }) {
|
||||
const preview = useAttachmentPreviewUrl(metadata);
|
||||
const uri = preview.status === "ready" ? preview.url : null;
|
||||
const source = useMemo(() => (uri ? { uri } : null), [uri]);
|
||||
if (!source) {
|
||||
return <AttachmentThumbnailPlaceholder />;
|
||||
return <View style={styles.thumbnailPlaceholder} />;
|
||||
}
|
||||
return <Image source={source} style={styles.thumbnail} />;
|
||||
}
|
||||
|
||||
@@ -688,32 +688,6 @@ it("keeps workspace-relative hover titles on explicit absolute file links", () =
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
"an angle-bracket destination",
|
||||
"[Open](</repo/src/file.ts>)",
|
||||
'[Open](</repo/src/file.ts> "src/file.ts")',
|
||||
],
|
||||
["an escaped slash", "[Open](\\/repo/src/file.ts)", '[Open](\\/repo/src/file.ts "src/file.ts")'],
|
||||
[
|
||||
"an escaped separator",
|
||||
"[Open](/repo\\/src/file.ts)",
|
||||
'[Open](/repo\\/src/file.ts "src/file.ts")',
|
||||
],
|
||||
[
|
||||
"a character reference",
|
||||
"[Open](/repo/src/file.ts)",
|
||||
'[Open](/repo/src/file.ts "src/file.ts")',
|
||||
],
|
||||
])("keeps the workspace hover title on a link written with %s", (_form, source, rendered) => {
|
||||
expect(prepareMarkdownSource(source, "/repo").render()).toBe(rendered);
|
||||
});
|
||||
|
||||
it("leaves links outside the workspace as written", () => {
|
||||
const source = "[Docs](https://example.com/repo/x) and [Other](/repository/x) near /repo/x";
|
||||
expect(prepareMarkdownSource(source, "/repo").render()).toBe(source);
|
||||
});
|
||||
|
||||
it.each(['""', "''", "()"])("preserves an authored empty link title: %s", (title) => {
|
||||
const source = `[Open](/repo/file.ts ${title})`;
|
||||
expect(prepareMarkdownSource(source, "/repo").render()).toBe(source);
|
||||
|
||||
@@ -150,13 +150,6 @@ function workspaceHoverTitle(link: Link, markup: string, workspaceRoot?: string)
|
||||
return link.url.slice(workspaceRoot.length + 1);
|
||||
}
|
||||
|
||||
// Only a link into the workspace gets an edit, its hover title. A link's URL differs from its
|
||||
// source text only by backslash escapes and character references, and `&` already takes the parse.
|
||||
function mayLinkIntoWorkspace(source: string, workspaceRoot?: string): boolean {
|
||||
if (!workspaceRoot || !source.includes("](")) return false;
|
||||
return source.includes(`${workspaceRoot}/`) || source.includes("\\");
|
||||
}
|
||||
|
||||
/** Preserve source spelling; adapt workspace images, spoiler delimiters, and entity text. */
|
||||
export function prepareMarkdownSource(
|
||||
source: string,
|
||||
@@ -198,7 +191,7 @@ export function prepareMarkdownSource(
|
||||
!/^[\t >]*[^\t >\r\n][^\r\n]*(?:\r\n|\r|\n)[^\r\n]+(?:\r\n|\r|\n)(?=[\t >:|-]*\|)[\t >|]*:?-[-\t :|]*$/m.test(
|
||||
source,
|
||||
) &&
|
||||
!mayLinkIntoWorkspace(source, workspaceRoot) &&
|
||||
!(workspaceRoot && source.includes("](")) &&
|
||||
!(external && /\]|<[a-z]+:/i.test(source))
|
||||
) {
|
||||
return { images, ...metadata, render: () => source };
|
||||
|
||||
@@ -21,11 +21,9 @@ import {
|
||||
type RewindMode,
|
||||
} from "@/components/rewind";
|
||||
import { TaskListRow } from "@/components/task-list-row";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { isNative, isWeb } from "@/constants/platform";
|
||||
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
|
||||
import { useRevealedText, type MarkdownPhase } from "@/hooks/use-revealed-text";
|
||||
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||
import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style";
|
||||
@@ -49,17 +47,13 @@ import type { AgentMessage } from "@getpaseo/protocol/agent-message";
|
||||
import type {
|
||||
AgentCapabilityFlags,
|
||||
AgentMetric,
|
||||
AgentProvider,
|
||||
ProviderSwitchContextSummary,
|
||||
ToolCallDetail,
|
||||
} from "@getpaseo/protocol/agent-types";
|
||||
import type { AgentAttachment } from "@getpaseo/protocol/messages";
|
||||
import MaskedView from "@react-native-masked-view/masked-view";
|
||||
import {
|
||||
ArrowRightLeft,
|
||||
Check,
|
||||
CheckSquare,
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
CircleDot,
|
||||
Copy,
|
||||
@@ -1581,206 +1575,6 @@ export const CompactionMarker = memo(function CompactionMarker({
|
||||
);
|
||||
});
|
||||
|
||||
const StyledSwitchIcon = withUnistyles(ArrowRightLeft, (theme) => ({
|
||||
color: theme.colors.foregroundMuted,
|
||||
}));
|
||||
const StyledChevronDownIcon = withUnistyles(ChevronDown, (theme) => ({
|
||||
color: theme.colors.foregroundMuted,
|
||||
}));
|
||||
const StyledChevronRightIcon = withUnistyles(ChevronRight, (theme) => ({
|
||||
color: theme.colors.foregroundMuted,
|
||||
}));
|
||||
|
||||
export interface ProviderSwitchMarkerProps {
|
||||
serverId?: string | null;
|
||||
fromProvider: AgentProvider;
|
||||
toProvider: AgentProvider;
|
||||
fromModel?: string | null;
|
||||
toModel?: string | null;
|
||||
context?: ProviderSwitchContextSummary;
|
||||
}
|
||||
|
||||
const providerSwitchStylesheet = StyleSheet.create((theme) => ({
|
||||
wrapper: {
|
||||
paddingVertical: theme.spacing[2],
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
row: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
width: "100%",
|
||||
},
|
||||
line: {
|
||||
flex: 1,
|
||||
minWidth: 12,
|
||||
height: 1,
|
||||
backgroundColor: theme.colors.border,
|
||||
},
|
||||
triggerButton: {
|
||||
flexShrink: 1,
|
||||
minWidth: 0,
|
||||
maxWidth: "85%",
|
||||
},
|
||||
triggerContent: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
flexShrink: 1,
|
||||
minWidth: 0,
|
||||
maxWidth: "100%",
|
||||
gap: theme.spacing[1.5],
|
||||
},
|
||||
triggerText: {
|
||||
flexShrink: 1,
|
||||
minWidth: 0,
|
||||
fontFamily: theme.fontFamily.ui,
|
||||
fontSize: 13,
|
||||
color: theme.colors.foregroundMuted,
|
||||
},
|
||||
chevronSlot: {
|
||||
width: 12,
|
||||
height: 12,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
detailsCard: {
|
||||
alignSelf: "center",
|
||||
maxWidth: 480,
|
||||
width: "100%",
|
||||
paddingVertical: theme.spacing[2],
|
||||
paddingHorizontal: theme.spacing[3],
|
||||
borderRadius: theme.borderRadius.md,
|
||||
borderWidth: 1,
|
||||
borderColor: theme.colors.border,
|
||||
backgroundColor: theme.colors.surface0,
|
||||
gap: theme.spacing[1],
|
||||
},
|
||||
detailRow: {
|
||||
fontFamily: theme.fontFamily.ui,
|
||||
fontSize: 12,
|
||||
color: theme.colors.foregroundMuted,
|
||||
},
|
||||
}));
|
||||
|
||||
function resolveProviderSwitchLabel(
|
||||
provider: string,
|
||||
entries: ReturnType<typeof useProvidersSnapshot>["entries"],
|
||||
): string {
|
||||
return entries?.find((entry) => entry.provider === provider)?.label ?? provider;
|
||||
}
|
||||
|
||||
function resolveProviderSwitchModelLabel(
|
||||
provider: string,
|
||||
modelId: string | null | undefined,
|
||||
entries: ReturnType<typeof useProvidersSnapshot>["entries"],
|
||||
): string | null {
|
||||
if (!modelId) return null;
|
||||
const entry = entries?.find((candidate) => candidate.provider === provider);
|
||||
return entry?.models?.find((model) => model.id === modelId)?.label ?? modelId;
|
||||
}
|
||||
|
||||
function formatProviderSwitchEndpoint(providerLabel: string, modelLabel: string | null): string {
|
||||
return modelLabel ? `${providerLabel} (${modelLabel})` : providerLabel;
|
||||
}
|
||||
|
||||
export const ProviderSwitchMarker = memo(function ProviderSwitchMarker({
|
||||
serverId = null,
|
||||
fromProvider,
|
||||
toProvider,
|
||||
fromModel,
|
||||
toModel,
|
||||
context,
|
||||
}: ProviderSwitchMarkerProps) {
|
||||
const { t } = useTranslation();
|
||||
const { entries: providerEntries } = useProvidersSnapshot(serverId);
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const handleToggle = useCallback(() => setExpanded((prev) => !prev), []);
|
||||
|
||||
const fromLabel = resolveProviderSwitchLabel(fromProvider, providerEntries);
|
||||
const toLabel = resolveProviderSwitchLabel(toProvider, providerEntries);
|
||||
const fromModelLabel = resolveProviderSwitchModelLabel(fromProvider, fromModel, providerEntries);
|
||||
const toModelLabel = resolveProviderSwitchModelLabel(toProvider, toModel, providerEntries);
|
||||
|
||||
const title = t("message.providerSwitch.switched", {
|
||||
from: fromLabel,
|
||||
to: toLabel,
|
||||
});
|
||||
const contextLine = context
|
||||
? t("message.providerSwitch.contextSummary", {
|
||||
count: context.includedItems,
|
||||
chars: context.charCount.toLocaleString(),
|
||||
budget: context.budgetChars.toLocaleString(),
|
||||
})
|
||||
: null;
|
||||
const reasonsLine =
|
||||
context?.truncated && context.omittedReasons?.length
|
||||
? t("message.providerSwitch.trimmed", {
|
||||
reasons: context.omittedReasons
|
||||
.map((reason) => {
|
||||
if (reason === "tail_window_limit") {
|
||||
return t("message.providerSwitch.reasonTailWindow");
|
||||
}
|
||||
if (reason === "char_budget") {
|
||||
return t("message.providerSwitch.reasonCharBudget");
|
||||
}
|
||||
return reason;
|
||||
})
|
||||
.join(", "),
|
||||
})
|
||||
: null;
|
||||
|
||||
let chevronIcon: React.ReactNode = null;
|
||||
if (context) {
|
||||
chevronIcon = expanded ? (
|
||||
<StyledChevronDownIcon size={12} />
|
||||
) : (
|
||||
<StyledChevronRightIcon size={12} />
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={providerSwitchStylesheet.wrapper} testID="provider-switch-marker">
|
||||
<View style={providerSwitchStylesheet.row}>
|
||||
<View style={providerSwitchStylesheet.line} />
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
style={providerSwitchStylesheet.triggerButton}
|
||||
onPress={context ? handleToggle : undefined}
|
||||
accessibilityLabel={title}
|
||||
testID="provider-switch-marker-toggle"
|
||||
>
|
||||
<View style={providerSwitchStylesheet.triggerContent}>
|
||||
<StyledSwitchIcon size={12} />
|
||||
<Text
|
||||
style={providerSwitchStylesheet.triggerText}
|
||||
numberOfLines={1}
|
||||
ellipsizeMode="tail"
|
||||
>
|
||||
{title}
|
||||
</Text>
|
||||
<View style={providerSwitchStylesheet.chevronSlot}>{chevronIcon}</View>
|
||||
</View>
|
||||
</Button>
|
||||
<View style={providerSwitchStylesheet.line} />
|
||||
</View>
|
||||
{expanded && context ? (
|
||||
<View style={providerSwitchStylesheet.detailsCard} testID="provider-switch-marker-details">
|
||||
<Text style={providerSwitchStylesheet.detailRow}>
|
||||
{`${formatProviderSwitchEndpoint(fromLabel, fromModelLabel)} → ${formatProviderSwitchEndpoint(toLabel, toModelLabel)}`}
|
||||
</Text>
|
||||
{contextLine ? (
|
||||
<Text style={providerSwitchStylesheet.detailRow}>{contextLine}</Text>
|
||||
) : null}
|
||||
{reasonsLine ? (
|
||||
<Text style={providerSwitchStylesheet.detailRow}>{reasonsLine}</Text>
|
||||
) : null}
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
});
|
||||
|
||||
interface TodoListCardProps {
|
||||
items: TodoEntry[];
|
||||
activity: TaskActivity;
|
||||
|
||||
@@ -11,6 +11,11 @@ describe("pairing target password", () => {
|
||||
expect(target.changeUrl(second)).toBe(false);
|
||||
});
|
||||
|
||||
it("clears the direct form credential when its advanced URI changes to a relay target", () => {
|
||||
const target = new PairingTargetTracker("", true);
|
||||
expect(target.changeUrl("relay://relay.example:443/srv_new?key=BBBB&ssl=true")).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps the password when a relay URI receives harmless whitespace", () => {
|
||||
const uri = "relay://relay.example:443/srv_a?key=AAAA&ssl=true";
|
||||
const target = new PairingTargetTracker(uri);
|
||||
|
||||
@@ -19,8 +19,8 @@ function pairingTarget(url: string): string | null {
|
||||
export class PairingTargetTracker {
|
||||
private currentTarget: string | null;
|
||||
|
||||
constructor(initialUrl = "") {
|
||||
this.currentTarget = pairingTarget(initialUrl);
|
||||
constructor(initialUrl = "", startsFromDirectForm = false) {
|
||||
this.currentTarget = pairingTarget(initialUrl) ?? (startsFromDirectForm ? "direct-form" : null);
|
||||
}
|
||||
|
||||
changeUrl(nextUrl: string): boolean {
|
||||
|
||||
@@ -10,11 +10,7 @@ import { useToast } from "@/contexts/toast-context";
|
||||
import type { AgentScreenReadySyncState } from "@/hooks/use-agent-screen-state-machine";
|
||||
import { selectAgentTimelineState, useSessionStore } from "@/stores/session-store";
|
||||
import { useRewindAgentMutation } from "./use-rewind-agent-mutation";
|
||||
import {
|
||||
isPromptInActiveSegment,
|
||||
isRewindableMessage,
|
||||
useRewindMenuItems,
|
||||
} from "./use-rewind-capabilities";
|
||||
import { isRewindableMessage, useRewindMenuItems } from "./use-rewind-capabilities";
|
||||
|
||||
export function RewindCommandCenterRegistration({
|
||||
serverId,
|
||||
@@ -46,16 +42,10 @@ export function RewindCommandCenterRegistration({
|
||||
if (timeline.status !== "synced" || timeline.newer === "available") {
|
||||
return undefined;
|
||||
}
|
||||
const candidate =
|
||||
return (
|
||||
session.agentStreamHead.get(agentId)?.findLast((item) => item.kind === "user_message") ??
|
||||
timeline.items.findLast((item) => item.kind === "user_message");
|
||||
if (
|
||||
!candidate ||
|
||||
!isPromptInActiveSegment(candidate.timelineCursor, timeline.range?.activeSegmentStartSeq)
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
return candidate;
|
||||
timeline.items.findLast((item) => item.kind === "user_message")
|
||||
);
|
||||
});
|
||||
const { rewindAgent, isPending } = useRewindAgentMutation({
|
||||
serverId,
|
||||
|
||||
@@ -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.18.0, remove after 2027-05-25. 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()
|
||||
|
||||
@@ -26,20 +26,6 @@ export function isRewindableMessage(messageId: string | undefined, text: string)
|
||||
return Boolean(messageId) && text.trim().length > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a user prompt belongs to the active provider segment (after the latest provider switch).
|
||||
* Prompts from earlier provider segments cannot be rewound.
|
||||
*/
|
||||
export function isPromptInActiveSegment(
|
||||
timelineCursor: { anchorSeq?: number; seq?: number } | undefined,
|
||||
activeSegmentStartSeq: number | undefined,
|
||||
): boolean {
|
||||
if (!activeSegmentStartSeq || activeSegmentStartSeq <= 0) return true;
|
||||
const anchor = timelineCursor?.anchorSeq ?? timelineCursor?.seq;
|
||||
if (anchor === undefined) return true;
|
||||
return anchor > activeSegmentStartSeq;
|
||||
}
|
||||
|
||||
export function resolveRewindMenuItems(
|
||||
capabilities:
|
||||
| Pick<
|
||||
|
||||
@@ -54,8 +54,6 @@ import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-
|
||||
import {
|
||||
collectAllPanes,
|
||||
createDefaultLayout,
|
||||
resolveGroupSizes,
|
||||
resolveMainSplitTree,
|
||||
selectExplorerSidebarPaneId,
|
||||
useWorkspaceLayoutStore,
|
||||
type SplitNode,
|
||||
@@ -82,7 +80,7 @@ interface SplitContainerProps {
|
||||
uiTabs: WorkspaceTab[];
|
||||
hoveredCloseTabKey: string | null;
|
||||
setHoveredCloseTabKey: Dispatch<SetStateAction<string | null>>;
|
||||
closingTabIds: ReadonlySet<string>;
|
||||
closingTabIds: Set<string>;
|
||||
onNavigateTab: (tabId: string) => void;
|
||||
onCloseTab: (tabId: string) => Promise<void> | void;
|
||||
onCopyResumeCommand: (agentId: string) => Promise<void> | void;
|
||||
@@ -207,7 +205,7 @@ export function SplitContainer({
|
||||
);
|
||||
|
||||
const mainRoot = useMemo(
|
||||
() => resolveMainSplitTree(layout.root, explorerSidebarPaneId),
|
||||
() => removePaneFromSplitTree(layout.root, explorerSidebarPaneId),
|
||||
[layout.root, explorerSidebarPaneId],
|
||||
);
|
||||
const workspaceHasMultiplePanes = Boolean(mainRoot && hasMultipleVisiblePanes(mainRoot));
|
||||
@@ -461,10 +459,11 @@ function SplitNodeView({
|
||||
);
|
||||
const groupChildren = node.kind === "group" ? node.group.children : EMPTY_SPLIT_NODES;
|
||||
// Dragged sizes live per group id, apart from the layout tree, and a group keeps its id when
|
||||
// panes are added or removed. A list of the wrong length would leave the dividers past its end
|
||||
// unable to move.
|
||||
// panes are added or removed. They only apply while they still have one entry per child;
|
||||
// otherwise the dividers past the end of the list could not move.
|
||||
const layoutGroupSizes = node.kind === "group" ? node.group.sizes : EMPTY_SPLIT_SIZES;
|
||||
const groupSizes =
|
||||
node.kind === "group" ? resolveGroupSizes(node.group, storedGroupSizes) : EMPTY_SPLIT_SIZES;
|
||||
storedGroupSizes?.length === groupChildren.length ? storedGroupSizes : layoutGroupSizes;
|
||||
const visibleFlex = useMemo(
|
||||
() => resolveVisibleGroupFlex(groupChildren, groupSizes, maximizedPaneId),
|
||||
[groupChildren, groupSizes, maximizedPaneId],
|
||||
@@ -911,6 +910,34 @@ function wrapRootPaneForStableMount(node: SplitNode): SplitNode {
|
||||
};
|
||||
}
|
||||
|
||||
function removePaneFromSplitTree(node: SplitNode, paneId: string | null): SplitNode | null {
|
||||
if (!paneId) {
|
||||
return node;
|
||||
}
|
||||
if (node.kind === "pane") {
|
||||
return node.pane.id === paneId ? null : node;
|
||||
}
|
||||
|
||||
const children = node.group.children.flatMap((child) => {
|
||||
const nextChild = removePaneFromSplitTree(child, paneId);
|
||||
return nextChild ? [nextChild] : [];
|
||||
});
|
||||
if (children.length === 0) {
|
||||
return null;
|
||||
}
|
||||
if (children.length === 1) {
|
||||
return children[0] ?? null;
|
||||
}
|
||||
return {
|
||||
kind: "group",
|
||||
group: {
|
||||
...node.group,
|
||||
children,
|
||||
sizes: children.map(() => 1 / children.length),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
workspaceShell: {
|
||||
flex: 1,
|
||||
|
||||
@@ -2,7 +2,6 @@ import {
|
||||
BottomSheetModal as GorhomBottomSheetModal,
|
||||
type BottomSheetModalProps,
|
||||
type BottomSheetBackdropProps,
|
||||
useBottomSheetInternal,
|
||||
} from "@gorhom/bottom-sheet";
|
||||
import React from "react";
|
||||
import {
|
||||
@@ -26,7 +25,6 @@ import {
|
||||
type AttachSheetContentDrag,
|
||||
type SheetContentDragGesture,
|
||||
} from "@/components/ui/bottom-sheet-scope";
|
||||
import { runOnJS, useAnimatedReaction, useSharedValue } from "react-native-reanimated";
|
||||
import { SheetBackdrop } from "./sheet-backdrop";
|
||||
|
||||
type GorhomBottomSheetModalMethods = ElementRef<typeof GorhomBottomSheetModal>;
|
||||
@@ -58,7 +56,7 @@ type IsolatedBottomSheetModalProps = Omit<
|
||||
/**
|
||||
* Whether closing (drag, backdrop, Back) also dismisses, which unmounts the content. Default
|
||||
* true: the owner hears `onDismiss` and drops its state. Pass `false` for a sheet whose close the
|
||||
* owner may veto: it parks at index -1 with its content mounted, the owner hears `onClosed`,
|
||||
* owner may veto: it parks at index -1 with its content mounted, the owner hears `onChange(-1)`,
|
||||
* and either snaps it back or unmounts it, which dismisses it from the stack.
|
||||
*/
|
||||
enableDismissOnClose?: boolean;
|
||||
@@ -76,15 +74,6 @@ type IsolatedBottomSheetModalProps = Omit<
|
||||
* inside the sheet and it throws on device only.
|
||||
*/
|
||||
contextBridge: ContextBridge | null;
|
||||
/**
|
||||
* Runs when a close animation settles at the closed detent, whoever started it.
|
||||
*
|
||||
* Gorhom reports that through `onChange(-1)`, but skips `onChange` when its index bookkeeping
|
||||
* already reads -1. An interrupted mount animation leaves it there, so the next close ends where
|
||||
* it began and the owner never hears about it. Watch this signal, not `onChange`, when a close
|
||||
* the owner may veto still has to reach the owner.
|
||||
*/
|
||||
onClosed?: () => void;
|
||||
};
|
||||
|
||||
export type IsolatedBottomSheetModalRef = GorhomBottomSheetModalMethods;
|
||||
@@ -116,7 +105,6 @@ export const IsolatedBottomSheetModal = forwardRef<
|
||||
contextBridge,
|
||||
backdropOpacity,
|
||||
enableDismissOnClose = true,
|
||||
onClosed,
|
||||
waitFor,
|
||||
simultaneousHandlers,
|
||||
...bottomSheetProps
|
||||
@@ -163,7 +151,6 @@ export const IsolatedBottomSheetModal = forwardRef<
|
||||
simultaneousHandlers={contentDragHandlers.simultaneousHandlers}
|
||||
>
|
||||
<BottomSheetScope attachContentDrag={attachContentDrag}>
|
||||
{onClosed ? <SheetCloseSignal onClosed={onClosed} /> : null}
|
||||
{contextBridge ? contextBridge(children) : children}
|
||||
</BottomSheetScope>
|
||||
</GorhomBottomSheetModal>
|
||||
@@ -172,43 +159,6 @@ export const IsolatedBottomSheetModal = forwardRef<
|
||||
return modal;
|
||||
});
|
||||
|
||||
/**
|
||||
* Reports a close animation that settles at the closed detent — the signal Gorhom only routes
|
||||
* through `onChange(-1)`, which it drops when the sheet's current index already reads -1.
|
||||
*
|
||||
* `animatedAnimationState.nextIndex` is -1 for the whole close animation and undefined once it
|
||||
* completes. The settled position then tells a real close from a spring back and an interruption.
|
||||
*/
|
||||
function SheetCloseSignal({ onClosed }: { onClosed: () => void }) {
|
||||
const { animatedAnimationState, animatedDetentsState, animatedPosition } =
|
||||
useBottomSheetInternal();
|
||||
const closing = useSharedValue(false);
|
||||
useAnimatedReaction(
|
||||
() => {
|
||||
const { nextIndex } = animatedAnimationState.get();
|
||||
if (nextIndex === -1) return -1;
|
||||
return nextIndex === undefined ? 0 : 1;
|
||||
},
|
||||
(phase, previousPhase) => {
|
||||
if (phase === -1) {
|
||||
closing.value = true;
|
||||
return;
|
||||
}
|
||||
if (phase === 1) {
|
||||
closing.value = false;
|
||||
return;
|
||||
}
|
||||
if (previousPhase !== -1 || !closing.value) return;
|
||||
closing.value = false;
|
||||
const closedPosition = animatedDetentsState.get().closedDetentPosition;
|
||||
if (closedPosition === undefined) return;
|
||||
if (Math.abs(animatedPosition.value - closedPosition) < 1) runOnJS(onClosed)();
|
||||
},
|
||||
[animatedAnimationState, animatedDetentsState, animatedPosition, onClosed],
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
export function useIsolatedBottomSheetVisibility({
|
||||
visible,
|
||||
isEnabled,
|
||||
|
||||
@@ -25,18 +25,22 @@ import {
|
||||
uploadFileAttachments,
|
||||
cancelComposerAgent,
|
||||
dispatchComposerAgentMessage,
|
||||
enqueueComposerAgentMessage,
|
||||
editQueuedComposerMessage,
|
||||
findForgeItemByOption,
|
||||
isAttachmentSelectedForForgeItem,
|
||||
openComposerAttachment,
|
||||
pickAndPersistImages,
|
||||
queueComposerMessage,
|
||||
removeComposerAttachmentAtIndex,
|
||||
sendQueuedComposerMessageNow,
|
||||
toggleForgeAttachment,
|
||||
toggleForgeAttachmentFromPicker,
|
||||
type MessageSubmissionWriter,
|
||||
type AttachmentPersister,
|
||||
type ComposerCancelClient,
|
||||
type ComposerSendClient,
|
||||
type QueueWriter,
|
||||
type QueuedComposerMessage,
|
||||
} from "./actions";
|
||||
|
||||
const imageMetadata: AttachmentMetadata = {
|
||||
@@ -180,7 +184,7 @@ interface FakeSendCall {
|
||||
text: string;
|
||||
options: {
|
||||
messageId: string;
|
||||
activeTurnBehavior?: "interrupt" | "steer" | "queue";
|
||||
activeTurnBehavior?: "interrupt" | "steer";
|
||||
images?: Array<{ data: string; mimeType: string }>;
|
||||
attachments: AgentAttachment[];
|
||||
};
|
||||
@@ -302,6 +306,19 @@ function writeSubmission(fake: FakeStream, agentId: string, state: FakeSubmissio
|
||||
submissionsByFakeStream.set(fake, submissions);
|
||||
}
|
||||
|
||||
function createFakeQueue(
|
||||
initial: Map<string, QueuedComposerMessage[]> = new Map(),
|
||||
): QueueWriter & { state: Map<string, QueuedComposerMessage[]> } {
|
||||
const fake: QueueWriter & { state: Map<string, QueuedComposerMessage[]> } = {
|
||||
state: new Map(initial),
|
||||
read: (agentId) => fake.state.get(agentId) ?? [],
|
||||
write: (updater) => {
|
||||
fake.state = updater(fake.state);
|
||||
},
|
||||
};
|
||||
return fake;
|
||||
}
|
||||
|
||||
const passthroughUploadImages = async (
|
||||
images: AttachmentMetadata[],
|
||||
): Promise<UploadedFileAttachment[]> =>
|
||||
@@ -738,186 +755,147 @@ describe("dispatchComposerAgentMessage", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("enqueueComposerAgentMessage", () => {
|
||||
it("hands a trimmed message to the host queue without adding a timeline row", async () => {
|
||||
const client = createFakeSendClient();
|
||||
const review = reviewWorkspaceAttachment("Queued review.");
|
||||
|
||||
await enqueueComposerAgentMessage({
|
||||
client,
|
||||
describe("queueComposerMessage", () => {
|
||||
it("queues a trimmed message under the agent id and returns the new entry", () => {
|
||||
const queue = createFakeQueue();
|
||||
const result = queueComposerMessage({
|
||||
agentId: "agent",
|
||||
text: " queue this ",
|
||||
attachments: [{ kind: "image", metadata: imageWithId("img-queue") }, review],
|
||||
uploadImages: passthroughUploadImages,
|
||||
text: " draft ",
|
||||
attachments: [],
|
||||
queue,
|
||||
});
|
||||
|
||||
expect(client.calls).toEqual([
|
||||
{
|
||||
agentId: "agent",
|
||||
text: "queue this",
|
||||
options: {
|
||||
messageId: expect.any(String),
|
||||
activeTurnBehavior: "queue",
|
||||
attachments: [
|
||||
review.attachment,
|
||||
expect.objectContaining({
|
||||
type: "uploaded_file",
|
||||
id: "upload_img-queue",
|
||||
role: "image",
|
||||
}),
|
||||
],
|
||||
},
|
||||
},
|
||||
expect(result.queued?.text).toBe("draft");
|
||||
expect(queue.state.get("agent")).toEqual([
|
||||
{ id: result.queued?.id, text: "draft", attachments: [] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("sends nothing for an empty message with no attachments", async () => {
|
||||
const client = createFakeSendClient();
|
||||
|
||||
await enqueueComposerAgentMessage({ client, agentId: "agent", text: " ", attachments: [] });
|
||||
|
||||
expect(client.calls).toEqual([]);
|
||||
});
|
||||
|
||||
it("queues a staged provider switch with the message so the host runs it on that provider", async () => {
|
||||
const client = createFakeSendClient();
|
||||
const switches: unknown[] = [];
|
||||
let queuedSwitches = 0;
|
||||
|
||||
const input: Parameters<typeof enqueueComposerAgentMessage>[0] = {
|
||||
client: {
|
||||
...client,
|
||||
switchAgentProvider: async (agentId, options) => {
|
||||
switches.push({ agentId, options });
|
||||
return {};
|
||||
},
|
||||
},
|
||||
it("does not queue an empty message with no attachments", () => {
|
||||
const queue = createFakeQueue();
|
||||
const result = queueComposerMessage({
|
||||
agentId: "agent",
|
||||
text: "do Z",
|
||||
text: " ",
|
||||
attachments: [],
|
||||
stagedProviderSwitch: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
modeId: "auto",
|
||||
thinkingOptionId: null,
|
||||
providerOptions: { fast_mode: true },
|
||||
},
|
||||
onProviderSwitchQueued: () => {
|
||||
queuedSwitches += 1;
|
||||
},
|
||||
};
|
||||
await enqueueComposerAgentMessage(input);
|
||||
// Nothing to send leaves the switch with the composer.
|
||||
await enqueueComposerAgentMessage({ ...input, text: " " });
|
||||
|
||||
expect(queuedSwitches).toBe(1);
|
||||
expect(client.calls).toEqual([]);
|
||||
expect(switches).toEqual([
|
||||
{
|
||||
agentId: "agent",
|
||||
options: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
modeId: "auto",
|
||||
thinkingOptionId: null,
|
||||
providerOptions: { fast_mode: true },
|
||||
text: "do Z",
|
||||
messageId: expect.any(String),
|
||||
activeTurnBehavior: "queue",
|
||||
attachments: [],
|
||||
},
|
||||
},
|
||||
]);
|
||||
queue,
|
||||
});
|
||||
expect(result.queued).toBeNull();
|
||||
expect(queue.state.get("agent")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("rejects when the host refuses the message", async () => {
|
||||
const rejection = new Error("Agent not found");
|
||||
const client = createFakeSendClient({ rejection });
|
||||
it("captures workspace review attachments at queue time alongside user attachments", () => {
|
||||
const queue = createFakeQueue();
|
||||
const review = reviewWorkspaceAttachment("Initial queued review.");
|
||||
const image = imageWithId("img-queue");
|
||||
queueComposerMessage({
|
||||
agentId: "agent",
|
||||
text: "queue this",
|
||||
attachments: [{ kind: "image", metadata: image }, review],
|
||||
queue,
|
||||
});
|
||||
|
||||
await expect(
|
||||
enqueueComposerAgentMessage({ client, agentId: "agent", text: "hello", attachments: [] }),
|
||||
).rejects.toBe(rejection);
|
||||
expect(queue.state.get("agent")?.[0]?.attachments).toEqual([
|
||||
{ kind: "image", metadata: image },
|
||||
review,
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("attachments restored from a queued message", () => {
|
||||
const uploadedImage: Extract<AgentAttachment, { type: "uploaded_file" }> = {
|
||||
type: "uploaded_file",
|
||||
id: "upload_restored",
|
||||
fileName: "photo.png",
|
||||
mimeType: "image/png",
|
||||
size: 42,
|
||||
path: "/home/user/.paseo/uploads/upload_restored/photo.png",
|
||||
role: "image",
|
||||
};
|
||||
const restoredImage: UserComposerAttachment = {
|
||||
kind: "agent_attachment",
|
||||
attachment: uploadedImage,
|
||||
};
|
||||
const restoredIssue: UserComposerAttachment = {
|
||||
kind: "agent_attachment",
|
||||
attachment: {
|
||||
type: "forge_issue",
|
||||
mimeType: "application/paseo-forge-issue",
|
||||
forge: "github",
|
||||
number: issueItem.number,
|
||||
title: issueItem.title,
|
||||
url: issueItem.url,
|
||||
},
|
||||
};
|
||||
describe("editQueuedComposerMessage", () => {
|
||||
it("returns null and leaves the queue untouched when the message id is missing", () => {
|
||||
const queue = createFakeQueue(
|
||||
new Map([["agent", [{ id: "other", text: "other", attachments: [] }]]]),
|
||||
);
|
||||
const result = editQueuedComposerMessage({ agentId: "agent", messageId: "missing", queue });
|
||||
expect(result).toBeNull();
|
||||
expect(queue.state.get("agent")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("queues the same uploaded image again without uploading it", async () => {
|
||||
const client = createFakeSendClient();
|
||||
it("returns the text and only user attachments, removing the queued entry", () => {
|
||||
const review = reviewWorkspaceAttachment("Queued snapshot.");
|
||||
const image = imageWithId("img-queued-edit");
|
||||
const queue = createFakeQueue(
|
||||
new Map([
|
||||
[
|
||||
"agent",
|
||||
[
|
||||
{
|
||||
id: "msg-1",
|
||||
text: "queued draft",
|
||||
attachments: [{ kind: "image", metadata: image }, review],
|
||||
},
|
||||
],
|
||||
],
|
||||
]),
|
||||
);
|
||||
|
||||
await enqueueComposerAgentMessage({
|
||||
client,
|
||||
agentId: "agent",
|
||||
text: "again",
|
||||
attachments: [restoredImage],
|
||||
const result = editQueuedComposerMessage({ agentId: "agent", messageId: "msg-1", queue });
|
||||
expect(result).toEqual({
|
||||
text: "queued draft",
|
||||
attachments: [{ kind: "image", metadata: image }],
|
||||
});
|
||||
|
||||
expect(client.uploadCalls).toEqual([]);
|
||||
expect(client.calls[0]?.options.attachments).toEqual([uploadedImage]);
|
||||
expect(queue.state.get("agent")).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
it("shows a sent uploaded image as an image on the optimistic message", async () => {
|
||||
const client = createFakeSendClient();
|
||||
const stream = createFakeStream();
|
||||
|
||||
await dispatchComposerAgentMessage({
|
||||
client,
|
||||
describe("sendQueuedComposerMessageNow", () => {
|
||||
it("returns missing without submitting when the message id is gone", async () => {
|
||||
const queue = createFakeQueue();
|
||||
const submitted: Array<{ text: string; attachments: ComposerAttachment[] }> = [];
|
||||
const result = await sendQueuedComposerMessageNow({
|
||||
agentId: "agent",
|
||||
text: "look",
|
||||
attachments: [restoredImage],
|
||||
submission: stream,
|
||||
});
|
||||
|
||||
const { type: _type, role: _role, ...upload } = uploadedImage;
|
||||
const shown = [...(stream.tail.get("agent") ?? []), ...(stream.head.get("agent") ?? [])];
|
||||
expect(shown).toEqual([
|
||||
expect.objectContaining({ images: [{ ...upload, storageType: "daemon-upload" }] }),
|
||||
]);
|
||||
expect(client.uploadCalls).toEqual([]);
|
||||
expect(client.calls[0]?.options.attachments).toEqual([uploadedImage]);
|
||||
});
|
||||
|
||||
it("counts a restored forge item as selected and toggles it off", () => {
|
||||
expect(isAttachmentSelectedForForgeItem([restoredIssue], issueItem)).toBe(true);
|
||||
expect(isAttachmentSelectedForForgeItem([restoredIssue], prItem)).toBe(false);
|
||||
expect(toggleForgeAttachment([restoredIssue], issueItem)).toEqual([]);
|
||||
});
|
||||
|
||||
it("opens the URL of a restored forge item", () => {
|
||||
const urls: string[] = [];
|
||||
openComposerAttachment({
|
||||
attachment: restoredIssue,
|
||||
setLightboxMetadata: () => {
|
||||
throw new Error("unexpected lightbox call");
|
||||
messageId: "msg-1",
|
||||
queue,
|
||||
submitMessage: async (input) => {
|
||||
submitted.push(input);
|
||||
},
|
||||
openWorkspaceAttachment: () => false,
|
||||
openExternalUrl: (url) => urls.push(url),
|
||||
});
|
||||
expect(urls).toEqual([issueItem.url]);
|
||||
expect(result).toEqual({ status: "missing" });
|
||||
expect(submitted).toEqual([]);
|
||||
});
|
||||
|
||||
it("removes the queued entry and submits its text + attachments", async () => {
|
||||
const review = reviewWorkspaceAttachment("Queued for send.");
|
||||
const queue = createFakeQueue(
|
||||
new Map([["agent", [{ id: "msg-1", text: "send me", attachments: [review] }]]]),
|
||||
);
|
||||
const submitted: Array<{ text: string; attachments: ComposerAttachment[] }> = [];
|
||||
const result = await sendQueuedComposerMessageNow({
|
||||
agentId: "agent",
|
||||
messageId: "msg-1",
|
||||
queue,
|
||||
submitMessage: async (input) => {
|
||||
submitted.push(input);
|
||||
},
|
||||
});
|
||||
expect(result).toEqual({ status: "submitted" });
|
||||
expect(queue.state.get("agent")).toEqual([]);
|
||||
expect(submitted).toEqual([{ text: "send me", attachments: [review] }]);
|
||||
});
|
||||
|
||||
it("restores the queued entry to the front and surfaces the error message on failure", async () => {
|
||||
const queue = createFakeQueue(
|
||||
new Map([
|
||||
[
|
||||
"agent",
|
||||
[
|
||||
{ id: "msg-1", text: "first", attachments: [] },
|
||||
{ id: "msg-2", text: "second", attachments: [] },
|
||||
],
|
||||
],
|
||||
]),
|
||||
);
|
||||
const result = await sendQueuedComposerMessageNow({
|
||||
agentId: "agent",
|
||||
messageId: "msg-1",
|
||||
queue,
|
||||
submitMessage: async () => {
|
||||
throw new Error("network down");
|
||||
},
|
||||
});
|
||||
expect(result).toEqual({ status: "failed", errorMessage: "network down" });
|
||||
const state = queue.state.get("agent");
|
||||
expect(state?.map((m) => m.id)).toEqual(["msg-1", "msg-2"]);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,40 +1,35 @@
|
||||
import type { SelectedFile } from "@/attachments/selected-file";
|
||||
import { prepareImageAttachmentsForSend } from "@/attachments/service";
|
||||
import { FILE_UPLOAD_MAX_BYTES } from "@/attachments/upload-limit";
|
||||
import type { AgentProvider, ProviderOptions } from "@getpaseo/protocol/agent-types";
|
||||
import type {
|
||||
ActiveTurnBehavior,
|
||||
AgentActiveTurnBehavior,
|
||||
AgentAttachment,
|
||||
AgentSnapshotPayload,
|
||||
ForgeSearchItem,
|
||||
UploadedFileAttachment,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
import { AgentProviderSwitchError } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { StagedProviderSwitch } from "@/composer/provider-switch";
|
||||
import type {
|
||||
AttachmentMetadata,
|
||||
ComposerAttachment,
|
||||
UserComposerAttachment,
|
||||
} from "@/attachments/types";
|
||||
import { isWorkspaceAttachment } from "@/attachments/workspace-attachment-utils";
|
||||
import { forgeItemKey } from "@/composer/attachments/forge-item-key";
|
||||
import {
|
||||
isWorkspaceAttachment,
|
||||
userAttachmentsOnly,
|
||||
} from "@/attachments/workspace-attachment-utils";
|
||||
import {
|
||||
splitComposerAttachmentsForSubmit,
|
||||
type ComposerAttachmentSubmitFormat,
|
||||
} from "@/composer/attachments/submit";
|
||||
import {
|
||||
createPendingProviderSwitchItem,
|
||||
createUserMessage,
|
||||
generateMessageId,
|
||||
toDaemonUploadedImageAttachments,
|
||||
type ProviderSwitchItem,
|
||||
type UserMessageItem,
|
||||
} from "@/types/stream";
|
||||
import { createUserMessage, generateMessageId, type UserMessageItem } from "@/types/stream";
|
||||
import type { MessageSubmissionRejectionOutcome } from "@/composer/submission/model";
|
||||
import type { PickedImageAttachmentInput } from "@/hooks/image-attachment-picker";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
|
||||
export interface QueuedComposerMessage {
|
||||
id: string;
|
||||
text: string;
|
||||
attachments: ComposerAttachment[];
|
||||
}
|
||||
|
||||
export interface AttachmentPersister {
|
||||
persistFromBlob: (input: {
|
||||
blob: Blob;
|
||||
@@ -60,26 +55,11 @@ export interface ComposerSendClient {
|
||||
text: string,
|
||||
options: {
|
||||
messageId: string;
|
||||
activeTurnBehavior?: AgentActiveTurnBehavior;
|
||||
activeTurnBehavior?: ActiveTurnBehavior;
|
||||
images?: Array<{ data: string; mimeType: string }>;
|
||||
attachments: ReturnType<typeof splitComposerAttachmentsForSubmit>["attachments"];
|
||||
},
|
||||
) => Promise<unknown>;
|
||||
switchAgentProvider?: (
|
||||
agentId: string,
|
||||
options: {
|
||||
provider: AgentProvider;
|
||||
model?: string | null;
|
||||
modeId?: string | null;
|
||||
thinkingOptionId?: string | null;
|
||||
providerOptions?: ProviderOptions;
|
||||
text: string;
|
||||
messageId: string;
|
||||
images?: Array<{ data: string; mimeType: string }>;
|
||||
attachments?: ReturnType<typeof splitComposerAttachmentsForSubmit>["attachments"];
|
||||
activeTurnBehavior?: "queue";
|
||||
},
|
||||
) => Promise<{ agent?: AgentSnapshotPayload }>;
|
||||
uploadFile: (input: { fileName: string; mimeType: string; bytes: Uint8Array }) => Promise<{
|
||||
requestId: string;
|
||||
file: UploadedFileAttachment | null;
|
||||
@@ -93,15 +73,18 @@ export interface ComposerCancelClient {
|
||||
}
|
||||
|
||||
export interface MessageSubmissionWriter {
|
||||
begin: (
|
||||
agentId: string,
|
||||
message: UserMessageItem,
|
||||
options?: { providerSwitch?: ProviderSwitchItem },
|
||||
) => void;
|
||||
begin: (agentId: string, message: UserMessageItem) => void;
|
||||
accept: (agentId: string, clientMessageId: string) => void;
|
||||
reject: (agentId: string, clientMessageId: string) => MessageSubmissionRejectionOutcome;
|
||||
}
|
||||
|
||||
export interface QueueWriter {
|
||||
read: (agentId: string) => QueuedComposerMessage[];
|
||||
write: (
|
||||
updater: (prev: Map<string, QueuedComposerMessage[]>) => Map<string, QueuedComposerMessage[]>,
|
||||
) => void;
|
||||
}
|
||||
|
||||
export async function pickAndPersistImages(input: {
|
||||
pickImages: () => Promise<PickedImageAttachmentInput[] | null>;
|
||||
persister: Pick<
|
||||
@@ -210,33 +193,6 @@ export interface DispatchComposerAgentMessageInput {
|
||||
submission: MessageSubmissionWriter;
|
||||
activeTurnBehavior?: ActiveTurnBehavior;
|
||||
activeTurnId?: string;
|
||||
currentProvider?: AgentProvider | null;
|
||||
currentModel?: string | null;
|
||||
stagedProviderSwitch?: StagedProviderSwitch | null;
|
||||
onProviderSwitchCommitted?: (agent: AgentSnapshotPayload | undefined) => void | Promise<void>;
|
||||
}
|
||||
|
||||
function buildPendingProviderSwitch(
|
||||
input: DispatchComposerAgentMessageInput,
|
||||
clientMessageId: string,
|
||||
timestamp: Date,
|
||||
): ProviderSwitchItem | undefined {
|
||||
if (
|
||||
!input.stagedProviderSwitch ||
|
||||
!input.client.switchAgentProvider ||
|
||||
!input.currentProvider ||
|
||||
input.stagedProviderSwitch.provider === input.currentProvider
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
return createPendingProviderSwitchItem({
|
||||
clientMessageId,
|
||||
fromProvider: input.currentProvider,
|
||||
toProvider: input.stagedProviderSwitch.provider,
|
||||
fromModel: input.currentModel ?? null,
|
||||
toModel: input.stagedProviderSwitch.model,
|
||||
timestamp,
|
||||
});
|
||||
}
|
||||
|
||||
export async function dispatchComposerAgentMessage(
|
||||
@@ -246,42 +202,24 @@ export async function dispatchComposerAgentMessage(
|
||||
format: input.attachmentSubmitFormat,
|
||||
});
|
||||
const clientMessageId = generateMessageId();
|
||||
const timestamp = new Date();
|
||||
const sent = separateUploadedImages(wirePayload.attachments);
|
||||
const userMessage = createUserMessage({
|
||||
clientMessageId,
|
||||
text: input.text,
|
||||
timestamp,
|
||||
images: [...wirePayload.images, ...sent.images],
|
||||
attachments: sent.attachments,
|
||||
...(input.activeTurnBehavior === "steer" && input.activeTurnId && !input.stagedProviderSwitch
|
||||
timestamp: new Date(),
|
||||
images: wirePayload.images,
|
||||
attachments: wirePayload.attachments,
|
||||
...(input.activeTurnBehavior === "steer" && input.activeTurnId
|
||||
? { turnId: input.activeTurnId }
|
||||
: {}),
|
||||
});
|
||||
const pendingProviderSwitch = buildPendingProviderSwitch(input, clientMessageId, timestamp);
|
||||
input.submission.begin(
|
||||
input.agentId,
|
||||
userMessage,
|
||||
pendingProviderSwitch ? { providerSwitch: pendingProviderSwitch } : undefined,
|
||||
);
|
||||
input.submission.begin(input.agentId, userMessage);
|
||||
try {
|
||||
const imagePayload = await prepareImagePayload(input, wirePayload.images);
|
||||
if (input.stagedProviderSwitch && input.client.switchAgentProvider) {
|
||||
const result = await input.client.switchAgentProvider(input.agentId, {
|
||||
provider: input.stagedProviderSwitch.provider,
|
||||
model: input.stagedProviderSwitch.model,
|
||||
modeId: input.stagedProviderSwitch.modeId,
|
||||
thinkingOptionId: input.stagedProviderSwitch.thinkingOptionId,
|
||||
providerOptions: input.stagedProviderSwitch.providerOptions,
|
||||
text: input.text,
|
||||
messageId: clientMessageId,
|
||||
...(imagePayload.images ? { images: imagePayload.images } : {}),
|
||||
attachments: [...wirePayload.attachments, ...(imagePayload.attachments ?? [])],
|
||||
});
|
||||
input.submission.accept(input.agentId, clientMessageId);
|
||||
await input.onProviderSwitchCommitted?.(result.agent);
|
||||
return;
|
||||
}
|
||||
const imagePayload = input.uploadImages
|
||||
? { attachments: await input.uploadImages(wirePayload.images) }
|
||||
: await prepareImageAttachmentsForSend({
|
||||
client: input.client,
|
||||
images: wirePayload.images,
|
||||
});
|
||||
await input.client.sendAgentMessage(input.agentId, input.text, {
|
||||
messageId: clientMessageId,
|
||||
...(input.activeTurnBehavior ? { activeTurnBehavior: input.activeTurnBehavior } : {}),
|
||||
@@ -291,77 +229,112 @@ export async function dispatchComposerAgentMessage(
|
||||
input.submission.accept(input.agentId, clientMessageId);
|
||||
} catch (error) {
|
||||
input.submission.reject(input.agentId, clientMessageId);
|
||||
if (error instanceof AgentProviderSwitchError && error.agent) {
|
||||
await input.onProviderSwitchCommitted?.(error.agent);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function prepareImagePayload(
|
||||
input: Pick<DispatchComposerAgentMessageInput, "client" | "uploadImages">,
|
||||
images: AttachmentMetadata[],
|
||||
) {
|
||||
if (input.uploadImages) return { attachments: await input.uploadImages(images) };
|
||||
return await prepareImageAttachmentsForSend({ client: input.client, images });
|
||||
export interface QueueComposerMessageInput {
|
||||
agentId: string;
|
||||
text: string;
|
||||
attachments: ComposerAttachment[];
|
||||
queue: QueueWriter;
|
||||
}
|
||||
|
||||
/** Images the host already holds render as images, the way its timeline echo does. */
|
||||
function separateUploadedImages(attachments: AgentAttachment[]) {
|
||||
const uploads: UploadedFileAttachment[] = [];
|
||||
const rest: AgentAttachment[] = [];
|
||||
for (const attachment of attachments) {
|
||||
if (attachment.type === "uploaded_file" && attachment.role === "image") {
|
||||
uploads.push(attachment);
|
||||
} else {
|
||||
rest.push(attachment);
|
||||
}
|
||||
export interface QueueComposerMessageResult {
|
||||
queued: QueuedComposerMessage | null;
|
||||
}
|
||||
|
||||
export function queueComposerMessage(input: QueueComposerMessageInput): QueueComposerMessageResult {
|
||||
const trimmed = input.text.trim();
|
||||
if (!trimmed && input.attachments.length === 0) {
|
||||
return { queued: null };
|
||||
}
|
||||
const images = toDaemonUploadedImageAttachments(
|
||||
uploads.map(({ id, fileName, mimeType, size, path }) => ({
|
||||
id,
|
||||
fileName,
|
||||
mimeType,
|
||||
size,
|
||||
path,
|
||||
})),
|
||||
);
|
||||
return { images: images ?? [], attachments: rest };
|
||||
}
|
||||
|
||||
/**
|
||||
* Hands a message to the host's queue. The timeline gets no row until the host dispatches it;
|
||||
* until then the queue track shows it. A staged provider switch goes with the message: the host
|
||||
* switches when the message's turn comes.
|
||||
*/
|
||||
export async function enqueueComposerAgentMessage(
|
||||
input: Omit<
|
||||
DispatchComposerAgentMessageInput,
|
||||
"submission" | "activeTurnBehavior" | "activeTurnId" | "onProviderSwitchCommitted"
|
||||
> & { onProviderSwitchQueued?: () => void },
|
||||
): Promise<void> {
|
||||
const text = input.text.trim();
|
||||
if (!text && input.attachments.length === 0) return;
|
||||
const wirePayload = splitComposerAttachmentsForSubmit(input.attachments, {
|
||||
format: input.attachmentSubmitFormat,
|
||||
});
|
||||
const imagePayload = await prepareImagePayload(input, wirePayload.images);
|
||||
const queued = {
|
||||
messageId: generateMessageId(),
|
||||
activeTurnBehavior: "queue" as const,
|
||||
...(imagePayload.images ? { images: imagePayload.images } : {}),
|
||||
attachments: [...wirePayload.attachments, ...(imagePayload.attachments ?? [])],
|
||||
const item: QueuedComposerMessage = {
|
||||
id: generateMessageId(),
|
||||
text: trimmed,
|
||||
attachments: input.attachments,
|
||||
};
|
||||
if (input.stagedProviderSwitch && input.client.switchAgentProvider) {
|
||||
await input.client.switchAgentProvider(input.agentId, {
|
||||
...input.stagedProviderSwitch,
|
||||
...queued,
|
||||
text,
|
||||
input.queue.write((prev) => {
|
||||
const next = new Map(prev);
|
||||
next.set(input.agentId, [...(prev.get(input.agentId) ?? []), item]);
|
||||
return next;
|
||||
});
|
||||
return { queued: item };
|
||||
}
|
||||
|
||||
export interface EditQueuedComposerMessageInput {
|
||||
agentId: string;
|
||||
messageId: string;
|
||||
queue: QueueWriter;
|
||||
}
|
||||
|
||||
export interface EditQueuedComposerMessageResult {
|
||||
text: string;
|
||||
attachments: UserComposerAttachment[];
|
||||
}
|
||||
|
||||
export function editQueuedComposerMessage(
|
||||
input: EditQueuedComposerMessageInput,
|
||||
): EditQueuedComposerMessageResult | null {
|
||||
const item = input.queue.read(input.agentId).find((q) => q.id === input.messageId);
|
||||
if (!item) return null;
|
||||
input.queue.write((prev) => {
|
||||
const next = new Map(prev);
|
||||
next.set(
|
||||
input.agentId,
|
||||
(prev.get(input.agentId) ?? []).filter((q) => q.id !== input.messageId),
|
||||
);
|
||||
return next;
|
||||
});
|
||||
return {
|
||||
text: item.text,
|
||||
attachments: userAttachmentsOnly(item.attachments),
|
||||
};
|
||||
}
|
||||
|
||||
export interface SendQueuedComposerMessageNowInput {
|
||||
agentId: string;
|
||||
messageId: string;
|
||||
queue: QueueWriter;
|
||||
submitMessage: (input: { text: string; attachments: ComposerAttachment[] }) => Promise<void>;
|
||||
failedToSendMessage?: string;
|
||||
}
|
||||
|
||||
export type SendQueuedComposerMessageNowResult =
|
||||
| { status: "missing" }
|
||||
| { status: "submitted" }
|
||||
| { status: "failed"; errorMessage: string };
|
||||
|
||||
export async function sendQueuedComposerMessageNow(
|
||||
input: SendQueuedComposerMessageNowInput,
|
||||
): Promise<SendQueuedComposerMessageNowResult> {
|
||||
const item = input.queue.read(input.agentId).find((q) => q.id === input.messageId);
|
||||
if (!item) return { status: "missing" };
|
||||
input.queue.write((prev) => {
|
||||
const next = new Map(prev);
|
||||
next.set(
|
||||
input.agentId,
|
||||
(prev.get(input.agentId) ?? []).filter((q) => q.id !== input.messageId),
|
||||
);
|
||||
return next;
|
||||
});
|
||||
try {
|
||||
await input.submitMessage({ text: item.text, attachments: item.attachments });
|
||||
return { status: "submitted" };
|
||||
} catch (error) {
|
||||
input.queue.write((prev) => {
|
||||
const next = new Map(prev);
|
||||
next.set(input.agentId, [item, ...(prev.get(input.agentId) ?? [])]);
|
||||
return next;
|
||||
});
|
||||
input.onProviderSwitchQueued?.();
|
||||
return;
|
||||
return {
|
||||
status: "failed",
|
||||
errorMessage:
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: (input.failedToSendMessage ?? i18n.t("composer.errors.failedToSend")),
|
||||
};
|
||||
}
|
||||
await input.client.sendAgentMessage(input.agentId, text, queued);
|
||||
}
|
||||
|
||||
export interface OpenComposerAttachmentInput {
|
||||
@@ -379,13 +352,6 @@ export function openComposerAttachment(input: OpenComposerAttachmentInput): void
|
||||
if (input.attachment.kind === "file" || input.attachment.kind === "workspace_file") {
|
||||
return;
|
||||
}
|
||||
if (input.attachment.kind === "agent_attachment") {
|
||||
// An uploaded image opens through its pill, which holds the downloaded copy.
|
||||
if ("url" in input.attachment.attachment) {
|
||||
input.openExternalUrl(input.attachment.attachment.url);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (isWorkspaceAttachment(input.attachment)) {
|
||||
input.openWorkspaceAttachment({ attachment: input.attachment });
|
||||
return;
|
||||
@@ -399,11 +365,31 @@ export function buildForgeAttachment(item: ForgeSearchItem): UserComposerAttachm
|
||||
: { kind: "forge_issue", item };
|
||||
}
|
||||
|
||||
function isForgeAttachment(
|
||||
attachment: UserComposerAttachment,
|
||||
): attachment is Extract<
|
||||
UserComposerAttachment,
|
||||
{ kind: "forge_issue" | "forge_change_request" | "github_issue" | "github_pr" }
|
||||
> {
|
||||
return (
|
||||
attachment.kind === "forge_issue" ||
|
||||
attachment.kind === "forge_change_request" ||
|
||||
// COMPAT(githubAttachmentKinds): accept legacy persisted attachment kinds
|
||||
// until 2027-01-17, when supported floors are >= v0.2.0 and old drafts no
|
||||
// longer require them.
|
||||
attachment.kind === "github_issue" ||
|
||||
attachment.kind === "github_pr"
|
||||
);
|
||||
}
|
||||
|
||||
export function toggleForgeAttachment(
|
||||
current: UserComposerAttachment[],
|
||||
item: ForgeSearchItem,
|
||||
): UserComposerAttachment[] {
|
||||
const matches = (attachment: UserComposerAttachment) => isSameForgeItem(attachment, item);
|
||||
const matches = (attachment: UserComposerAttachment) =>
|
||||
isForgeAttachment(attachment) &&
|
||||
attachment.item.kind === item.kind &&
|
||||
attachment.item.number === item.number;
|
||||
if (current.some(matches)) {
|
||||
return current.filter((attachment) => !matches(attachment));
|
||||
}
|
||||
@@ -421,7 +407,12 @@ export function toggleForgeAttachmentFromPicker({
|
||||
item,
|
||||
markForgeAttachmentRemoved,
|
||||
}: ToggleForgeAttachmentFromPickerInput): UserComposerAttachment[] {
|
||||
const existingAttachment = current.find((attachment) => isSameForgeItem(attachment, item));
|
||||
const existingAttachment = current.find(
|
||||
(attachment) =>
|
||||
isForgeAttachment(attachment) &&
|
||||
attachment.item.kind === item.kind &&
|
||||
attachment.item.number === item.number,
|
||||
);
|
||||
if (existingAttachment) {
|
||||
markForgeAttachmentRemoved(existingAttachment);
|
||||
}
|
||||
@@ -439,9 +430,10 @@ export function isAttachmentSelectedForForgeItem(
|
||||
current: readonly ComposerAttachment[],
|
||||
item: ForgeSearchItem,
|
||||
): boolean {
|
||||
return current.some((attachment) => isSameForgeItem(attachment, item));
|
||||
}
|
||||
|
||||
function isSameForgeItem(attachment: ComposerAttachment, item: ForgeSearchItem): boolean {
|
||||
return forgeItemKey(attachment) === `${item.kind}:${item.number}`;
|
||||
return userAttachmentsOnly(current).some(
|
||||
(attachment) =>
|
||||
isForgeAttachment(attachment) &&
|
||||
attachment.item.kind === item.kind &&
|
||||
attachment.item.number === item.number,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -16,21 +16,12 @@ import { formatThinkingOptionLabel } from "@/agent-controls/labels";
|
||||
import { CombinedModelSelector } from "@/components/combined-model-selector";
|
||||
import {
|
||||
buildProviderSelectorProviders,
|
||||
buildSelectableProviderSelectorProviders,
|
||||
buildSelectorProvider,
|
||||
type ProviderSelectorProvider,
|
||||
} from "@/provider-selection/provider-selection";
|
||||
import { filterSelectableModels } from "@/provider-selection/model-catalog";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
|
||||
import { useDraftProviderOptions } from "@/hooks/use-draft-provider-options";
|
||||
import {
|
||||
clearStagedProviderSwitch,
|
||||
isStagedProviderSwitchInFlight,
|
||||
type StagedProviderSwitch,
|
||||
useStagedProviderSwitch,
|
||||
useStagedProviderSwitchStore,
|
||||
} from "@/composer/provider-switch";
|
||||
import { resolveProviderDefinition } from "@/utils/provider-definitions";
|
||||
import { mergeProviderPreferences, useFormPreferences } from "@/hooks/use-form-preferences";
|
||||
import {
|
||||
@@ -113,7 +104,6 @@ import {
|
||||
type AgentProfilePicker,
|
||||
type AgentProfileSeed,
|
||||
type DraftAgentProfileControls,
|
||||
type MaterializedAgentProfile,
|
||||
} from "@/agent-profiles";
|
||||
import { buildSettingsHostSectionRoute } from "@/utils/host-routes";
|
||||
|
||||
@@ -1006,148 +996,6 @@ function useAgentOptionControls(
|
||||
);
|
||||
}
|
||||
|
||||
function resolveActiveStagedSwitch(
|
||||
supportsProviderSwitching: boolean,
|
||||
rawStagedSwitch: StagedProviderSwitch | null,
|
||||
liveProvider: string | undefined,
|
||||
): StagedProviderSwitch | null {
|
||||
if (!supportsProviderSwitching || !rawStagedSwitch || !liveProvider) {
|
||||
return null;
|
||||
}
|
||||
return rawStagedSwitch.provider !== liveProvider ? rawStagedSwitch : null;
|
||||
}
|
||||
|
||||
function resolveDraftTargetModelId(
|
||||
modelId: string,
|
||||
preferredModel: string | undefined,
|
||||
nextModels: AgentModelDefinition[] | null,
|
||||
): string | null {
|
||||
if (modelId) return modelId;
|
||||
if (preferredModel) return preferredModel;
|
||||
const defaultModel = nextModels?.find((m) => m.isDefault);
|
||||
return defaultModel?.id ?? nextModels?.[0]?.id ?? null;
|
||||
}
|
||||
|
||||
function resolveDraftThinkingOptionId(
|
||||
targetModelId: string | null,
|
||||
targetModel: AgentModelDefinition | undefined,
|
||||
thinkingByModel: Record<string, string> | undefined,
|
||||
): string | null {
|
||||
const preferred = targetModelId ? thinkingByModel?.[targetModelId] : undefined;
|
||||
if (preferred) return preferred;
|
||||
return targetModel?.defaultThinkingOptionId ?? targetModel?.thinkingOptions?.[0]?.id ?? null;
|
||||
}
|
||||
|
||||
function resolveDraftModeId(
|
||||
preferredMode: string | undefined,
|
||||
nextEntry: ReturnType<typeof resolveProviderSnapshotEntry>,
|
||||
): string | null {
|
||||
if (preferredMode) return preferredMode;
|
||||
return nextEntry?.defaultModeId ?? nextEntry?.modes?.[0]?.id ?? null;
|
||||
}
|
||||
|
||||
function buildStagedProviderSwitchDraft(input: {
|
||||
nextProvider: string;
|
||||
modelId: string;
|
||||
snapshotEntries: ReturnType<typeof useProvidersSnapshot>["entries"];
|
||||
providerPreferences: ReturnType<typeof useFormPreferences>["preferences"]["providerPreferences"];
|
||||
}): StagedProviderSwitch {
|
||||
const { nextProvider, modelId, snapshotEntries, providerPreferences } = input;
|
||||
const nextEntry = resolveProviderSnapshotEntry(snapshotEntries, nextProvider);
|
||||
const nextModels = filterSelectableModels(nextEntry?.models ?? null);
|
||||
const preferred = providerPreferences?.[nextProvider];
|
||||
const targetModelId = resolveDraftTargetModelId(modelId, preferred?.model, nextModels);
|
||||
const targetModel = nextModels?.find((m) => m.id === targetModelId);
|
||||
return {
|
||||
provider: nextProvider,
|
||||
model: targetModelId,
|
||||
thinkingOptionId: resolveDraftThinkingOptionId(
|
||||
targetModelId,
|
||||
targetModel,
|
||||
preferred?.thinkingByModel,
|
||||
),
|
||||
modeId: resolveDraftModeId(preferred?.mode, nextEntry),
|
||||
providerOptions: preferred?.options ? { ...preferred.options } : {},
|
||||
};
|
||||
}
|
||||
|
||||
function resolveAgentModelSelectionWithStagedSwitch(input: {
|
||||
models: AgentModelDefinition[] | null;
|
||||
agent: AgentControlsSlice;
|
||||
activeStagedSwitch: StagedProviderSwitch | null;
|
||||
}) {
|
||||
const { models, agent, activeStagedSwitch } = input;
|
||||
return resolveAgentModelSelection({
|
||||
models,
|
||||
runtimeModelId: activeStagedSwitch ? null : agent?.runtimeModelId,
|
||||
configuredModelId: activeStagedSwitch ? activeStagedSwitch.model : agent?.model,
|
||||
runtimeThinkingOptionId: activeStagedSwitch ? null : agent?.runtimeThinkingOptionId,
|
||||
explicitThinkingOptionId: activeStagedSwitch
|
||||
? activeStagedSwitch.thinkingOptionId
|
||||
: agent?.thinkingOptionId,
|
||||
});
|
||||
}
|
||||
|
||||
function buildStagedDraftOptionsParams(input: {
|
||||
serverId: string;
|
||||
agentCwd: string | null | undefined;
|
||||
activeStagedSwitch: StagedProviderSwitch | null;
|
||||
getProvider: () => AgentProvider | null;
|
||||
modelId: string | null;
|
||||
thinkingOptionId: string | null;
|
||||
}) {
|
||||
const { serverId, agentCwd, activeStagedSwitch, getProvider, modelId, thinkingOptionId } = input;
|
||||
return {
|
||||
serverId: activeStagedSwitch ? serverId : null,
|
||||
provider: activeStagedSwitch ? activeStagedSwitch.provider : null,
|
||||
getProvider,
|
||||
cwd: agentCwd,
|
||||
modeId: activeStagedSwitch?.modeId ?? null,
|
||||
modelId,
|
||||
thinkingOptionId,
|
||||
initialOptions: activeStagedSwitch?.providerOptions,
|
||||
};
|
||||
}
|
||||
|
||||
function resolveAgentOptionControlsForComposer(input: {
|
||||
activeStagedSwitch: StagedProviderSwitch | null;
|
||||
stagedControls: ComposerOptionControls | null | undefined;
|
||||
liveOptionControls: ComposerOptionControls;
|
||||
onSetOption: (key: string, value: unknown) => void;
|
||||
}): ComposerOptionControls {
|
||||
const { activeStagedSwitch, stagedControls, liveOptionControls, onSetOption } = input;
|
||||
if (!activeStagedSwitch) {
|
||||
return liveOptionControls;
|
||||
}
|
||||
if (stagedControls) {
|
||||
return { ...stagedControls, onSetOption };
|
||||
}
|
||||
return { controls: [], options: activeStagedSwitch.providerOptions, onSetOption };
|
||||
}
|
||||
|
||||
function resolveControlledAgentControlsProps(input: {
|
||||
effectiveProvider: string | undefined;
|
||||
liveProvider: string;
|
||||
selectedModelId: string | null;
|
||||
selectedThinkingId: string | null;
|
||||
thinkingOptions: AgentControlOption[];
|
||||
supportsProviderSwitching: boolean;
|
||||
handleSelectProviderAndModel: (provider: string, modelId: string) => void;
|
||||
snapshotIsLoading: boolean;
|
||||
selectedProviderIsLoading: boolean;
|
||||
}) {
|
||||
return {
|
||||
provider: input.effectiveProvider ?? input.liveProvider,
|
||||
selectedModelId: input.selectedModelId ?? undefined,
|
||||
selectedThinkingOptionId: input.selectedThinkingId ?? undefined,
|
||||
thinkingOptions: input.thinkingOptions.length > 0 ? input.thinkingOptions : undefined,
|
||||
onSelectProviderAndModel: input.supportsProviderSwitching
|
||||
? input.handleSelectProviderAndModel
|
||||
: undefined,
|
||||
isModelLoading: input.snapshotIsLoading || input.selectedProviderIsLoading,
|
||||
};
|
||||
}
|
||||
|
||||
export const AgentControls = memo(function AgentControls({
|
||||
showToolbar,
|
||||
agentId,
|
||||
@@ -1155,22 +1003,15 @@ export const AgentControls = memo(function AgentControls({
|
||||
onDropdownClose,
|
||||
isCompactLayout,
|
||||
}: AgentControlsProps) {
|
||||
const { preferences, updatePreferences } = useFormPreferences();
|
||||
const { updatePreferences } = useFormPreferences();
|
||||
const agent = useSessionStore(
|
||||
useShallow((state) => selectAgentControlsSlice(state, serverId, agentId)),
|
||||
);
|
||||
const client = useSessionStore((state) => state.sessions[serverId]?.client ?? null);
|
||||
const supportsProviderSwitching = useSessionStore(
|
||||
(state) => state.sessions[serverId]?.serverInfo?.features?.providerSwitching === true,
|
||||
);
|
||||
const rawStagedSwitch = useStagedProviderSwitch(serverId, agentId);
|
||||
const activeStagedSwitch = resolveActiveStagedSwitch(
|
||||
supportsProviderSwitching,
|
||||
rawStagedSwitch,
|
||||
agent?.provider,
|
||||
);
|
||||
const toast = useToast();
|
||||
const liveModeControl = useLiveAgentModeControl(serverId, agentId);
|
||||
const modeControl = useLiveAgentModeControl(serverId, agentId);
|
||||
const commandCenterModes = toCommandCenterModes(modeControl);
|
||||
const modeProviderDefinitions = getModeProviderDefinitions(modeControl);
|
||||
|
||||
const {
|
||||
entries: snapshotEntries,
|
||||
@@ -1180,35 +1021,24 @@ export const AgentControls = memo(function AgentControls({
|
||||
refetchIfStale: refetchSnapshotIfStale,
|
||||
} = useProvidersSnapshot(serverId, { cwd: agent?.cwd });
|
||||
|
||||
const stagedProvider = activeStagedSwitch ? activeStagedSwitch.provider : null;
|
||||
const effectiveProvider = stagedProvider ?? agent?.provider;
|
||||
const stagedProviderRef = useRef<AgentProvider | null>(stagedProvider);
|
||||
stagedProviderRef.current = stagedProvider;
|
||||
|
||||
const snapshotSelectedEntry = useMemo(
|
||||
() => resolveProviderSnapshotEntry(snapshotEntries, effectiveProvider),
|
||||
[snapshotEntries, effectiveProvider],
|
||||
() => resolveProviderSnapshotEntry(snapshotEntries, agent?.provider),
|
||||
[snapshotEntries, agent?.provider],
|
||||
);
|
||||
|
||||
const models = filterSelectableModels(snapshotSelectedEntry?.models ?? null);
|
||||
const selectedProviderIsLoading = snapshotSelectedEntry?.status === "loading";
|
||||
|
||||
const agentProviderDefinitions = useMemo(
|
||||
() => buildAgentProviderDefinitions(effectiveProvider, snapshotEntries),
|
||||
[effectiveProvider, snapshotEntries],
|
||||
() => buildAgentProviderDefinitions(agent?.provider, snapshotEntries),
|
||||
[agent?.provider, snapshotEntries],
|
||||
);
|
||||
|
||||
const agentProviderModels = useMemo(
|
||||
() => buildAgentProviderModels(effectiveProvider, models),
|
||||
[effectiveProvider, models],
|
||||
() => buildAgentProviderModels(agent?.provider, models),
|
||||
[agent?.provider, models],
|
||||
);
|
||||
const agentModelSelectorProviders = useMemo(() => {
|
||||
if (supportsProviderSwitching && snapshotEntries && snapshotEntries.length > 0) {
|
||||
const selectable = buildSelectableProviderSelectorProviders(snapshotEntries, {
|
||||
selectedProvider: effectiveProvider ?? null,
|
||||
});
|
||||
if (selectable.length > 0) return selectable;
|
||||
}
|
||||
if (snapshotSelectedEntry) {
|
||||
return [buildSelectorProvider(snapshotSelectedEntry)];
|
||||
}
|
||||
@@ -1216,19 +1046,14 @@ export const AgentControls = memo(function AgentControls({
|
||||
providerDefinitions: agentProviderDefinitions,
|
||||
modelsByProvider: agentProviderModels,
|
||||
});
|
||||
}, [
|
||||
agentProviderDefinitions,
|
||||
agentProviderModels,
|
||||
effectiveProvider,
|
||||
snapshotEntries,
|
||||
snapshotSelectedEntry,
|
||||
supportsProviderSwitching,
|
||||
]);
|
||||
}, [agentProviderDefinitions, agentProviderModels, snapshotSelectedEntry]);
|
||||
|
||||
const modelSelection = resolveAgentModelSelectionWithStagedSwitch({
|
||||
const modelSelection = resolveAgentModelSelection({
|
||||
models,
|
||||
agent,
|
||||
activeStagedSwitch,
|
||||
runtimeModelId: agent?.runtimeModelId,
|
||||
configuredModelId: agent?.model,
|
||||
runtimeThinkingOptionId: agent?.runtimeThinkingOptionId,
|
||||
explicitThinkingOptionId: agent?.thinkingOptionId,
|
||||
});
|
||||
|
||||
const modelOptions = useMemo<AgentControlOption[]>(() => {
|
||||
@@ -1245,71 +1070,13 @@ export const AgentControls = memo(function AgentControls({
|
||||
const agentProvider = agent?.provider;
|
||||
const activeModelId = modelSelection.activeModelId;
|
||||
|
||||
const stagedModeOptions = useMemo<AgentMode[]>(() => {
|
||||
if (!activeStagedSwitch || !snapshotSelectedEntry?.modes) return [];
|
||||
return snapshotSelectedEntry.modes.map((mode) => ({
|
||||
id: mode.id,
|
||||
label: mode.label,
|
||||
description: mode.description ?? "",
|
||||
}));
|
||||
}, [activeStagedSwitch, snapshotSelectedEntry?.modes]);
|
||||
|
||||
const handleSelectStagedMode = useCallback(
|
||||
(modeId: string) => {
|
||||
useStagedProviderSwitchStore.getState().patch(serverId, agentId, (current) => ({
|
||||
...current,
|
||||
modeId,
|
||||
}));
|
||||
},
|
||||
[agentId, serverId],
|
||||
);
|
||||
|
||||
const modeControl = useMemo<AgentModeControlValue | null>(() => {
|
||||
if (!activeStagedSwitch) return liveModeControl;
|
||||
if (stagedModeOptions.length === 0) return null;
|
||||
return {
|
||||
provider: activeStagedSwitch.provider,
|
||||
providerDefinitions: agentProviderDefinitions,
|
||||
modeOptions: stagedModeOptions,
|
||||
selectedModeId:
|
||||
activeStagedSwitch.modeId ??
|
||||
snapshotSelectedEntry?.defaultModeId ??
|
||||
stagedModeOptions[0]?.id ??
|
||||
null,
|
||||
onSelectMode: handleSelectStagedMode,
|
||||
disabled: !client,
|
||||
};
|
||||
}, [
|
||||
activeStagedSwitch,
|
||||
agentProviderDefinitions,
|
||||
client,
|
||||
handleSelectStagedMode,
|
||||
liveModeControl,
|
||||
snapshotSelectedEntry?.defaultModeId,
|
||||
stagedModeOptions,
|
||||
]);
|
||||
const commandCenterModes = toCommandCenterModes(modeControl);
|
||||
const modeProviderDefinitions = getModeProviderDefinitions(modeControl);
|
||||
|
||||
const getStagedProvider = useCallback(() => stagedProviderRef.current, []);
|
||||
const stagedDraftOptions = useDraftProviderOptions(
|
||||
buildStagedDraftOptionsParams({
|
||||
serverId,
|
||||
agentCwd: agent?.cwd,
|
||||
activeStagedSwitch,
|
||||
getProvider: getStagedProvider,
|
||||
modelId: modelSelection.activeModelId,
|
||||
thinkingOptionId: modelSelection.selectedThinkingId,
|
||||
}),
|
||||
);
|
||||
|
||||
const applyLiveModel = useCallback(
|
||||
const handleSelectModel = useCallback(
|
||||
async (modelId: string) => {
|
||||
if (!client || !agentProvider) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await client.setAgentModel(agentId, modelId, { expectedProvider: agentProvider });
|
||||
await client.setAgentModel(agentId, modelId);
|
||||
await updatePreferences((current) =>
|
||||
mergeProviderPreferences({
|
||||
preferences: current,
|
||||
@@ -1324,147 +1091,21 @@ export const AgentControls = memo(function AgentControls({
|
||||
},
|
||||
[agentId, agentProvider, client, toast, updatePreferences],
|
||||
);
|
||||
|
||||
const handleSelectModel = useCallback(
|
||||
async (modelId: string) => {
|
||||
if (activeStagedSwitch) {
|
||||
const nextModel = models?.find((candidate) => candidate.id === modelId);
|
||||
const preferredThinking =
|
||||
preferences.providerPreferences?.[activeStagedSwitch.provider]?.thinkingByModel?.[
|
||||
modelId
|
||||
];
|
||||
const nextThinking =
|
||||
preferredThinking ??
|
||||
nextModel?.defaultThinkingOptionId ??
|
||||
nextModel?.thinkingOptions?.[0]?.id ??
|
||||
null;
|
||||
useStagedProviderSwitchStore.getState().patch(serverId, agentId, (current) => ({
|
||||
...current,
|
||||
model: modelId,
|
||||
thinkingOptionId: nextThinking,
|
||||
}));
|
||||
return;
|
||||
}
|
||||
await applyLiveModel(modelId);
|
||||
},
|
||||
[
|
||||
activeStagedSwitch,
|
||||
agentId,
|
||||
applyLiveModel,
|
||||
models,
|
||||
preferences.providerPreferences,
|
||||
serverId,
|
||||
],
|
||||
);
|
||||
|
||||
const handleSelectProviderAndModel = useCallback(
|
||||
(nextProvider: string, modelId: string) => {
|
||||
if (!agentProvider) return;
|
||||
if (nextProvider === agentProvider && !isStagedProviderSwitchInFlight(serverId, agentId)) {
|
||||
clearStagedProviderSwitch(serverId, agentId);
|
||||
const liveModelId = agent?.runtimeModelId ?? agent?.model ?? null;
|
||||
if (modelId && modelId !== liveModelId) {
|
||||
void applyLiveModel(modelId);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!supportsProviderSwitching) return;
|
||||
useStagedProviderSwitchStore.getState().stage(
|
||||
serverId,
|
||||
agentId,
|
||||
buildStagedProviderSwitchDraft({
|
||||
nextProvider,
|
||||
modelId,
|
||||
snapshotEntries,
|
||||
providerPreferences: preferences.providerPreferences,
|
||||
}),
|
||||
);
|
||||
},
|
||||
[
|
||||
agent?.model,
|
||||
agent?.runtimeModelId,
|
||||
agentId,
|
||||
agentProvider,
|
||||
applyLiveModel,
|
||||
preferences.providerPreferences,
|
||||
serverId,
|
||||
snapshotEntries,
|
||||
supportsProviderSwitching,
|
||||
],
|
||||
);
|
||||
|
||||
const handleSelectCommandCenterModel = useCallback(
|
||||
(provider: AgentProvider, modelId: string) => {
|
||||
if (supportsProviderSwitching) {
|
||||
handleSelectProviderAndModel(provider, modelId);
|
||||
return;
|
||||
}
|
||||
void handleSelectModel(modelId);
|
||||
},
|
||||
[handleSelectModel, handleSelectProviderAndModel, supportsProviderSwitching],
|
||||
(_provider: AgentProvider, modelId: string) => handleSelectModel(modelId),
|
||||
[handleSelectModel],
|
||||
);
|
||||
|
||||
const handleStageAgentProfileSwitch = useCallback(
|
||||
(resolved: MaterializedAgentProfile) => {
|
||||
if (!supportsProviderSwitching) return;
|
||||
const nextEntry = resolveProviderSnapshotEntry(snapshotEntries, resolved.provider);
|
||||
const modeIds = resolveSnapshotModeIds(nextEntry);
|
||||
const validModeId =
|
||||
resolved.modeId && (!modeIds || modeIds.includes(resolved.modeId))
|
||||
? resolved.modeId
|
||||
: (nextEntry?.defaultModeId ?? nextEntry?.modes?.[0]?.id ?? null);
|
||||
useStagedProviderSwitchStore.getState().stage(serverId, agentId, {
|
||||
provider: resolved.provider,
|
||||
model: resolved.modelId ?? null,
|
||||
modeId: validModeId,
|
||||
thinkingOptionId: resolved.thinkingOptionId ?? null,
|
||||
providerOptions: resolved.options ? { ...resolved.options } : {},
|
||||
});
|
||||
stagedDraftOptions.applyProfile({
|
||||
provider: resolved.provider,
|
||||
options: resolved.options ?? {},
|
||||
});
|
||||
},
|
||||
[agentId, serverId, snapshotEntries, stagedDraftOptions, supportsProviderSwitching],
|
||||
);
|
||||
|
||||
const handleClearStagedSwitchOnProfile = useCallback(() => {
|
||||
clearStagedProviderSwitch(serverId, agentId);
|
||||
}, [agentId, serverId]);
|
||||
|
||||
const profileProviders = useMemo(() => {
|
||||
if (supportsProviderSwitching) {
|
||||
return agentModelSelectorProviders.map((entry) => entry.id);
|
||||
}
|
||||
return agentProvider ? [agentProvider] : [];
|
||||
}, [agentModelSelectorProviders, agentProvider, supportsProviderSwitching]);
|
||||
const liveSnapshotEntry = useMemo(
|
||||
() => resolveProviderSnapshotEntry(snapshotEntries, agentProvider),
|
||||
[snapshotEntries, agentProvider],
|
||||
);
|
||||
// A running agent is one provider's process, so only that provider's profiles
|
||||
// can apply to it.
|
||||
const profileProviders = useMemo(() => (agentProvider ? [agentProvider] : []), [agentProvider]);
|
||||
const profileModeIds = useMemo(
|
||||
() => resolveSnapshotModeIds(liveSnapshotEntry),
|
||||
[liveSnapshotEntry],
|
||||
() => resolveSnapshotModeIds(snapshotSelectedEntry),
|
||||
[snapshotSelectedEntry],
|
||||
);
|
||||
const profileTarget = useMemo<AgentProfileApplyTarget>(
|
||||
() => ({
|
||||
kind: "agent",
|
||||
agentId,
|
||||
availableModeIds: profileModeIds,
|
||||
currentProvider: agentProvider,
|
||||
isSwitchInFlight: () => isStagedProviderSwitchInFlight(serverId, agentId),
|
||||
onApplySameProvider: handleClearStagedSwitchOnProfile,
|
||||
onStageProviderSwitch: supportsProviderSwitching ? handleStageAgentProfileSwitch : undefined,
|
||||
}),
|
||||
[
|
||||
agentId,
|
||||
agentProvider,
|
||||
handleClearStagedSwitchOnProfile,
|
||||
handleStageAgentProfileSwitch,
|
||||
profileModeIds,
|
||||
serverId,
|
||||
supportsProviderSwitching,
|
||||
],
|
||||
() => ({ kind: "agent", agentId, availableModeIds: profileModeIds }),
|
||||
[agentId, profileModeIds],
|
||||
);
|
||||
const agentProfiles = useAgentProfilePicker({
|
||||
serverId,
|
||||
@@ -1477,13 +1118,6 @@ export const AgentControls = memo(function AgentControls({
|
||||
|
||||
const handleSelectThinkingOption = useCallback(
|
||||
(thinkingOptionId: string) => {
|
||||
if (activeStagedSwitch) {
|
||||
useStagedProviderSwitchStore.getState().patch(serverId, agentId, (current) => ({
|
||||
...current,
|
||||
thinkingOptionId,
|
||||
}));
|
||||
return;
|
||||
}
|
||||
if (!client || !agentProvider) {
|
||||
return;
|
||||
}
|
||||
@@ -1504,35 +1138,18 @@ export const AgentControls = memo(function AgentControls({
|
||||
});
|
||||
}
|
||||
void client
|
||||
.setAgentThinkingOption(agentId, thinkingOptionId, { expectedProvider: agentProvider })
|
||||
.setAgentThinkingOption(agentId, thinkingOptionId)
|
||||
.then((notice) => showProviderNoticeToast(toast, notice))
|
||||
.catch((error) => {
|
||||
console.warn("[AgentControls] setAgentThinkingOption failed", error);
|
||||
toast.error(toErrorMessage(error));
|
||||
});
|
||||
},
|
||||
[
|
||||
activeModelId,
|
||||
activeStagedSwitch,
|
||||
agentId,
|
||||
agentProvider,
|
||||
client,
|
||||
serverId,
|
||||
toast,
|
||||
updatePreferences,
|
||||
],
|
||||
[activeModelId, agentId, agentProvider, client, toast, updatePreferences],
|
||||
);
|
||||
|
||||
const handleSetOption = useCallback(
|
||||
(key: string, value: unknown) => {
|
||||
if (activeStagedSwitch) {
|
||||
stagedDraftOptions.setOption(key, value);
|
||||
useStagedProviderSwitchStore.getState().patch(serverId, agentId, (current) => ({
|
||||
...current,
|
||||
providerOptions: { ...current.providerOptions, [key]: value },
|
||||
}));
|
||||
return;
|
||||
}
|
||||
if (!client || !agentProvider) {
|
||||
return;
|
||||
}
|
||||
@@ -1549,36 +1166,15 @@ export const AgentControls = memo(function AgentControls({
|
||||
).catch((error) => {
|
||||
console.warn("[AgentControls] persist option preference failed", error);
|
||||
});
|
||||
void client
|
||||
.setAgentOptions(agentId, { [key]: value }, { expectedProvider: agentProvider })
|
||||
.catch((error) => {
|
||||
console.warn("[AgentControls] setAgentOptions failed", error);
|
||||
toast.error(toErrorMessage(error));
|
||||
});
|
||||
void client.setAgentOptions(agentId, { [key]: value }).catch((error) => {
|
||||
console.warn("[AgentControls] setAgentOptions failed", error);
|
||||
toast.error(toErrorMessage(error));
|
||||
});
|
||||
},
|
||||
[
|
||||
activeStagedSwitch,
|
||||
agentId,
|
||||
agentProvider,
|
||||
client,
|
||||
serverId,
|
||||
stagedDraftOptions,
|
||||
toast,
|
||||
updatePreferences,
|
||||
],
|
||||
[agentId, agentProvider, client, toast, updatePreferences],
|
||||
);
|
||||
|
||||
const liveOptionControls = useAgentOptionControls(agent, handleSetOption);
|
||||
const agentOptionControls = useMemo<ComposerOptionControls>(
|
||||
() =>
|
||||
resolveAgentOptionControlsForComposer({
|
||||
activeStagedSwitch,
|
||||
stagedControls: stagedDraftOptions.optionControls,
|
||||
liveOptionControls,
|
||||
onSetOption: handleSetOption,
|
||||
}),
|
||||
[activeStagedSwitch, handleSetOption, liveOptionControls, stagedDraftOptions.optionControls],
|
||||
);
|
||||
const agentOptionControls = useAgentOptionControls(agent, handleSetOption);
|
||||
|
||||
// The agent's composer exists apart from this component; while this is mounted, prompt
|
||||
// commands go through the input the user is typing in.
|
||||
@@ -1602,12 +1198,12 @@ export const AgentControls = memo(function AgentControls({
|
||||
() => ({
|
||||
serverId,
|
||||
ownerKey: agentId,
|
||||
provider: effectiveProvider,
|
||||
provider: agentProvider,
|
||||
providerDefinitions: modeProviderDefinitions,
|
||||
profiles: agentProfiles,
|
||||
models: {
|
||||
providers: agentModelSelectorProviders,
|
||||
selectedProvider: effectiveProvider,
|
||||
selectedProvider: agentProvider,
|
||||
selectedModelId: activeModelId,
|
||||
select: handleSelectCommandCenterModel,
|
||||
},
|
||||
@@ -1626,7 +1222,7 @@ export const AgentControls = memo(function AgentControls({
|
||||
client,
|
||||
agentId,
|
||||
agentModelSelectorProviders,
|
||||
effectiveProvider,
|
||||
agentProvider,
|
||||
commandCenterModes,
|
||||
handleSelectCommandCenterModel,
|
||||
handleSelectThinkingOption,
|
||||
@@ -1646,8 +1242,8 @@ export const AgentControls = memo(function AgentControls({
|
||||
);
|
||||
|
||||
const handleModelSelectorOpen = useCallback(() => {
|
||||
refetchSnapshotIfStale(supportsProviderSwitching ? undefined : effectiveProvider);
|
||||
}, [effectiveProvider, refetchSnapshotIfStale, supportsProviderSwitching]);
|
||||
refetchSnapshotIfStale(agentProvider);
|
||||
}, [agentProvider, refetchSnapshotIfStale]);
|
||||
|
||||
const handleRetryModelProvider = useCallback(
|
||||
(provider: AgentProvider) => {
|
||||
@@ -1660,18 +1256,6 @@ export const AgentControls = memo(function AgentControls({
|
||||
return null;
|
||||
}
|
||||
|
||||
const resolvedControlProps = resolveControlledAgentControlsProps({
|
||||
effectiveProvider,
|
||||
liveProvider: agent.provider,
|
||||
selectedModelId: modelSelection.activeModelId,
|
||||
selectedThinkingId: modelSelection.selectedThinkingId,
|
||||
thinkingOptions,
|
||||
supportsProviderSwitching,
|
||||
handleSelectProviderAndModel,
|
||||
snapshotIsLoading,
|
||||
selectedProviderIsLoading,
|
||||
});
|
||||
|
||||
return (
|
||||
<ComposerModelProvider value={composer}>
|
||||
{commandCenterRegistration}
|
||||
@@ -1679,17 +1263,21 @@ export const AgentControls = memo(function AgentControls({
|
||||
<>
|
||||
{profileEditor.element}
|
||||
<ControlledAgentControls
|
||||
{...resolvedControlProps}
|
||||
provider={agent.provider}
|
||||
modelSelectorProviders={agentModelSelectorProviders}
|
||||
modelOptions={modelOptions}
|
||||
selectedModelId={modelSelection.activeModelId ?? undefined}
|
||||
onSelectModel={handleSelectModel}
|
||||
agentProfiles={agentProfiles}
|
||||
onApplyAgentProfile={agentProfiles?.applyProfile}
|
||||
onEditAgentProfiles={handleEditAgentProfiles}
|
||||
onCreateAgentProfile={profileActions.create}
|
||||
onEditAgentProfile={profileActions.edit}
|
||||
thinkingOptions={thinkingOptions.length > 0 ? thinkingOptions : undefined}
|
||||
selectedThinkingOptionId={modelSelection.selectedThinkingId ?? undefined}
|
||||
onSelectThinkingOption={handleSelectThinkingOption}
|
||||
optionControls={agentOptionControls}
|
||||
isModelLoading={snapshotIsLoading || selectedProviderIsLoading}
|
||||
onModelSelectorOpen={handleModelSelectorOpen}
|
||||
onRetryModelProvider={handleRetryModelProvider}
|
||||
isRetryingModelProvider={snapshotIsRefreshing}
|
||||
|
||||
@@ -296,7 +296,7 @@ export function useLiveAgentModeControl(
|
||||
console.warn("[AgentModeControl] persist mode preference failed", error);
|
||||
});
|
||||
void client
|
||||
.setAgentMode(agentId, modeId, { expectedProvider: slice.provider })
|
||||
.setAgentMode(agentId, modeId)
|
||||
.then((notice) => showProviderNoticeToast(toast, notice))
|
||||
.catch((error) => {
|
||||
console.warn("[AgentModeControl] setAgentMode failed", error);
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
import type { ComposerAttachment } from "@/attachments/types";
|
||||
import type { AgentAttachment } from "@getpaseo/protocol/messages";
|
||||
|
||||
/** `issue:101` or `change_request:202` for an attachment that points at a forge item. */
|
||||
export function forgeItemKey(attachment: ComposerAttachment | undefined): string | null {
|
||||
switch (attachment?.kind) {
|
||||
case "forge_issue":
|
||||
case "forge_change_request":
|
||||
// COMPAT(githubAttachmentKinds): accept legacy persisted attachment kinds
|
||||
// until 2027-01-17, when supported floors are >= v0.2.0 and old drafts no
|
||||
// longer require them.
|
||||
case "github_issue":
|
||||
case "github_pr":
|
||||
return `${attachment.item.kind}:${attachment.item.number}`;
|
||||
case "agent_attachment":
|
||||
return agentAttachmentForgeKey(attachment.attachment);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function agentAttachmentForgeKey(attachment: AgentAttachment): string | null {
|
||||
switch (attachment.type) {
|
||||
case "forge_issue":
|
||||
case "github_issue":
|
||||
return `issue:${attachment.number}`;
|
||||
case "forge_change_request":
|
||||
case "github_pr":
|
||||
return `change_request:${attachment.number}`;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,102 +0,0 @@
|
||||
import { useCallback, useMemo, type ReactElement } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
AttachmentLabel,
|
||||
AttachmentPill,
|
||||
AttachmentThumbnail,
|
||||
AttachmentThumbnailPlaceholder,
|
||||
} from "@/components/attachment-pill";
|
||||
import { getAgentAttachmentPillContent } from "@/attachments/attachment-pill-content";
|
||||
import type { ComposerAttachment } from "@/attachments/types";
|
||||
import { useDaemonUploadedImage } from "@/attachments/use-daemon-uploaded-image";
|
||||
import { useHostRuntimeClient } from "@/runtime/host-runtime";
|
||||
import type { UploadedFileAttachment } from "@getpaseo/protocol/messages";
|
||||
|
||||
type RestoredAttachment = Extract<ComposerAttachment, { kind: "agent_attachment" }>;
|
||||
|
||||
interface RestoredAttachmentPillProps {
|
||||
serverId: string;
|
||||
attachment: RestoredAttachment;
|
||||
index: number;
|
||||
disabled: boolean;
|
||||
onOpen: (attachment: ComposerAttachment) => void;
|
||||
onRemove: (index: number) => void;
|
||||
openImageLabel: string;
|
||||
removeImageLabel: string;
|
||||
}
|
||||
|
||||
/** The tray pill for an attachment taken back from a queued message. */
|
||||
export function RestoredAttachmentPill(props: RestoredAttachmentPillProps): ReactElement {
|
||||
const wire = props.attachment.attachment;
|
||||
if (wire.type === "uploaded_file" && wire.role === "image") {
|
||||
return <RestoredImagePill {...props} upload={wire} />;
|
||||
}
|
||||
return <RestoredLabelPill {...props} />;
|
||||
}
|
||||
|
||||
/** An image the host holds. It is downloaded to preview it, and sent again by reference. */
|
||||
function RestoredImagePill({
|
||||
serverId,
|
||||
upload,
|
||||
index,
|
||||
disabled,
|
||||
onOpen,
|
||||
onRemove,
|
||||
openImageLabel,
|
||||
removeImageLabel,
|
||||
}: RestoredAttachmentPillProps & { upload: UploadedFileAttachment }): ReactElement {
|
||||
const client = useHostRuntimeClient(serverId);
|
||||
const image = useMemo(
|
||||
() => ({
|
||||
id: upload.id,
|
||||
fileName: upload.fileName,
|
||||
mimeType: upload.mimeType,
|
||||
size: upload.size,
|
||||
path: upload.path,
|
||||
storageType: "daemon-upload" as const,
|
||||
}),
|
||||
[upload],
|
||||
);
|
||||
const metadata = useDaemonUploadedImage({ image, client, serverId });
|
||||
const handleOpen = useCallback(() => {
|
||||
if (metadata) onOpen({ kind: "image", metadata });
|
||||
}, [metadata, onOpen]);
|
||||
const handleRemove = useCallback(() => onRemove(index), [onRemove, index]);
|
||||
return (
|
||||
<AttachmentPill
|
||||
testID="composer-image-attachment-pill"
|
||||
onOpen={handleOpen}
|
||||
onRemove={handleRemove}
|
||||
openAccessibilityLabel={openImageLabel}
|
||||
removeAccessibilityLabel={removeImageLabel}
|
||||
disabled={disabled}
|
||||
>
|
||||
{metadata ? <AttachmentThumbnail metadata={metadata} /> : <AttachmentThumbnailPlaceholder />}
|
||||
</AttachmentPill>
|
||||
);
|
||||
}
|
||||
|
||||
function RestoredLabelPill({
|
||||
attachment,
|
||||
index,
|
||||
disabled,
|
||||
onOpen,
|
||||
onRemove,
|
||||
}: RestoredAttachmentPillProps): ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const content = getAgentAttachmentPillContent(attachment.attachment, t);
|
||||
const handleOpen = useCallback(() => onOpen(attachment), [onOpen, attachment]);
|
||||
const handleRemove = useCallback(() => onRemove(index), [onRemove, index]);
|
||||
return (
|
||||
<AttachmentPill
|
||||
testID="composer-restored-attachment-pill"
|
||||
onOpen={handleOpen}
|
||||
onRemove={handleRemove}
|
||||
openAccessibilityLabel={content.title}
|
||||
removeAccessibilityLabel={t("composer.attachments.removeAttachment")}
|
||||
disabled={disabled}
|
||||
>
|
||||
<AttachmentLabel icon={content.icon} title={content.title} subtitle={content.subtitle} />
|
||||
</AttachmentPill>
|
||||
);
|
||||
}
|
||||
@@ -55,11 +55,6 @@ export function splitComposerAttachmentsForSubmit(
|
||||
continue;
|
||||
}
|
||||
|
||||
if (attachment.kind === "agent_attachment") {
|
||||
agentAttachments.push(attachment.attachment);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (attachment.kind === "workspace_file") {
|
||||
agentAttachments.push(workspaceFileAttachmentToAgentAttachment(attachment));
|
||||
continue;
|
||||
|
||||
@@ -209,7 +209,7 @@ function useWorkspaceAttachmentBinding({
|
||||
|
||||
const completeSubmit = useCallback(
|
||||
({ result, outgoingAttachments }: CompleteSubmitInput) => {
|
||||
if (result === "submitted" || result === "queued") {
|
||||
if (result === "submitted") {
|
||||
clearSentAttachments(outgoingAttachments);
|
||||
}
|
||||
if (result === "queued" || result === "submitted" || result === "failed") {
|
||||
|
||||
@@ -82,8 +82,9 @@ function ComposerViewport({
|
||||
);
|
||||
}
|
||||
|
||||
/** Bound the complete composer slot (tracks and input) to the visible viewport capacity. */
|
||||
/** Bound the complete composer (including its controls), not just the text input. */
|
||||
function ComposerViewportContent({ style, ...props }: ViewProps) {
|
||||
const compact = useIsCompactFormFactor();
|
||||
const sizing = useContext(ViewportSizing);
|
||||
if (!sizing) throw new Error("ComposerViewportContent requires ComposerViewport");
|
||||
const constraint = useAnimatedStyle(() => ({
|
||||
@@ -92,60 +93,11 @@ function ComposerViewportContent({ style, ...props }: ViewProps) {
|
||||
// Fullscreen styles override it with a static minHeight instead of feeding the mode
|
||||
// in here: Reanimated applies a dependency change frames after the React commit,
|
||||
// so the fullscreen slot would paint clamped to the inline cap first.
|
||||
maxHeight: sizing.value?.capacity,
|
||||
}));
|
||||
|
||||
return (
|
||||
<Animated.View testID="composer-viewport-content" {...props} style={[style, constraint]} />
|
||||
);
|
||||
}
|
||||
|
||||
interface ComposerInputCapProps {
|
||||
fullscreen?: boolean;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cap the inline editing box below the dock's viewport capacity so tracks above it
|
||||
* (like the queued message list) keep room instead of collapsing when an attachment pill
|
||||
* or multi-line draft grows the input.
|
||||
*/
|
||||
export function ComposerInputCap({ fullscreen = false, children }: ComposerInputCapProps) {
|
||||
const compact = useIsCompactFormFactor();
|
||||
const sizing = useContext(ViewportSizing);
|
||||
if (!sizing) {
|
||||
return (
|
||||
<View style={fullscreen ? dockStyles.fullscreenFill : dockStyles.composer}>{children}</View>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<ConstrainedComposerInputCap sizing={sizing} compact={compact} fullscreen={fullscreen}>
|
||||
{children}
|
||||
</ConstrainedComposerInputCap>
|
||||
);
|
||||
}
|
||||
|
||||
function ConstrainedComposerInputCap({
|
||||
sizing,
|
||||
compact,
|
||||
fullscreen,
|
||||
children,
|
||||
}: {
|
||||
sizing: SharedValue<ComposerCapacity | undefined>;
|
||||
compact: boolean;
|
||||
fullscreen: boolean;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const constraint = useAnimatedStyle(() => ({
|
||||
maxHeight: resolveInlineComposerCapacity(sizing.value?.capacity, compact),
|
||||
}));
|
||||
|
||||
return (
|
||||
<Animated.View
|
||||
style={[fullscreen ? dockStyles.fullscreenSurface : dockStyles.composer, constraint]}
|
||||
>
|
||||
{children}
|
||||
</Animated.View>
|
||||
<Animated.View testID="composer-viewport-content" {...props} style={[style, constraint]} />
|
||||
);
|
||||
}
|
||||
|
||||
@@ -342,7 +294,6 @@ const dockStyles = StyleSheet.create({
|
||||
// Yoga applies minHeight after maxHeight, so this fills the viewport over the
|
||||
// inline cap that ComposerViewportContent keeps animating.
|
||||
fullscreenSurface: { flex: 1, minHeight: "100%" },
|
||||
fullscreenFill: { flex: 1, minHeight: 0, width: "100%" },
|
||||
centeredViewport: { flex: 1, alignItems: "center", justifyContent: "center" },
|
||||
centered: { flexShrink: 1, width: "100%" },
|
||||
// Reserve the composer's own capped height before the setup scroll view shrinks.
|
||||
|
||||
@@ -1,25 +1,14 @@
|
||||
export { ComposerDockBackground } from "./internal/background";
|
||||
export { ComposerFullscreenBody, ComposerFullscreenFooter } from "./internal/fullscreen";
|
||||
import { ScrollView } from "@/components/ui/scroll-view";
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { useState, useCallback, useMemo, useRef, type ReactNode } from "react";
|
||||
import { View } from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style";
|
||||
import { resolveInlineComposerCapacity } from "./internal/capacity";
|
||||
import { useFullscreenSlotFrame } from "./internal/fullscreen";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { HEADER_INNER_HEIGHT } from "@/constants/layout";
|
||||
|
||||
const ViewportHeightContext = createContext<number | undefined>(undefined);
|
||||
|
||||
interface ComposerDockProps {
|
||||
children: [ReactNode, ReactNode, ReactNode?];
|
||||
centered?: boolean;
|
||||
@@ -32,39 +21,40 @@ export function ComposerDock({
|
||||
centered = false,
|
||||
fullscreen = false,
|
||||
}: ComposerDockProps) {
|
||||
const compact = useIsCompactFormFactor();
|
||||
const [surfaceSize, setSurfaceSize] = useState<{ width: number; height: number }>();
|
||||
const surfaceRef = useRef<View>(null);
|
||||
const fullscreenFrame = useFullscreenSlotFrame(fullscreen, surfaceRef, surfaceSize);
|
||||
const constraint = useMemo(
|
||||
() =>
|
||||
surfaceSize?.height !== undefined
|
||||
? inlineUnistylesStyle({ maxHeight: surfaceSize.height })
|
||||
: undefined,
|
||||
[surfaceSize?.height],
|
||||
() => ({ maxHeight: resolveInlineComposerCapacity(surfaceSize?.height, compact) }),
|
||||
[surfaceSize?.height, compact],
|
||||
);
|
||||
const measureViewport = useCallback((event: import("react-native").LayoutChangeEvent) => {
|
||||
const { width, height } = event.nativeEvent.layout;
|
||||
if (height > 0) setSurfaceSize({ width, height });
|
||||
}, []);
|
||||
const body = centered ? (
|
||||
<View ref={surfaceRef} style={styles.centered} onLayout={measureViewport}>
|
||||
<View style={styles.form}>
|
||||
<ScrollView style={styles.setup} keyboardShouldPersistTaps="handled">
|
||||
{content}
|
||||
</ScrollView>
|
||||
<View
|
||||
style={
|
||||
fullscreen
|
||||
? [styles.fullscreenComposer, fullscreenFrame]
|
||||
: [styles.centeredComposer, constraint]
|
||||
}
|
||||
>
|
||||
{composer}
|
||||
if (centered) {
|
||||
return (
|
||||
<View ref={surfaceRef} style={styles.centered} onLayout={measureViewport}>
|
||||
<View style={styles.form}>
|
||||
<ScrollView style={styles.setup} keyboardShouldPersistTaps="handled">
|
||||
{content}
|
||||
</ScrollView>
|
||||
<View
|
||||
style={
|
||||
fullscreen
|
||||
? [styles.fullscreenComposer, fullscreenFrame]
|
||||
: [styles.centeredComposer, constraint]
|
||||
}
|
||||
>
|
||||
{composer}
|
||||
</View>
|
||||
{overlay}
|
||||
</View>
|
||||
{overlay}
|
||||
</View>
|
||||
</View>
|
||||
) : (
|
||||
);
|
||||
}
|
||||
return (
|
||||
<View ref={surfaceRef} style={styles.surface} onLayout={measureViewport}>
|
||||
<View style={styles.content}>{content}</View>
|
||||
<View
|
||||
@@ -77,43 +67,12 @@ export function ComposerDock({
|
||||
{overlay}
|
||||
</View>
|
||||
);
|
||||
return (
|
||||
<ViewportHeightContext.Provider value={surfaceSize?.height}>
|
||||
{body}
|
||||
</ViewportHeightContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
/** Cap the inline editing box below the viewport capacity so tracks above it keep room. */
|
||||
export function ComposerInputCap({
|
||||
fullscreen = false,
|
||||
children,
|
||||
}: {
|
||||
fullscreen?: boolean;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const compact = useIsCompactFormFactor();
|
||||
const viewportHeight = useContext(ViewportHeightContext);
|
||||
const cap = useMemo(
|
||||
() =>
|
||||
!fullscreen && viewportHeight !== undefined
|
||||
? inlineUnistylesStyle({
|
||||
maxHeight: resolveInlineComposerCapacity(viewportHeight, compact),
|
||||
})
|
||||
: undefined,
|
||||
[compact, fullscreen, viewportHeight],
|
||||
);
|
||||
return (
|
||||
<View style={fullscreen ? styles.fullscreenFill : [styles.inputCap, cap]}>{children}</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
surface: { flex: 1, overflow: "hidden" },
|
||||
content: { flex: 1, justifyContent: "flex-end" },
|
||||
composer: { width: "100%", flexShrink: 1, paddingBottom: theme.spacing[4] },
|
||||
inputCap: { width: "100%", flexShrink: 1 },
|
||||
fullscreenFill: { flex: 1, minHeight: 0, width: "100%" },
|
||||
// Fixed, not absolute: a touch pan that starts inside an overflow-hidden ancestor
|
||||
// never reaches the zoomed visual viewport, while a fixed box chains to the viewport
|
||||
// directly. React Native Web renders `fixed`; React Native's style type omits it.
|
||||
|
||||
@@ -14,7 +14,6 @@ import { buildForgeSearchQueryOptions, type ForgeSearchClient } from "@/git/use-
|
||||
import { extractForgeRefs, type ForgeRef } from "@/git/forge-refs";
|
||||
import type { ForgeSearchItem } from "@getpaseo/protocol/messages";
|
||||
import { isAttachmentSelectedForForgeItem, toggleForgeAttachment } from "./actions";
|
||||
import { forgeItemKey } from "./attachments/forge-item-key";
|
||||
|
||||
const AUTO_ATTACH_DEBOUNCE_MS = 300;
|
||||
|
||||
@@ -149,7 +148,7 @@ export function useComposerForgeAutoAttach(
|
||||
]);
|
||||
|
||||
const markForgeAttachmentRemoved = useCallback((attachment: ComposerAttachment | undefined) => {
|
||||
const key = forgeItemKey(attachment);
|
||||
const key = attachmentKey(attachment);
|
||||
if (key) {
|
||||
removedRefKeysRef.current.add(key);
|
||||
}
|
||||
@@ -506,7 +505,7 @@ function isSameLookupTarget(
|
||||
}
|
||||
|
||||
function hasForgeAttachment(attachments: UserComposerAttachment[], ref: ForgeRef): boolean {
|
||||
return attachments.some((attachment) => forgeItemKey(attachment) === forgeRefKey(ref));
|
||||
return attachments.some((attachment) => attachmentKey(attachment) === forgeRefKey(ref));
|
||||
}
|
||||
|
||||
function forgeItemMatchesRef(item: ForgeSearchItem, ref: ForgeRef): boolean {
|
||||
@@ -520,3 +519,15 @@ function forgeItemKind(ref: ForgeRef): ForgeSearchItem["kind"] {
|
||||
function forgeRefKey(ref: ForgeRef): string {
|
||||
return `${forgeItemKind(ref)}:${ref.number}`;
|
||||
}
|
||||
|
||||
function attachmentKey(attachment: ComposerAttachment | undefined): string | null {
|
||||
if (
|
||||
attachment?.kind !== "forge_change_request" &&
|
||||
attachment?.kind !== "forge_issue" &&
|
||||
attachment?.kind !== "github_pr" &&
|
||||
attachment?.kind !== "github_issue"
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return `${attachment.item.kind}:${attachment.item.number}`;
|
||||
}
|
||||
|
||||
+319
-393
@@ -9,25 +9,9 @@ import { useStore } from "zustand";
|
||||
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import { Alert } from "@/components/ui/alert";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
beginStagedProviderSwitch,
|
||||
clearStagedProviderSwitch,
|
||||
endStagedProviderSwitch,
|
||||
getStagedProviderSwitch,
|
||||
isStagedProviderSwitchInFlight,
|
||||
settleCommittedProviderSwitch,
|
||||
settleStagedProviderSwitch,
|
||||
useFailedStartupSettings,
|
||||
useIsStagedProviderSwitchInFlight,
|
||||
useStagedProviderSwitch,
|
||||
useStagedProviderSwitchStore,
|
||||
} from "@/composer/provider-switch";
|
||||
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
|
||||
import { normalizeAgentSnapshot } from "@/utils/agent-snapshots";
|
||||
import { resolveProviderLabel } from "@/utils/provider-definitions";
|
||||
import {
|
||||
View,
|
||||
Pressable,
|
||||
Text,
|
||||
StyleSheet as RNStyleSheet,
|
||||
type PressableStateCallbackType,
|
||||
@@ -64,8 +48,9 @@ import { usePanelStore, type MobilePanelView } from "@/stores/panel-store";
|
||||
import { usePointerCapabilities } from "@/hooks/pointer-capabilities";
|
||||
import { useShallow } from "zustand/shallow";
|
||||
import {
|
||||
ArrowRightLeft,
|
||||
ArrowUp,
|
||||
Square,
|
||||
Pencil,
|
||||
AudioLines,
|
||||
CircleDot,
|
||||
FileText,
|
||||
@@ -105,15 +90,19 @@ import { focusWithRetries } from "@/utils/web-focus";
|
||||
import {
|
||||
cancelComposerAgent,
|
||||
dispatchComposerAgentMessage,
|
||||
enqueueComposerAgentMessage,
|
||||
editQueuedComposerMessage,
|
||||
findForgeItemByOption,
|
||||
isAttachmentSelectedForForgeItem,
|
||||
openComposerAttachment,
|
||||
pickAndPersistImages,
|
||||
queueComposerMessage,
|
||||
removeComposerAttachmentAtIndex,
|
||||
sendQueuedComposerMessageNow,
|
||||
toggleForgeAttachmentFromPicker,
|
||||
uploadFileAttachments,
|
||||
type AttachmentPersister,
|
||||
type QueueWriter,
|
||||
type QueuedComposerMessage,
|
||||
} from "@/composer/actions";
|
||||
import { useVoiceOptional } from "@/contexts/voice-context";
|
||||
import { useToast } from "@/contexts/toast-context";
|
||||
@@ -173,12 +162,6 @@ import type { ComposerFocusOptions } from "@/composer/model";
|
||||
import { useRetainedPanelActive } from "@/components/retained-panel";
|
||||
import { insertAtSelection } from "@/composer/insert-text";
|
||||
import { composerWorkspaceAttachment } from "@/composer/attachments/workspace";
|
||||
import { forgeItemKey } from "@/composer/attachments/forge-item-key";
|
||||
import { RestoredAttachmentPill } from "@/composer/attachments/restored-pill";
|
||||
import type { RestoredQueuedMessage } from "@/composer/queue/actions";
|
||||
import { ComposerQueueTrack } from "@/composer/queue/track";
|
||||
import { ComposerInputCap } from "@/composer/dock";
|
||||
import { useHostFeature } from "@/runtime/host-features";
|
||||
import { useWorkspaceAttachmentsForScopes } from "@/attachments/workspace-attachments-store";
|
||||
import { droppedItemsToSelectedFiles } from "@/composer/attachments/drop";
|
||||
import { getFileTypeLabel } from "@/attachments/file-types";
|
||||
@@ -221,6 +204,8 @@ const composerImageAttachmentPersister: Pick<
|
||||
persistFromFileUri: persistAttachmentFromFileUri,
|
||||
};
|
||||
|
||||
type QueuedMessage = QueuedComposerMessage;
|
||||
|
||||
type AttachmentListUpdater =
|
||||
| UserComposerAttachment[]
|
||||
| ((prev: UserComposerAttachment[]) => UserComposerAttachment[]);
|
||||
@@ -313,29 +298,16 @@ function buildRealtimeVoiceButtonStyle(pressed: boolean, voiceButtonDisabled: bo
|
||||
|
||||
const EMPTY_METRICS: AgentMetric[] = [];
|
||||
|
||||
const EMPTY_AGENT_STATE = {
|
||||
provider: null,
|
||||
status: null,
|
||||
contextWindowMaxTokens: null,
|
||||
contextWindowUsedTokens: null,
|
||||
totalCostUsd: null,
|
||||
sessionMetrics: EMPTY_METRICS,
|
||||
model: null,
|
||||
};
|
||||
|
||||
function buildAgentStateSelector(serverId: string, agentId: string) {
|
||||
return (state: ReturnType<typeof useSessionStore.getState>) => {
|
||||
const agent = state.sessions[serverId]?.agents?.get(agentId) ?? null;
|
||||
if (!agent) return EMPTY_AGENT_STATE;
|
||||
const usage = agent.lastUsage;
|
||||
return {
|
||||
provider: agent.provider ?? null,
|
||||
status: agent.status ?? null,
|
||||
contextWindowMaxTokens: usage?.contextWindowMaxTokens ?? null,
|
||||
contextWindowUsedTokens: usage?.contextWindowUsedTokens ?? null,
|
||||
totalCostUsd: usage?.totalCostUsd ?? null,
|
||||
sessionMetrics: agent.sessionMetrics ?? EMPTY_METRICS,
|
||||
model: agent.model ?? null,
|
||||
status: agent?.status ?? null,
|
||||
contextWindowMaxTokens: agent?.lastUsage?.contextWindowMaxTokens ?? null,
|
||||
contextWindowUsedTokens: agent?.lastUsage?.contextWindowUsedTokens ?? null,
|
||||
totalCostUsd: agent?.lastUsage?.totalCostUsd ?? null,
|
||||
sessionMetrics: agent?.sessionMetrics ?? EMPTY_METRICS,
|
||||
model: agent?.model ?? null,
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -434,6 +406,34 @@ function renderAttachmentTray(args: RenderAttachmentTrayArgs): ReactElement | nu
|
||||
);
|
||||
}
|
||||
|
||||
interface RenderQueueTrackArgs {
|
||||
queuedMessages: readonly QueuedMessage[];
|
||||
handleEditQueuedMessage: (id: string) => void;
|
||||
handleSendQueuedNow: (id: string) => Promise<void>;
|
||||
editLabel: string;
|
||||
sendNowLabel: string;
|
||||
}
|
||||
|
||||
function renderQueueTrack(args: RenderQueueTrackArgs): ReactElement | null {
|
||||
const { queuedMessages, handleEditQueuedMessage, handleSendQueuedNow, editLabel, sendNowLabel } =
|
||||
args;
|
||||
if (queuedMessages.length === 0) return null;
|
||||
return (
|
||||
<View style={styles.queueTrack}>
|
||||
{queuedMessages.map((item) => (
|
||||
<QueuedMessageRow
|
||||
key={item.id}
|
||||
item={item}
|
||||
onEdit={handleEditQueuedMessage}
|
||||
onSendNow={handleSendQueuedNow}
|
||||
editLabel={editLabel}
|
||||
sendNowLabel={sendNowLabel}
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
interface RenderComposerAttachmentPillArgs {
|
||||
serverId: string;
|
||||
attachment: ComposerAttachment;
|
||||
@@ -493,22 +493,6 @@ function renderComposerAttachmentPill(args: RenderComposerAttachmentPillArgs): R
|
||||
onRemove,
|
||||
});
|
||||
}
|
||||
if (attachment.kind === "agent_attachment") {
|
||||
const wire = attachment.attachment;
|
||||
return (
|
||||
<RestoredAttachmentPill
|
||||
key={wire.type === "uploaded_file" ? wire.id : `${wire.type}:${index}`}
|
||||
serverId={args.serverId}
|
||||
attachment={attachment}
|
||||
index={index}
|
||||
disabled={disabled}
|
||||
onOpen={onOpen}
|
||||
onRemove={onRemove}
|
||||
openImageLabel={labels.openImage}
|
||||
removeImageLabel={labels.removeImage}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (attachment.kind === "plugin_resource") {
|
||||
return (
|
||||
<PluginResourceAttachmentPill
|
||||
@@ -712,6 +696,54 @@ function resolveMessageInputPassthroughAction(
|
||||
}
|
||||
}
|
||||
|
||||
interface QueuedMessageRowProps {
|
||||
item: QueuedMessage;
|
||||
onEdit: (id: string) => void;
|
||||
onSendNow: (id: string) => void;
|
||||
editLabel: string;
|
||||
sendNowLabel: string;
|
||||
}
|
||||
|
||||
function QueuedMessageRow({
|
||||
item,
|
||||
onEdit,
|
||||
onSendNow,
|
||||
editLabel,
|
||||
sendNowLabel,
|
||||
}: QueuedMessageRowProps) {
|
||||
const handleEdit = useCallback(() => {
|
||||
onEdit(item.id);
|
||||
}, [onEdit, item.id]);
|
||||
const handleSendNow = useCallback(() => {
|
||||
onSendNow(item.id);
|
||||
}, [onSendNow, item.id]);
|
||||
return (
|
||||
<View style={styles.queueItem}>
|
||||
<Text style={styles.queueText} numberOfLines={2} ellipsizeMode="tail">
|
||||
{item.text}
|
||||
</Text>
|
||||
<View style={styles.queueActions}>
|
||||
<Pressable
|
||||
onPress={handleEdit}
|
||||
style={styles.queueActionButton}
|
||||
accessibilityLabel={editLabel}
|
||||
accessibilityRole="button"
|
||||
>
|
||||
<ThemedPencil size={ICON_SIZE.sm} uniProps={iconForegroundMapping} />
|
||||
</Pressable>
|
||||
<Pressable
|
||||
onPress={handleSendNow}
|
||||
style={[styles.queueActionButton, styles.queueSendButton]}
|
||||
accessibilityLabel={sendNowLabel}
|
||||
accessibilityRole="button"
|
||||
>
|
||||
<ThemedArrowUp size={ICON_SIZE.sm} uniProps={iconAccentForegroundMapping} />
|
||||
</Pressable>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
interface ImageAttachmentPillProps {
|
||||
attachment: Extract<ComposerAttachment, { kind: "image" }>;
|
||||
index: number;
|
||||
@@ -994,6 +1026,7 @@ interface ComposerProps {
|
||||
error?: string | null;
|
||||
}
|
||||
|
||||
const EMPTY_ARRAY: readonly QueuedMessage[] = [];
|
||||
const StableMessageInput = memo(MessageInput);
|
||||
|
||||
interface ComposerAutocompleteHandle {
|
||||
@@ -1319,53 +1352,13 @@ function ComposerContentImpl({
|
||||
const { settings: appSettings } = useAppSettings();
|
||||
|
||||
const agentState = useSessionStore(useShallow(buildAgentStateSelector(serverId, agentId)));
|
||||
const supportsProviderSwitching = useSessionStore(
|
||||
(state) => state.sessions[serverId]?.serverInfo?.features?.providerSwitching === true,
|
||||
);
|
||||
const rawStagedSwitch = useStagedProviderSwitch(serverId, agentId);
|
||||
const isStagedSwitchInFlight = useIsStagedProviderSwitchInFlight(serverId, agentId);
|
||||
const failedStartupSettings = useFailedStartupSettings(serverId, agentId);
|
||||
const stagedSwitch =
|
||||
supportsProviderSwitching &&
|
||||
rawStagedSwitch &&
|
||||
agentState.provider &&
|
||||
rawStagedSwitch.provider !== agentState.provider
|
||||
? rawStagedSwitch
|
||||
: null;
|
||||
const { entries: providerSnapshotEntries } = useProvidersSnapshot(serverId, { cwd });
|
||||
const stagedProviderLabel = stagedSwitch
|
||||
? resolveProviderLabel(stagedSwitch.provider, providerSnapshotEntries)
|
||||
: null;
|
||||
const providerLabel = useCallback(
|
||||
(provider: string) => resolveProviderLabel(provider, providerSnapshotEntries),
|
||||
[providerSnapshotEntries],
|
||||
|
||||
const queuedMessagesRaw = useSessionStore((state) =>
|
||||
state.sessions[serverId]?.queuedMessages?.get(agentId),
|
||||
);
|
||||
const queuedMessages = queuedMessagesRaw ?? EMPTY_ARRAY;
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
rawStagedSwitch &&
|
||||
agentState.provider &&
|
||||
rawStagedSwitch.provider === agentState.provider &&
|
||||
!isStagedProviderSwitchInFlight(serverId, agentId)
|
||||
) {
|
||||
clearStagedProviderSwitch(serverId, agentId);
|
||||
}
|
||||
}, [agentId, agentState.provider, rawStagedSwitch, serverId]);
|
||||
|
||||
const handleCancelStagedSwitch = useCallback(() => {
|
||||
clearStagedProviderSwitch(serverId, agentId);
|
||||
setSendError(null);
|
||||
}, [agentId, serverId]);
|
||||
|
||||
const handleRetryFailedStartupSettings = useCallback(() => {
|
||||
setSendError(null);
|
||||
void getHostRuntimeStore().recoverFailedStartupSettings(serverId, agentId, "retry");
|
||||
}, [agentId, serverId]);
|
||||
|
||||
const handleDismissFailedStartupSettings = useCallback(() => {
|
||||
setSendError(null);
|
||||
void getHostRuntimeStore().recoverFailedStartupSettings(serverId, agentId, "discard");
|
||||
}, [agentId, serverId]);
|
||||
const setQueuedMessages = useSessionStore((state) => state.setQueuedMessages);
|
||||
|
||||
const isCompactFormFactor = useIsCompactFormFactor();
|
||||
const isCompactLayout = resolveCompactLayout(isCompactLayoutOverride, isCompactFormFactor);
|
||||
@@ -1384,6 +1377,7 @@ function ComposerContentImpl({
|
||||
removeAttachment,
|
||||
openAttachment,
|
||||
beginSubmit,
|
||||
clearSentAttachments,
|
||||
completeSubmit,
|
||||
resetSuppression,
|
||||
} = composerWorkspaceAttachment.useBinding({
|
||||
@@ -1725,62 +1719,24 @@ function ComposerContentImpl({
|
||||
if (!client) {
|
||||
throw new Error(t("workspace.terminal.hostDisconnected"));
|
||||
}
|
||||
const sessionState = useSessionStore.getState().sessions[serverId];
|
||||
const liveProvider = sessionState?.agents.get(targetAgentId)?.provider;
|
||||
const canSwitch = sessionState?.serverInfo?.features?.providerSwitching === true;
|
||||
const pendingSwitch = canSwitch ? getStagedProviderSwitch(serverId, targetAgentId) : null;
|
||||
const stagedProviderSwitch =
|
||||
pendingSwitch && pendingSwitch.provider !== liveProvider ? pendingSwitch : null;
|
||||
if (stagedProviderSwitch) {
|
||||
beginStagedProviderSwitch(serverId, targetAgentId);
|
||||
}
|
||||
try {
|
||||
await dispatchComposerAgentMessage({
|
||||
client,
|
||||
agentId: targetAgentId,
|
||||
text,
|
||||
attachments: sendAttachments,
|
||||
attachmentSubmitFormat: resolveComposerAttachmentSubmitFormat({
|
||||
supportsForgeAttachments: supportsForgeSearch,
|
||||
}),
|
||||
submission: createMessageSubmissionWriter(serverId),
|
||||
currentProvider: liveProvider ?? null,
|
||||
currentModel: sessionState?.agents.get(targetAgentId)?.model ?? null,
|
||||
stagedProviderSwitch,
|
||||
onProviderSwitchCommitted: async (agent) => {
|
||||
if (agent) {
|
||||
getHostRuntimeStore().tryAcceptAgentSnapshot(
|
||||
serverId,
|
||||
normalizeAgentSnapshot(agent, serverId),
|
||||
);
|
||||
}
|
||||
if (stagedProviderSwitch) {
|
||||
const settled = await settleCommittedProviderSwitch({
|
||||
serverId,
|
||||
agentId: targetAgentId,
|
||||
sentDraft: stagedProviderSwitch,
|
||||
committedProvider: agent?.provider ?? null,
|
||||
client,
|
||||
});
|
||||
if (!settled.applied) {
|
||||
setSendError(settled.errorMessage);
|
||||
}
|
||||
}
|
||||
},
|
||||
activeTurnBehavior,
|
||||
activeTurnId:
|
||||
activeTurnBehavior === "steer"
|
||||
? (selectAgentTurnPresentation(
|
||||
useSessionStore.getState().sessions[serverId],
|
||||
targetAgentId,
|
||||
).turnId ?? undefined)
|
||||
: undefined,
|
||||
});
|
||||
} finally {
|
||||
if (stagedProviderSwitch) {
|
||||
endStagedProviderSwitch(serverId, targetAgentId);
|
||||
}
|
||||
}
|
||||
await dispatchComposerAgentMessage({
|
||||
client,
|
||||
agentId: targetAgentId,
|
||||
text,
|
||||
attachments: sendAttachments,
|
||||
attachmentSubmitFormat: resolveComposerAttachmentSubmitFormat({
|
||||
supportsForgeAttachments: supportsForgeSearch,
|
||||
}),
|
||||
submission: createMessageSubmissionWriter(serverId),
|
||||
activeTurnBehavior,
|
||||
activeTurnId:
|
||||
activeTurnBehavior === "steer"
|
||||
? (selectAgentTurnPresentation(
|
||||
useSessionStore.getState().sessions[serverId],
|
||||
targetAgentId,
|
||||
).turnId ?? undefined)
|
||||
: undefined,
|
||||
});
|
||||
onAttentionPromptSend?.();
|
||||
};
|
||||
}, [appSettings.sendBehavior, client, onAttentionPromptSend, serverId, supportsForgeSearch, t]);
|
||||
@@ -1806,37 +1762,43 @@ function ComposerContentImpl({
|
||||
}
|
||||
return false;
|
||||
});
|
||||
// COMPAT(agentMessageQueue): added in v0.18.2, remove gate after 2027-06-01.
|
||||
const supportsQueue = useHostFeature(serverId, "agentMessageQueue");
|
||||
const activeSendBehavior = resolveActiveSendBehavior(
|
||||
appSettings.sendBehavior,
|
||||
hasPendingPermission,
|
||||
supportsQueue,
|
||||
);
|
||||
const hasAgent = agentState.status !== null;
|
||||
|
||||
const enqueueMessage = useCallback(
|
||||
async (text: string, queuedAttachments: ComposerAttachment[]) => {
|
||||
if (!client) {
|
||||
throw new Error(t("workspace.terminal.hostDisconnected"));
|
||||
}
|
||||
const targetAgentId = agentIdRef.current;
|
||||
await enqueueComposerAgentMessage({
|
||||
client,
|
||||
agentId: targetAgentId,
|
||||
text,
|
||||
const queueWriter = useMemo<QueueWriter>(
|
||||
() => ({
|
||||
read: (id) => useSessionStore.getState().sessions[serverId]?.queuedMessages?.get(id) ?? [],
|
||||
write: (updater) => setQueuedMessages(serverId, updater),
|
||||
}),
|
||||
[serverId, setQueuedMessages],
|
||||
);
|
||||
|
||||
const queueMessage = useCallback(
|
||||
(queuedMessage: string, queuedAttachments: ComposerAttachment[]) => {
|
||||
const result = queueComposerMessage({
|
||||
agentId,
|
||||
text: queuedMessage,
|
||||
attachments: queuedAttachments,
|
||||
attachmentSubmitFormat: resolveComposerAttachmentSubmitFormat({
|
||||
supportsForgeAttachments: supportsForgeSearch,
|
||||
}),
|
||||
stagedProviderSwitch: stagedSwitch,
|
||||
// The host owns the switch now. A choice made since then stays staged.
|
||||
onProviderSwitchQueued: () => {
|
||||
if (stagedSwitch) settleStagedProviderSwitch(serverId, targetAgentId, stagedSwitch);
|
||||
},
|
||||
queue: queueWriter,
|
||||
});
|
||||
if (!result.queued) return;
|
||||
|
||||
replaceUserInput("");
|
||||
setSelectedAttachments([]);
|
||||
resetSuppression();
|
||||
clearSentAttachments(queuedAttachments);
|
||||
},
|
||||
[client, serverId, stagedSwitch, supportsForgeSearch, t],
|
||||
[
|
||||
agentId,
|
||||
clearSentAttachments,
|
||||
queueWriter,
|
||||
resetSuppression,
|
||||
setSelectedAttachments,
|
||||
replaceUserInput,
|
||||
],
|
||||
);
|
||||
|
||||
const sendMessageWithContent = useCallback(
|
||||
@@ -1850,17 +1812,14 @@ function ComposerContentImpl({
|
||||
attachments: outgoingAttachments,
|
||||
hasExternalContent,
|
||||
allowEmptySubmit,
|
||||
forceSend: stagedSwitch && isAgentRunning ? false : forceSend,
|
||||
forceSend,
|
||||
submitBehavior,
|
||||
isAgentRunning: isAgentRunning && supportsQueue,
|
||||
isAgentRunning,
|
||||
// Parent-managed submits are still valid submit paths even when the
|
||||
// transport is disconnected, because the parent decides the failure mode.
|
||||
canSubmit: Boolean(sendAgentMessageRef.current || onSubmitMessageRef.current),
|
||||
queueMessage: async ({ message: queuedText, attachments: queuedAttachments }) => {
|
||||
if (submitBehavior !== "preserve-and-lock") {
|
||||
beginSubmit(queuedAttachments);
|
||||
}
|
||||
await enqueueMessage(queuedText, queuedAttachments);
|
||||
queueMessage: ({ message: queuedText, attachments: queuedAttachments }) => {
|
||||
queueMessage(queuedText, queuedAttachments);
|
||||
},
|
||||
submitMessage: async ({ message: submitText, attachments: submitAttachments }) => {
|
||||
if (submitBehavior !== "preserve-and-lock") {
|
||||
@@ -1890,13 +1849,11 @@ function ComposerContentImpl({
|
||||
beginSubmit,
|
||||
clearDraft,
|
||||
completeSubmit,
|
||||
enqueueMessage,
|
||||
hasExternalContent,
|
||||
isAgentRunning,
|
||||
supportsQueue,
|
||||
queueMessage,
|
||||
setSelectedAttachments,
|
||||
replaceUserInput,
|
||||
stagedSwitch,
|
||||
submitBehavior,
|
||||
submitMessage,
|
||||
t,
|
||||
@@ -2141,25 +2098,37 @@ function ComposerContentImpl({
|
||||
});
|
||||
}, [agentId, hasAgent, isConnected, serverId, voice]);
|
||||
|
||||
const handleRestoreQueuedMessage = useCallback(
|
||||
(message: RestoredQueuedMessage) => {
|
||||
replaceUserInput(message.text);
|
||||
setSelectedAttachments(message.attachments);
|
||||
if (message.providerSwitch) {
|
||||
useStagedProviderSwitchStore.getState().stage(serverId, agentId, message.providerSwitch);
|
||||
}
|
||||
focusInput();
|
||||
const handleEditQueuedMessage = useCallback(
|
||||
(id: string) => {
|
||||
const result = editQueuedComposerMessage({
|
||||
agentId,
|
||||
messageId: id,
|
||||
queue: queueWriter,
|
||||
});
|
||||
if (!result) return;
|
||||
replaceUserInput(result.text);
|
||||
setSelectedAttachments(result.attachments);
|
||||
},
|
||||
[agentId, focusInput, replaceUserInput, serverId, setSelectedAttachments],
|
||||
[agentId, queueWriter, replaceUserInput, setSelectedAttachments],
|
||||
);
|
||||
const handleQueuedMessageAlreadySending = useCallback(() => {
|
||||
toastErrorRef.current(t("composer.queue.alreadySending"));
|
||||
}, [t]);
|
||||
const handleQueueError = useCallback(
|
||||
(error: unknown) => {
|
||||
setSendError(resolveErrorMessage(error) ?? t("composer.errors.failedToSend"));
|
||||
|
||||
const handleSendQueuedNow = useCallback(
|
||||
async (id: string) => {
|
||||
if (!sendAgentMessageRef.current && !onSubmitMessageRef.current) return;
|
||||
// Reuse the regular send path; server-side send atomically interrupts any active run.
|
||||
const result = await sendQueuedComposerMessageNow({
|
||||
agentId,
|
||||
messageId: id,
|
||||
queue: queueWriter,
|
||||
submitMessage: ({ text, attachments: queuedAttachments }) =>
|
||||
submitMessage(text, queuedAttachments),
|
||||
failedToSendMessage: t("composer.errors.failedToSend"),
|
||||
});
|
||||
if (result.status === "failed") {
|
||||
setSendError(result.errorMessage);
|
||||
}
|
||||
},
|
||||
[t],
|
||||
[agentId, queueWriter, submitMessage, t],
|
||||
);
|
||||
|
||||
const handleQueue = useCallback(
|
||||
@@ -2178,15 +2147,15 @@ function ComposerContentImpl({
|
||||
commands: pluginClientSlashCommands,
|
||||
});
|
||||
if (pluginSlashCommand && runPluginClientSlashCommand(pluginSlashCommand)) return;
|
||||
void sendMessageWithContent(payload.text, outgoingAttachments);
|
||||
queueMessage(payload.text, outgoingAttachments);
|
||||
},
|
||||
[
|
||||
attachments,
|
||||
buildOutgoingAttachments,
|
||||
pluginClientSlashCommands,
|
||||
queueMessage,
|
||||
runClientSlashCommand,
|
||||
runPluginClientSlashCommand,
|
||||
sendMessageWithContent,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -2305,7 +2274,14 @@ function ComposerContentImpl({
|
||||
);
|
||||
|
||||
const hasGithubAttachment = useMemo(
|
||||
() => selectedAttachments.some((attachment) => forgeItemKey(attachment) !== null),
|
||||
() =>
|
||||
selectedAttachments.some(
|
||||
(attachment) =>
|
||||
attachment.kind === "forge_change_request" ||
|
||||
attachment.kind === "forge_issue" ||
|
||||
attachment.kind === "github_pr" ||
|
||||
attachment.kind === "github_issue",
|
||||
),
|
||||
[selectedAttachments],
|
||||
);
|
||||
// Composer stays mounted for each focused agent, so avoid a forge CLI call
|
||||
@@ -2551,6 +2527,18 @@ function ComposerContentImpl({
|
||||
],
|
||||
);
|
||||
|
||||
const queueList = useMemo(
|
||||
() =>
|
||||
renderQueueTrack({
|
||||
queuedMessages,
|
||||
handleEditQueuedMessage,
|
||||
handleSendQueuedNow,
|
||||
editLabel: t("composer.attachments.editQueuedMessage"),
|
||||
sendNowLabel: t("composer.attachments.sendQueuedMessageNow"),
|
||||
}),
|
||||
[handleEditQueuedMessage, handleSendQueuedNow, queuedMessages, t],
|
||||
);
|
||||
|
||||
const autocompleteConfiguration = useMemo(
|
||||
() => ({
|
||||
setUserInput: replaceUserInput,
|
||||
@@ -2593,131 +2581,18 @@ function ComposerContentImpl({
|
||||
// Focusing the composer on a touch screen raises the on-screen keyboard over the conversation.
|
||||
const messageInputAutoFocus = autoFocus && isDesktopWebBreakpoint && hasFinePointer;
|
||||
const submitLoadingPressHandler = isAgentRunning ? handleCancelAgent : undefined;
|
||||
const displayError = externalError || sendError || failedStartupSettings?.errorMessage;
|
||||
const displayError = externalError || sendError;
|
||||
const sendErrorNode = useMemo(
|
||||
() =>
|
||||
displayError ? (
|
||||
<Alert variant="error" size="sm" description={displayError} testID="composer-error">
|
||||
{failedStartupSettings ? (
|
||||
<>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onPress={handleRetryFailedStartupSettings}
|
||||
testID="retry-failed-startup-settings"
|
||||
>
|
||||
{t("common.actions.retry")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onPress={handleDismissFailedStartupSettings}
|
||||
testID="dismiss-failed-startup-settings"
|
||||
>
|
||||
{t("common.actions.dismiss")}
|
||||
</Button>
|
||||
</>
|
||||
) : null}
|
||||
</Alert>
|
||||
<Alert variant="error" size="sm" description={displayError} testID="composer-error" />
|
||||
) : null,
|
||||
[
|
||||
displayError,
|
||||
failedStartupSettings,
|
||||
handleDismissFailedStartupSettings,
|
||||
handleRetryFailedStartupSettings,
|
||||
t,
|
||||
],
|
||||
[displayError],
|
||||
);
|
||||
const githubEmptyText = githubSearchResultsQuery.isFetching
|
||||
? t("composer.github.searching")
|
||||
: t("composer.github.noResults");
|
||||
|
||||
const stagedSwitchBannerNode = useMemo(() => {
|
||||
if (!stagedSwitch || !stagedProviderLabel || isStagedSwitchInFlight) return null;
|
||||
const message = isAgentRunning
|
||||
? t("composer.providerSwitch.switchingAfterTurn", { provider: stagedProviderLabel })
|
||||
: t("composer.providerSwitch.switchingNextMessage", { provider: stagedProviderLabel });
|
||||
return (
|
||||
<View style={styles.stagedSwitchBanner} testID="staged-provider-switch-banner">
|
||||
<View style={styles.stagedSwitchLabelRow}>
|
||||
<ThemedArrowRightLeft size={ICON_SIZE.sm} uniProps={iconForegroundMutedMapping} />
|
||||
<Text style={styles.stagedSwitchText} numberOfLines={1}>
|
||||
{message}
|
||||
</Text>
|
||||
</View>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onPress={handleCancelStagedSwitch}
|
||||
testID="cancel-staged-provider-switch"
|
||||
>
|
||||
{t("common.actions.cancel")}
|
||||
</Button>
|
||||
</View>
|
||||
);
|
||||
}, [
|
||||
handleCancelStagedSwitch,
|
||||
isAgentRunning,
|
||||
isStagedSwitchInFlight,
|
||||
stagedProviderLabel,
|
||||
stagedSwitch,
|
||||
t,
|
||||
]);
|
||||
|
||||
const messageInputNode = (
|
||||
<RenderProfile id="MessageInput">
|
||||
<StableMessageInput
|
||||
ref={messageInputRef}
|
||||
editingSession={editingSession}
|
||||
submissionError={sendErrorNode}
|
||||
value={textSource.getSnapshot()}
|
||||
onChangeText={setUserInput}
|
||||
onSubmit={handleSubmit}
|
||||
hasExternalContent={hasExternalContent}
|
||||
allowEmptySubmit={allowEmptySubmit}
|
||||
submitButtonAccessibilityLabel={submitButtonAccessibilityLabel}
|
||||
submitButtonTestID={submitButtonTestID}
|
||||
submitIcon={submitIcon}
|
||||
isSubmitDisabled={isSubmitDisabled}
|
||||
isSubmitLoading={isSubmitLoadingVisible}
|
||||
preserveHeightOnSubmit={submitBehavior === "preserve-and-lock"}
|
||||
attachments={selectedAttachments}
|
||||
cwd={cwd}
|
||||
attachmentMenuItems={attachmentMenuItems}
|
||||
onAttachButtonRef={handleAttachButtonRef}
|
||||
onAddImages={addImages}
|
||||
onPasteImages={handleNativePasteImages}
|
||||
client={client}
|
||||
isReadyForDictation={isDictationReady}
|
||||
placeholder={messagePlaceholder}
|
||||
autoFocus={messageInputAutoFocus}
|
||||
autoFocusKey={`${serverId}:${agentId}:${autoFocusKey ?? ""}`}
|
||||
disabled={isSubmitLoading}
|
||||
leftContent={leftContent}
|
||||
beforeVoiceContent={beforeVoiceContent}
|
||||
voiceModeContent={voiceModeContent}
|
||||
activeActionContent={activeActionContent}
|
||||
voiceServerId={serverId}
|
||||
voiceAgentId={agentId}
|
||||
isAgentRunning={isAgentRunning}
|
||||
defaultSendBehavior={activeSendBehavior}
|
||||
sendShortcut={appSettings.sendShortcut}
|
||||
onQueue={supportsQueue ? handleQueue : undefined}
|
||||
onSubmitLoadingPress={submitLoadingPressHandler}
|
||||
onKeyPress={handleCommandKeyPress}
|
||||
onSelectionChange={handleSelectionChange}
|
||||
onFocusChange={handleFocusChange}
|
||||
onHeightChange={onComposerHeightChange}
|
||||
inputWrapperStyle={inputWrapperStyle}
|
||||
attachmentSlot={attachmentTray}
|
||||
inputMode={inputMode}
|
||||
readOnly={readOnly}
|
||||
textReplacement={textReplacement}
|
||||
submitLabel={submitLabel}
|
||||
/>
|
||||
</RenderProfile>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<ComposerKeyboardRegistration
|
||||
@@ -2742,63 +2617,100 @@ function ComposerContentImpl({
|
||||
dataSet={isFullscreen ? undefined : CHAT_COLUMN_RAIL_DATASET}
|
||||
>
|
||||
<View style={inputAreaContentStyle}>
|
||||
{!isFullscreen && hasAgent && supportsQueue ? (
|
||||
<ComposerQueueTrack
|
||||
serverId={serverId}
|
||||
agentId={agentId}
|
||||
sendBehavior={appSettings.sendBehavior}
|
||||
providerLabel={providerLabel}
|
||||
onRestore={handleRestoreQueuedMessage}
|
||||
onAlreadySending={handleQueuedMessageAlreadySending}
|
||||
onError={handleQueueError}
|
||||
/>
|
||||
) : null}
|
||||
{isFullscreen ? null : stagedSwitchBannerNode}
|
||||
{isFullscreen ? null : queueList}
|
||||
{!isFullscreen && sendErrorNode}
|
||||
|
||||
<ComposerInputCap fullscreen={isFullscreen}>
|
||||
<ComposerAutocompleteBinding
|
||||
<ComposerAutocompleteBinding
|
||||
text={textSource}
|
||||
cursor={cursor}
|
||||
recall={recall}
|
||||
inputRef={messageInputRef}
|
||||
anchorStyle={messageInputContainerStyle}
|
||||
show={mode.showAutocomplete && !isFullscreen && !isComposerLocked}
|
||||
ref={autocompleteRef}
|
||||
configuration={autocompleteConfiguration}
|
||||
>
|
||||
<ComposerForgeBinding
|
||||
text={textSource}
|
||||
cursor={cursor}
|
||||
recall={recall}
|
||||
inputRef={messageInputRef}
|
||||
anchorStyle={messageInputContainerStyle}
|
||||
show={mode.showAutocomplete && !isFullscreen && !isComposerLocked}
|
||||
ref={autocompleteRef}
|
||||
configuration={autocompleteConfiguration}
|
||||
>
|
||||
<ComposerForgeBinding
|
||||
text={textSource}
|
||||
configuration={forgeConfiguration}
|
||||
ref={forgeAutoAttachRef}
|
||||
onResolvingChange={setIsForgeResolving}
|
||||
/>
|
||||
configuration={forgeConfiguration}
|
||||
ref={forgeAutoAttachRef}
|
||||
onResolvingChange={setIsForgeResolving}
|
||||
/>
|
||||
|
||||
{/* MessageInput handles everything: text, dictation, attachments, all buttons */}
|
||||
{messageInputNode}
|
||||
<Combobox
|
||||
options={githubSearchOptions}
|
||||
value=""
|
||||
onSelect={noop}
|
||||
keepOpenOnSelect
|
||||
searchable
|
||||
searchPlaceholder={t("composer.github.searchPlaceholder", {
|
||||
context: forgePresentation.changeRequestContext,
|
||||
})}
|
||||
title={t("composer.github.title", {
|
||||
context: forgePresentation.changeRequestContext,
|
||||
})}
|
||||
open={isGithubPickerOpen}
|
||||
onOpenChange={handleGithubPickerOpenChange}
|
||||
onSearchQueryChange={setGithubSearchQuery}
|
||||
desktopPlacement="top-start"
|
||||
anchorRef={attachButtonRef}
|
||||
emptyText={githubEmptyText}
|
||||
renderOption={renderGithubPickerOption}
|
||||
{/* MessageInput handles everything: text, dictation, attachments, all buttons */}
|
||||
<RenderProfile id="MessageInput">
|
||||
<StableMessageInput
|
||||
ref={messageInputRef}
|
||||
editingSession={editingSession}
|
||||
submissionError={sendErrorNode}
|
||||
value={textSource.getSnapshot()}
|
||||
onChangeText={setUserInput}
|
||||
onSubmit={handleSubmit}
|
||||
hasExternalContent={hasExternalContent}
|
||||
allowEmptySubmit={allowEmptySubmit}
|
||||
submitButtonAccessibilityLabel={submitButtonAccessibilityLabel}
|
||||
submitButtonTestID={submitButtonTestID}
|
||||
submitIcon={submitIcon}
|
||||
isSubmitDisabled={isSubmitDisabled}
|
||||
isSubmitLoading={isSubmitLoadingVisible}
|
||||
preserveHeightOnSubmit={submitBehavior === "preserve-and-lock"}
|
||||
attachments={selectedAttachments}
|
||||
cwd={cwd}
|
||||
attachmentMenuItems={attachmentMenuItems}
|
||||
onAttachButtonRef={handleAttachButtonRef}
|
||||
onAddImages={addImages}
|
||||
onPasteImages={handleNativePasteImages}
|
||||
client={client}
|
||||
isReadyForDictation={isDictationReady}
|
||||
placeholder={messagePlaceholder}
|
||||
autoFocus={messageInputAutoFocus}
|
||||
autoFocusKey={`${serverId}:${agentId}:${autoFocusKey ?? ""}`}
|
||||
disabled={isSubmitLoading}
|
||||
leftContent={leftContent}
|
||||
beforeVoiceContent={beforeVoiceContent}
|
||||
voiceModeContent={voiceModeContent}
|
||||
activeActionContent={activeActionContent}
|
||||
voiceServerId={serverId}
|
||||
voiceAgentId={agentId}
|
||||
isAgentRunning={isAgentRunning}
|
||||
defaultSendBehavior={activeSendBehavior}
|
||||
sendShortcut={appSettings.sendShortcut}
|
||||
onQueue={handleQueue}
|
||||
onSubmitLoadingPress={submitLoadingPressHandler}
|
||||
onKeyPress={handleCommandKeyPress}
|
||||
onSelectionChange={handleSelectionChange}
|
||||
onFocusChange={handleFocusChange}
|
||||
onHeightChange={onComposerHeightChange}
|
||||
inputWrapperStyle={inputWrapperStyle}
|
||||
attachmentSlot={attachmentTray}
|
||||
inputMode={inputMode}
|
||||
readOnly={readOnly}
|
||||
textReplacement={textReplacement}
|
||||
submitLabel={submitLabel}
|
||||
/>
|
||||
{pluginAttachments.picker}
|
||||
</ComposerAutocompleteBinding>
|
||||
</ComposerInputCap>
|
||||
</RenderProfile>
|
||||
<Combobox
|
||||
options={githubSearchOptions}
|
||||
value=""
|
||||
onSelect={noop}
|
||||
keepOpenOnSelect
|
||||
searchable
|
||||
searchPlaceholder={t("composer.github.searchPlaceholder", {
|
||||
context: forgePresentation.changeRequestContext,
|
||||
})}
|
||||
title={t("composer.github.title", {
|
||||
context: forgePresentation.changeRequestContext,
|
||||
})}
|
||||
open={isGithubPickerOpen}
|
||||
onOpenChange={handleGithubPickerOpenChange}
|
||||
onSearchQueryChange={setGithubSearchQuery}
|
||||
desktopPlacement="top-start"
|
||||
anchorRef={attachButtonRef}
|
||||
emptyText={githubEmptyText}
|
||||
renderOption={renderGithubPickerOption}
|
||||
/>
|
||||
{pluginAttachments.picker}
|
||||
</ComposerAutocompleteBinding>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
@@ -2924,35 +2836,48 @@ const styles = StyleSheet.create((theme: Theme) => ({
|
||||
buttonDisabled: {
|
||||
opacity: 0.5,
|
||||
},
|
||||
stagedSwitchBanner: {
|
||||
queueTrack: {
|
||||
flexDirection: "column",
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
queueItem: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
paddingLeft: theme.spacing[3],
|
||||
paddingRight: theme.spacing[1.5],
|
||||
paddingVertical: theme.spacing[1],
|
||||
paddingHorizontal: theme.spacing[3],
|
||||
paddingVertical: theme.spacing[2],
|
||||
backgroundColor: theme.colors.surface1,
|
||||
borderRadius: theme.borderRadius.md,
|
||||
borderRadius: theme.borderRadius.lg,
|
||||
borderWidth: theme.borderWidth[1],
|
||||
borderColor: theme.colors.border,
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
stagedSwitchLabelRow: {
|
||||
queueText: {
|
||||
flex: 1,
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.base,
|
||||
},
|
||||
queueActions: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[1.5],
|
||||
minWidth: 0,
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
stagedSwitchText: {
|
||||
flex: 1,
|
||||
fontSize: theme.fontSize.sm,
|
||||
color: theme.colors.foregroundMuted,
|
||||
queueActionButton: {
|
||||
width: 32,
|
||||
height: 32,
|
||||
borderRadius: theme.borderRadius.full,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
backgroundColor: theme.colors.surface2,
|
||||
},
|
||||
queueSendButton: {
|
||||
backgroundColor: theme.colors.accent,
|
||||
},
|
||||
})) as unknown as Record<string, object>;
|
||||
|
||||
const ThemedAttachmentSpinner = withUnistyles(LoadingSpinner);
|
||||
const ThemedArrowRightLeft = withUnistyles(ArrowRightLeft);
|
||||
const ThemedPencil = withUnistyles(Pencil);
|
||||
const ThemedArrowUp = withUnistyles(ArrowUp);
|
||||
const ThemedGitPullRequest = withUnistyles(GitPullRequest);
|
||||
const ThemedCircleDot = withUnistyles(CircleDot);
|
||||
const ThemedAudioLines = withUnistyles(AudioLines);
|
||||
@@ -2962,6 +2887,7 @@ const ThemedClipboardPaste = withUnistyles(ClipboardPaste);
|
||||
const ThemedFileText = withUnistyles(FileText);
|
||||
const iconForegroundMapping = (theme: Theme) => ({ color: theme.colors.foreground });
|
||||
const iconForegroundMutedMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
|
||||
const iconAccentForegroundMapping = (theme: Theme) => ({ color: theme.colors.accentForeground });
|
||||
|
||||
function renderForgeAttachmentIcon(icon: string): ReactElement {
|
||||
return (
|
||||
|
||||
@@ -196,16 +196,9 @@ describe("dictation transcript behavior", () => {
|
||||
|
||||
describe("composer send behavior", () => {
|
||||
it("sends immediately when queue mode cannot advance past a permission", () => {
|
||||
expect(resolveActiveSendBehavior("queue", true, true)).toBe("interrupt");
|
||||
expect(resolveActiveSendBehavior("queue", false, true)).toBe("queue");
|
||||
expect(resolveActiveSendBehavior("steer", true, true)).toBe("steer");
|
||||
});
|
||||
|
||||
it("steers instead of queueing on a host without a message queue, keeping the turn", () => {
|
||||
expect(resolveActiveSendBehavior("queue", false, false)).toBe("steer");
|
||||
expect(resolveActiveSendBehavior("queue", true, false)).toBe("interrupt");
|
||||
expect(resolveActiveSendBehavior("steer", false, false)).toBe("steer");
|
||||
expect(resolveActiveSendBehavior("interrupt", false, false)).toBe("interrupt");
|
||||
expect(resolveActiveSendBehavior("queue", true)).toBe("interrupt");
|
||||
expect(resolveActiveSendBehavior("queue", false)).toBe("queue");
|
||||
expect(resolveActiveSendBehavior("steer", true)).toBe("steer");
|
||||
});
|
||||
|
||||
function actions() {
|
||||
|
||||
@@ -9,13 +9,8 @@ export type SendBehavior = ActiveTurnBehavior | "queue";
|
||||
export function resolveActiveSendBehavior(
|
||||
sendBehavior: SendBehavior,
|
||||
hasPendingPermission: boolean,
|
||||
hostHasMessageQueue: boolean,
|
||||
): SendBehavior {
|
||||
if (sendBehavior !== "queue") return sendBehavior;
|
||||
if (hasPendingPermission) return "interrupt";
|
||||
// COMPAT(agentMessageQueue): added in v0.18.2, remove gate after 2027-06-01.
|
||||
// Steering keeps the running turn alive on a host that cannot hold the message.
|
||||
return hostHasMessageQueue ? "queue" : "steer";
|
||||
return sendBehavior === "queue" && hasPendingPermission ? "interrupt" : sendBehavior;
|
||||
}
|
||||
|
||||
interface ComposerSurfaceState {
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
export {
|
||||
applyFailedStartupSettings,
|
||||
beginStagedProviderSwitch,
|
||||
clearStagedProviderSwitch,
|
||||
discardFailedStartupSettings,
|
||||
endStagedProviderSwitch,
|
||||
getFailedStartupSettings,
|
||||
getStagedProviderSwitch,
|
||||
isStagedProviderSwitchInFlight,
|
||||
settleCommittedProviderSwitch,
|
||||
settleStagedProviderSwitch,
|
||||
toStagedProviderSwitch,
|
||||
useFailedStartupSettings,
|
||||
useIsStagedProviderSwitchInFlight,
|
||||
useStagedProviderSwitch,
|
||||
useStagedProviderSwitchStore,
|
||||
type FailedStartupSettings,
|
||||
type LiveAgentSettingsWriter,
|
||||
type SettleCommittedProviderSwitchResult,
|
||||
type StagedProviderSwitch,
|
||||
} from "./store";
|
||||
@@ -1,694 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { AgentProviderSwitchError } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { AgentSnapshotPayload } from "@getpaseo/protocol/messages";
|
||||
import { dispatchComposerAgentMessage } from "@/composer/actions";
|
||||
import { isPromptInActiveSegment } from "@/components/rewind/use-rewind-capabilities";
|
||||
import { collapseTurns } from "@/agent-stream/turn-collapse/model";
|
||||
import {
|
||||
processAgentStreamEvent,
|
||||
processTimelineResponse,
|
||||
} from "@/timeline/session-stream-reducers";
|
||||
import { ReplicaCache } from "@/runtime/replica-cache";
|
||||
import type { ReplicaRow, ReplicaRowStore } from "@/runtime/replica-cache/row-store";
|
||||
import { HostRuntimeStore } from "@/runtime/host-runtime";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import {
|
||||
appendSubmittedUserMessage,
|
||||
createPendingProviderSwitchItem,
|
||||
createUserMessage,
|
||||
removeSubmittedUserMessage,
|
||||
replaceWithCanonicalStream,
|
||||
type ProviderSwitchItem,
|
||||
type StreamItem,
|
||||
type UserMessageItem,
|
||||
} from "@/types/stream";
|
||||
import {
|
||||
clearStagedProviderSwitch,
|
||||
getFailedStartupSettings,
|
||||
getStagedProviderSwitch,
|
||||
settleCommittedProviderSwitch,
|
||||
useStagedProviderSwitchStore,
|
||||
} from "./index";
|
||||
|
||||
function createInMemoryRowStore(): ReplicaRowStore {
|
||||
const rows = new Map<string, ReplicaRow>();
|
||||
const keyOf = (r: { serverId: string; kind: string; id: string }) =>
|
||||
`${r.serverId}:${r.kind}:${r.id}`;
|
||||
return {
|
||||
async open() {},
|
||||
async read(serverId, kinds, ids) {
|
||||
const kindSet = new Set(kinds);
|
||||
const idSet = ids ? new Set(ids) : null;
|
||||
return [...rows.values()].filter(
|
||||
(r) => r.serverId === serverId && kindSet.has(r.kind) && (!idSet || idSet.has(r.id)),
|
||||
);
|
||||
},
|
||||
async readIndex() {
|
||||
const byServer = new Map<
|
||||
string,
|
||||
Array<{ serverId: string; kind: ReplicaRow["kind"]; id: string; bytes: number }>
|
||||
>();
|
||||
for (const row of rows.values()) {
|
||||
const list = byServer.get(row.serverId) ?? [];
|
||||
list.push({
|
||||
serverId: row.serverId,
|
||||
kind: row.kind,
|
||||
id: row.id,
|
||||
bytes: Buffer.byteLength(row.payload, "utf8"),
|
||||
});
|
||||
byServer.set(row.serverId, list);
|
||||
}
|
||||
return [...byServer.entries()].map(([serverId, list]) => ({ serverId, rows: list }));
|
||||
},
|
||||
async apply(changes) {
|
||||
for (const del of changes.deletes) rows.delete(keyOf(del));
|
||||
for (const up of changes.upserts) rows.set(keyOf(up), up);
|
||||
},
|
||||
async deleteHost(serverId) {
|
||||
for (const [k, v] of rows) if (v.serverId === serverId) rows.delete(k);
|
||||
},
|
||||
async renameHost() {},
|
||||
async clear() {
|
||||
rows.clear();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const TS = "2026-11-25T10:00:00.000Z";
|
||||
|
||||
function agentSnapshot(provider: string): AgentSnapshotPayload {
|
||||
return {
|
||||
id: "agent-1",
|
||||
provider,
|
||||
cwd: "/repo",
|
||||
model: null,
|
||||
thinkingOptionId: null,
|
||||
createdAt: TS,
|
||||
updatedAt: TS,
|
||||
lastUserMessageAt: null,
|
||||
status: "idle",
|
||||
capabilities: {
|
||||
supportsStreaming: true,
|
||||
supportsSessionPersistence: true,
|
||||
supportsDynamicModes: false,
|
||||
supportsMcpServers: false,
|
||||
supportsReasoningStream: false,
|
||||
supportsToolInvocations: true,
|
||||
supportsRewindConversation: true,
|
||||
supportsRewindFiles: false,
|
||||
supportsRewindBoth: false,
|
||||
},
|
||||
currentModeId: null,
|
||||
availableModes: [],
|
||||
pendingPermissions: [],
|
||||
persistence: null,
|
||||
title: null,
|
||||
labels: {},
|
||||
};
|
||||
}
|
||||
|
||||
describe("app provider switching integration", () => {
|
||||
beforeEach(() => {
|
||||
useStagedProviderSwitchStore.setState({ stagedByKey: new Map() });
|
||||
});
|
||||
|
||||
it("dispatches switchAgentProvider when staged and handles pre-commit vs post-commit failures", async () => {
|
||||
const committed: Array<AgentSnapshotPayload | undefined> = [];
|
||||
const sendAgentMessage = vi.fn().mockResolvedValue(undefined);
|
||||
const switchAgentProvider = vi.fn().mockResolvedValue({ agent: agentSnapshot("codex") });
|
||||
const submission = {
|
||||
begin: vi.fn(),
|
||||
accept: vi.fn(),
|
||||
reject: vi.fn(),
|
||||
};
|
||||
|
||||
const staged = {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
thinkingOptionId: "high",
|
||||
modeId: "auto",
|
||||
providerOptions: {},
|
||||
};
|
||||
|
||||
// Success path
|
||||
await dispatchComposerAgentMessage({
|
||||
client: {
|
||||
sendAgentMessage,
|
||||
switchAgentProvider,
|
||||
uploadFile: vi.fn(),
|
||||
getLastServerInfoMessage: () => null,
|
||||
},
|
||||
agentId: "agent-1",
|
||||
text: "Continue with Codex",
|
||||
attachments: [],
|
||||
submission,
|
||||
currentProvider: "claude",
|
||||
currentModel: "sonnet",
|
||||
stagedProviderSwitch: staged,
|
||||
onProviderSwitchCommitted: (agent) => {
|
||||
committed.push(agent);
|
||||
},
|
||||
});
|
||||
|
||||
expect(sendAgentMessage).not.toHaveBeenCalled();
|
||||
expect(switchAgentProvider).toHaveBeenCalledTimes(1);
|
||||
expect(submission.begin).toHaveBeenCalledWith(
|
||||
"agent-1",
|
||||
expect.objectContaining({ kind: "user_message", text: "Continue with Codex" }),
|
||||
expect.objectContaining({
|
||||
providerSwitch: expect.objectContaining({
|
||||
kind: "provider_switch",
|
||||
fromProvider: "claude",
|
||||
toProvider: "codex",
|
||||
fromModel: "sonnet",
|
||||
toModel: "gpt-5.4",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(committed).toEqual([expect.objectContaining({ provider: "codex" })]);
|
||||
expect(submission.accept).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Pre-commit failure: onProviderSwitchCommitted MUST NOT run
|
||||
committed.length = 0;
|
||||
switchAgentProvider.mockRejectedValueOnce(new Error("Codex CLI unavailable"));
|
||||
await expect(
|
||||
dispatchComposerAgentMessage({
|
||||
client: {
|
||||
sendAgentMessage,
|
||||
switchAgentProvider,
|
||||
uploadFile: vi.fn(),
|
||||
getLastServerInfoMessage: () => null,
|
||||
},
|
||||
agentId: "agent-1",
|
||||
text: "Retry",
|
||||
attachments: [],
|
||||
submission,
|
||||
stagedProviderSwitch: staged,
|
||||
onProviderSwitchCommitted: (agent) => {
|
||||
committed.push(agent);
|
||||
},
|
||||
}),
|
||||
).rejects.toThrow("Codex CLI unavailable");
|
||||
expect(committed).toEqual([]);
|
||||
|
||||
// Post-commit start failure (AgentProviderSwitchError with .agent): MUST commit live agent snapshot
|
||||
switchAgentProvider.mockRejectedValueOnce(
|
||||
new AgentProviderSwitchError("Rate limited", agentSnapshot("codex")),
|
||||
);
|
||||
await expect(
|
||||
dispatchComposerAgentMessage({
|
||||
client: {
|
||||
sendAgentMessage,
|
||||
switchAgentProvider,
|
||||
uploadFile: vi.fn(),
|
||||
getLastServerInfoMessage: () => null,
|
||||
},
|
||||
agentId: "agent-1",
|
||||
text: "Retry 2",
|
||||
attachments: [],
|
||||
submission,
|
||||
stagedProviderSwitch: staged,
|
||||
onProviderSwitchCommitted: (agent) => {
|
||||
committed.push(agent);
|
||||
},
|
||||
}),
|
||||
).rejects.toThrow("Rate limited");
|
||||
expect(committed).toEqual([expect.objectContaining({ provider: "codex" })]);
|
||||
});
|
||||
|
||||
it("advances activeSegmentStartSeq immediately on live provider_switch events and scopes rewind eligibility", () => {
|
||||
const preSwitchPrompt: UserMessageItem = {
|
||||
kind: "user_message",
|
||||
id: "u1",
|
||||
messageId: "u1",
|
||||
text: "Claude prompt",
|
||||
timestamp: new Date(TS),
|
||||
timelineCursor: { epoch: "ep-1", seq: 1, anchorSeq: 1 },
|
||||
};
|
||||
|
||||
const liveResult = processAgentStreamEvent({
|
||||
event: {
|
||||
type: "timeline",
|
||||
provider: "codex",
|
||||
item: {
|
||||
type: "provider_switch",
|
||||
fromProvider: "claude",
|
||||
toProvider: "codex",
|
||||
fromModel: "sonnet",
|
||||
toModel: "gpt-5.4",
|
||||
fromSessionId: "s1",
|
||||
toSessionId: null,
|
||||
context: { includedItems: 2, truncated: false, charCount: 100, budgetChars: 100_000 },
|
||||
},
|
||||
},
|
||||
seq: 3,
|
||||
epoch: "ep-1",
|
||||
currentTail: [preSwitchPrompt],
|
||||
currentHead: [],
|
||||
currentCursor: { epoch: "ep-1", startSeq: 1, endSeq: 2 },
|
||||
hasAuthoritativeBaseline: true,
|
||||
timestamp: new Date(TS),
|
||||
});
|
||||
|
||||
expect(liveResult.cursor?.activeSegmentStartSeq).toBe(3);
|
||||
expect(liveResult.tail.some((item) => item.kind === "provider_switch")).toBe(true);
|
||||
|
||||
// Pre-switch prompt (anchor 1 <= 3) is NOT rewindable; post-switch prompt (anchor 4 > 3) IS!
|
||||
expect(
|
||||
isPromptInActiveSegment(
|
||||
preSwitchPrompt.timelineCursor,
|
||||
liveResult.cursor?.activeSegmentStartSeq,
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isPromptInActiveSegment({ seq: 4, anchorSeq: 4 }, liveResult.cursor?.activeSegmentStartSeq),
|
||||
).toBe(true);
|
||||
|
||||
// Timeline page response also propagates activeSegmentStartSeq
|
||||
const pageResult = processTimelineResponse({
|
||||
payload: {
|
||||
agentId: "agent-1",
|
||||
direction: "tail",
|
||||
projection: "projected",
|
||||
reset: true,
|
||||
epoch: "ep-1",
|
||||
window: { minSeq: 1, maxSeq: 4, nextSeq: 5 },
|
||||
startCursor: { seq: 1 },
|
||||
endCursor: { seq: 4 },
|
||||
hasNewer: false,
|
||||
hasOlder: false,
|
||||
activeSegmentStartSeq: 3,
|
||||
entries: [
|
||||
{
|
||||
seqStart: 1,
|
||||
seqEnd: 1,
|
||||
provider: "claude",
|
||||
timestamp: TS,
|
||||
item: { type: "user_message", text: "Claude prompt", messageId: "u1" },
|
||||
},
|
||||
{
|
||||
seqStart: 3,
|
||||
seqEnd: 3,
|
||||
provider: "codex",
|
||||
timestamp: TS,
|
||||
item: {
|
||||
type: "provider_switch",
|
||||
fromProvider: "claude",
|
||||
toProvider: "codex",
|
||||
context: { includedItems: 1, truncated: false, charCount: 50, budgetChars: 100_000 },
|
||||
},
|
||||
},
|
||||
],
|
||||
error: null,
|
||||
},
|
||||
currentTail: [],
|
||||
currentHead: [],
|
||||
currentCursor: undefined,
|
||||
isInitializing: true,
|
||||
hasActiveInitDeferred: false,
|
||||
initRequestDirection: "tail",
|
||||
sendingClientMessageIds: [],
|
||||
});
|
||||
|
||||
expect(pageResult.cursor?.activeSegmentStartSeq).toBe(3);
|
||||
});
|
||||
|
||||
it("persists provider_switch items and activeSegmentStartSeq in ReplicaCache and keeps markers visible when turns collapse", async () => {
|
||||
const rowStore = createInMemoryRowStore();
|
||||
const cache = new ReplicaCache(rowStore);
|
||||
cache.setHosts(["srv-1"]);
|
||||
const switchItem: ProviderSwitchItem = {
|
||||
kind: "provider_switch",
|
||||
id: "provider_switch:ep-1:3",
|
||||
timestamp: new Date(TS),
|
||||
timelineCursor: { epoch: "ep-1", seq: 3, anchorSeq: 3 },
|
||||
fromProvider: "claude",
|
||||
toProvider: "codex",
|
||||
fromModel: "sonnet",
|
||||
toModel: "gpt-5.4",
|
||||
fromSessionId: "s1",
|
||||
toSessionId: null,
|
||||
context: {
|
||||
includedItems: 2,
|
||||
truncated: true,
|
||||
charCount: 150,
|
||||
budgetChars: 100_000,
|
||||
omittedReasons: ["tail_window_limit"],
|
||||
},
|
||||
};
|
||||
const items: StreamItem[] = [
|
||||
{
|
||||
kind: "user_message",
|
||||
id: "u1",
|
||||
messageId: "u1",
|
||||
text: "Hello",
|
||||
timestamp: new Date(TS),
|
||||
timelineCursor: { epoch: "ep-1", seq: 1, anchorSeq: 1 },
|
||||
},
|
||||
switchItem,
|
||||
];
|
||||
|
||||
cache.commitTimeline("srv-1", "agent-1", {
|
||||
agentId: "agent-1",
|
||||
items,
|
||||
range: { epoch: "ep-1", startSeq: 1, endSeq: 3, activeSegmentStartSeq: 3 },
|
||||
hasOlder: false,
|
||||
});
|
||||
await cache.flush();
|
||||
|
||||
const restored = await cache.readTimeline("srv-1", "agent-1");
|
||||
expect(restored?.range?.activeSegmentStartSeq).toBe(3);
|
||||
expect(restored?.items.find((i) => i.kind === "provider_switch")).toMatchObject({
|
||||
kind: "provider_switch",
|
||||
fromProvider: "claude",
|
||||
toProvider: "codex",
|
||||
context: { truncated: true, omittedReasons: ["tail_window_limit"] },
|
||||
});
|
||||
|
||||
// Turn collapse keeps provider_switch visible
|
||||
const collapsed = collapseTurns({
|
||||
tail: [
|
||||
items[0]!,
|
||||
{
|
||||
kind: "tool_call",
|
||||
id: "tc1",
|
||||
timestamp: new Date(TS),
|
||||
payload: {
|
||||
source: "agent",
|
||||
data: {
|
||||
provider: "claude",
|
||||
callId: "c1",
|
||||
name: "read",
|
||||
status: "completed",
|
||||
error: null,
|
||||
detail: { type: "read", filePath: "a.ts" },
|
||||
},
|
||||
},
|
||||
},
|
||||
switchItem,
|
||||
{
|
||||
kind: "assistant_message",
|
||||
id: "a1",
|
||||
text: "Done",
|
||||
timestamp: new Date(TS),
|
||||
},
|
||||
],
|
||||
isLatestTurnOpen: false,
|
||||
expandedHostIds: new Set(),
|
||||
getGroupedCalls: () => undefined,
|
||||
previousSummaryRowsByHostId: new Map(),
|
||||
});
|
||||
expect(collapsed.tail.some((item) => item.kind === "provider_switch")).toBe(true);
|
||||
});
|
||||
|
||||
const sentDraft = {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3",
|
||||
thinkingOptionId: "low",
|
||||
modeId: "auto",
|
||||
providerOptions: { plan_mode: false },
|
||||
};
|
||||
|
||||
it("forwards target provider setting edits made during switch startup to the live agent", async () => {
|
||||
const serverId = "srv-startup-edits";
|
||||
const applied: unknown[] = [];
|
||||
const record =
|
||||
(setting: string) => async (_agentId: string, value: unknown, opts?: unknown) => {
|
||||
applied.push({ setting, value, opts });
|
||||
};
|
||||
useStagedProviderSwitchStore.getState().stage(serverId, "agent-1", sentDraft);
|
||||
useStagedProviderSwitchStore.getState().patch(serverId, "agent-1", (current) => ({
|
||||
...current,
|
||||
model: "gpt-5.4",
|
||||
modeId: "full-auto",
|
||||
thinkingOptionId: "high",
|
||||
providerOptions: { plan_mode: true },
|
||||
}));
|
||||
|
||||
const settled = await settleCommittedProviderSwitch({
|
||||
serverId,
|
||||
agentId: "agent-1",
|
||||
sentDraft,
|
||||
committedProvider: "codex",
|
||||
client: {
|
||||
setAgentModel: record("model"),
|
||||
setAgentMode: record("mode"),
|
||||
setAgentThinkingOption: record("thinking"),
|
||||
setAgentOptions: record("options"),
|
||||
},
|
||||
});
|
||||
|
||||
const opts = { expectedProvider: "codex" };
|
||||
expect(settled).toEqual({ applied: true });
|
||||
expect(applied).toEqual([
|
||||
{ setting: "model", value: "gpt-5.4", opts },
|
||||
{ setting: "mode", value: "full-auto", opts },
|
||||
{ setting: "thinking", value: "high", opts },
|
||||
{ setting: "options", value: { plan_mode: true }, opts },
|
||||
]);
|
||||
expect(getStagedProviderSwitch(serverId, "agent-1")).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps rejected startup settings until the user retries or dismisses them", async () => {
|
||||
const serverId = "srv-rejected-startup-edits";
|
||||
const configs: unknown[] = [];
|
||||
let rejection: Error | null = new Error("Plan mode rejected by provider");
|
||||
const client = {
|
||||
applyAgentConfig: async (_agentId: string, config: unknown, opts?: unknown) => {
|
||||
configs.push({ config, opts });
|
||||
if (rejection) throw rejection;
|
||||
return null;
|
||||
},
|
||||
} as unknown as DaemonClient;
|
||||
const runtime = new HostRuntimeStore({
|
||||
deps: {
|
||||
createClient: () => client,
|
||||
connectToDaemon: async () => ({ client, serverId, hostname: null }),
|
||||
getClientId: async () => "cid_rejected_startup_edits",
|
||||
},
|
||||
});
|
||||
useSessionStore.getState().initializeSession(serverId, client, 1);
|
||||
const rejectEdit = async () => {
|
||||
useStagedProviderSwitchStore.getState().stage(serverId, "agent-1", sentDraft);
|
||||
useStagedProviderSwitchStore.getState().patch(serverId, "agent-1", (current) => ({
|
||||
...current,
|
||||
providerOptions: { plan_mode: true },
|
||||
}));
|
||||
return await settleCommittedProviderSwitch({
|
||||
serverId,
|
||||
agentId: "agent-1",
|
||||
sentDraft,
|
||||
committedProvider: "codex",
|
||||
client,
|
||||
});
|
||||
};
|
||||
|
||||
expect(await rejectEdit()).toEqual({
|
||||
applied: false,
|
||||
errorMessage: "Plan mode rejected by provider",
|
||||
});
|
||||
// The model picker clears the staged draft on a live change. The failure stays.
|
||||
clearStagedProviderSwitch(serverId, "agent-1");
|
||||
expect(getFailedStartupSettings(serverId, "agent-1")?.bundle).toEqual({
|
||||
options: { plan_mode: true },
|
||||
});
|
||||
|
||||
rejection = null;
|
||||
expect(await runtime.recoverFailedStartupSettings(serverId, "agent-1", "retry")).toBe(true);
|
||||
expect(configs).toEqual(
|
||||
Array(2).fill({
|
||||
config: { options: { plan_mode: true } },
|
||||
opts: { expectedProvider: "codex" },
|
||||
}),
|
||||
);
|
||||
expect(getFailedStartupSettings(serverId, "agent-1")).toBeNull();
|
||||
|
||||
rejection = new Error("Disconnected");
|
||||
await rejectEdit();
|
||||
expect(await runtime.recoverFailedStartupSettings(serverId, "agent-1", "discard")).toBe(true);
|
||||
expect(getFailedStartupSettings(serverId, "agent-1")).toBeNull();
|
||||
expect(configs).toHaveLength(3);
|
||||
|
||||
useSessionStore.getState().clearSession(serverId);
|
||||
});
|
||||
|
||||
it("places optimistic switch marker above submitted message, upgrades in place on commit, and handles failure and cache cleanly", async () => {
|
||||
const preSwitchPrompt: UserMessageItem = {
|
||||
kind: "user_message",
|
||||
id: "u1",
|
||||
messageId: "u1",
|
||||
text: "First prompt",
|
||||
timestamp: new Date(TS),
|
||||
timelineCursor: { epoch: "ep-1", seq: 1, anchorSeq: 1 },
|
||||
};
|
||||
const submittedMsg = createUserMessage({
|
||||
clientMessageId: "cm-switch-1",
|
||||
text: "Switched prompt",
|
||||
timestamp: new Date(TS),
|
||||
});
|
||||
const pendingMarker = createPendingProviderSwitchItem({
|
||||
clientMessageId: "cm-switch-1",
|
||||
fromProvider: "claude",
|
||||
toProvider: "codex",
|
||||
fromModel: "sonnet",
|
||||
toModel: "gpt-5.4",
|
||||
timestamp: new Date(TS),
|
||||
});
|
||||
|
||||
// 1. Atomic optimistic insert puts marker ABOVE the submitted user message.
|
||||
const submitted = appendSubmittedUserMessage({
|
||||
tail: [preSwitchPrompt],
|
||||
head: [],
|
||||
message: submittedMsg,
|
||||
providerSwitch: pendingMarker,
|
||||
});
|
||||
expect(submitted.tail.map((item) => item.kind)).toEqual([
|
||||
"user_message",
|
||||
"provider_switch",
|
||||
"user_message",
|
||||
]);
|
||||
expect(submitted.tail[1]?.id).toBe(pendingMarker.id);
|
||||
|
||||
// 2. ReplicaCache skips pending provider_switch markers (no context yet).
|
||||
const rowStore = createInMemoryRowStore();
|
||||
const cache = new ReplicaCache(rowStore);
|
||||
cache.setHosts(["srv-pending"]);
|
||||
cache.commitTimeline("srv-pending", "agent-1", {
|
||||
agentId: "agent-1",
|
||||
items: submitted.tail,
|
||||
range: { epoch: "ep-1", startSeq: 1, endSeq: 1 },
|
||||
hasOlder: false,
|
||||
});
|
||||
await cache.flush();
|
||||
const cachedPending = await cache.readTimeline("srv-pending", "agent-1");
|
||||
expect(cachedPending?.items.some((item) => item.kind === "provider_switch")).toBe(false);
|
||||
|
||||
// 3. Canonical refresh while switch is still pending preserves [pendingMarker, submittedMsg].
|
||||
const refreshed = replaceWithCanonicalStream({
|
||||
previousTail: submitted.tail,
|
||||
previousHead: [],
|
||||
canonical: [preSwitchPrompt],
|
||||
sendingClientMessageIds: ["cm-switch-1"],
|
||||
preserveContinuity: true,
|
||||
canonicalCoverage: { epoch: "ep-1", endSeq: 1 },
|
||||
});
|
||||
expect(refreshed.tail.map((item) => item.kind)).toEqual([
|
||||
"user_message",
|
||||
"provider_switch",
|
||||
"user_message",
|
||||
]);
|
||||
expect(refreshed.tail[1]?.id).toBe(pendingMarker.id);
|
||||
|
||||
// 4. Authoritative provider_switch upgrades the pending marker IN PLACE keeping its exact id and order.
|
||||
const committedSwitch = processAgentStreamEvent({
|
||||
event: {
|
||||
type: "timeline",
|
||||
provider: "codex",
|
||||
item: {
|
||||
type: "provider_switch",
|
||||
fromProvider: "claude",
|
||||
toProvider: "codex",
|
||||
fromModel: "sonnet",
|
||||
toModel: "gpt-5.4",
|
||||
fromSessionId: "s1",
|
||||
toSessionId: "s2",
|
||||
context: { includedItems: 1, truncated: false, charCount: 42, budgetChars: 100_000 },
|
||||
},
|
||||
},
|
||||
seq: 2,
|
||||
epoch: "ep-1",
|
||||
currentTail: submitted.tail,
|
||||
currentHead: [],
|
||||
currentCursor: { epoch: "ep-1", startSeq: 1, endSeq: 1 },
|
||||
hasAuthoritativeBaseline: true,
|
||||
timestamp: new Date(TS),
|
||||
});
|
||||
expect(committedSwitch.tail.map((item) => item.kind)).toEqual([
|
||||
"user_message",
|
||||
"provider_switch",
|
||||
"user_message",
|
||||
]);
|
||||
const upgradedMarker = committedSwitch.tail[1] as ProviderSwitchItem;
|
||||
expect(upgradedMarker.id).toBe(pendingMarker.id);
|
||||
expect(upgradedMarker.pendingClientMessageId).toBeUndefined();
|
||||
expect(upgradedMarker.timelineCursor).toEqual({ epoch: "ep-1", seq: 2, anchorSeq: 2 });
|
||||
expect(upgradedMarker.context?.includedItems).toBe(1);
|
||||
|
||||
// 5. Canonical user_message reconciles in place after the upgraded marker without reordering.
|
||||
const committedPrompt = processAgentStreamEvent({
|
||||
event: {
|
||||
type: "timeline",
|
||||
provider: "codex",
|
||||
item: {
|
||||
type: "user_message",
|
||||
text: "Switched prompt",
|
||||
messageId: "cm-switch-1",
|
||||
},
|
||||
},
|
||||
seq: 3,
|
||||
epoch: "ep-1",
|
||||
currentTail: committedSwitch.tail,
|
||||
currentHead: [],
|
||||
currentCursor: committedSwitch.cursor ?? undefined,
|
||||
hasAuthoritativeBaseline: true,
|
||||
timestamp: new Date(TS),
|
||||
});
|
||||
expect(committedPrompt.tail.map((item) => item.kind)).toEqual([
|
||||
"user_message",
|
||||
"provider_switch",
|
||||
"user_message",
|
||||
]);
|
||||
expect(committedPrompt.tail[1]?.id).toBe(pendingMarker.id);
|
||||
|
||||
// 6. Pre-commit rejection removes BOTH pending marker and optimistic user message.
|
||||
const preCommitRemoved = removeSubmittedUserMessage({
|
||||
tail: submitted.tail,
|
||||
head: [],
|
||||
clientMessageId: "cm-switch-1",
|
||||
});
|
||||
expect(preCommitRemoved.tail.map((item) => item.id)).toEqual(["u1"]);
|
||||
|
||||
// 7. Post-commit rejection removes only the optimistic user message and preserves the committed marker.
|
||||
const postCommitRemoved = removeSubmittedUserMessage({
|
||||
tail: committedSwitch.tail,
|
||||
head: [],
|
||||
clientMessageId: "cm-switch-1",
|
||||
});
|
||||
expect(postCommitRemoved.tail.map((item) => item.kind)).toEqual([
|
||||
"user_message",
|
||||
"provider_switch",
|
||||
]);
|
||||
|
||||
// 8. Defense in depth: arriving provider_switch without an optimistic marker inserts BEFORE trailing local user_message.
|
||||
const withoutPending = appendSubmittedUserMessage({
|
||||
tail: [preSwitchPrompt],
|
||||
head: [],
|
||||
message: submittedMsg,
|
||||
});
|
||||
const insertedBeforeLocal = processAgentStreamEvent({
|
||||
event: {
|
||||
type: "timeline",
|
||||
provider: "codex",
|
||||
item: {
|
||||
type: "provider_switch",
|
||||
fromProvider: "claude",
|
||||
toProvider: "codex",
|
||||
context: { includedItems: 1, truncated: false, charCount: 42, budgetChars: 100_000 },
|
||||
},
|
||||
},
|
||||
seq: 2,
|
||||
epoch: "ep-1",
|
||||
currentTail: withoutPending.tail,
|
||||
currentHead: [],
|
||||
currentCursor: { epoch: "ep-1", startSeq: 1, endSeq: 1 },
|
||||
hasAuthoritativeBaseline: true,
|
||||
timestamp: new Date(TS),
|
||||
});
|
||||
expect(insertedBeforeLocal.tail.map((item) => item.kind)).toEqual([
|
||||
"user_message",
|
||||
"provider_switch",
|
||||
"user_message",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,86 +0,0 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import {
|
||||
clearStagedProviderSwitch,
|
||||
getStagedProviderSwitch,
|
||||
settleStagedProviderSwitch,
|
||||
useStagedProviderSwitchStore,
|
||||
} from "./index";
|
||||
|
||||
describe("staged provider switch store", () => {
|
||||
beforeEach(() => {
|
||||
useStagedProviderSwitchStore.setState({ stagedByKey: new Map() });
|
||||
});
|
||||
|
||||
it("stages, patches, and clears per server and agent", () => {
|
||||
const store = useStagedProviderSwitchStore.getState();
|
||||
store.stage("srv-1", "agent-1", {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
thinkingOptionId: "high",
|
||||
modeId: "auto",
|
||||
providerOptions: { fast_mode: true },
|
||||
});
|
||||
store.stage("srv-1", "agent-2", {
|
||||
provider: "opencode",
|
||||
model: null,
|
||||
thinkingOptionId: null,
|
||||
modeId: null,
|
||||
providerOptions: {},
|
||||
});
|
||||
|
||||
expect(getStagedProviderSwitch("srv-1", "agent-1")).toEqual({
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
thinkingOptionId: "high",
|
||||
modeId: "auto",
|
||||
providerOptions: { fast_mode: true },
|
||||
});
|
||||
|
||||
store.patch("srv-1", "agent-1", (current) => ({
|
||||
...current,
|
||||
thinkingOptionId: "medium",
|
||||
}));
|
||||
expect(getStagedProviderSwitch("srv-1", "agent-1")?.thinkingOptionId).toBe("medium");
|
||||
|
||||
clearStagedProviderSwitch("srv-1", "agent-1");
|
||||
expect(getStagedProviderSwitch("srv-1", "agent-1")).toBeNull();
|
||||
expect(getStagedProviderSwitch("srv-1", "agent-2")?.provider).toBe("opencode");
|
||||
|
||||
store.clearForServer("srv-1");
|
||||
expect(getStagedProviderSwitch("srv-1", "agent-2")).toBeNull();
|
||||
});
|
||||
|
||||
it("settles only the draft that was sent and preserves any newer selection or edit", () => {
|
||||
const store = useStagedProviderSwitchStore.getState();
|
||||
store.stage("srv-1", "agent-1", {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
thinkingOptionId: null,
|
||||
modeId: null,
|
||||
providerOptions: {},
|
||||
});
|
||||
const sentDraft = getStagedProviderSwitch("srv-1", "agent-1")!;
|
||||
|
||||
// User chooses Copilot before Codex reply returns -> settling Codex draft preserves Copilot.
|
||||
store.stage("srv-1", "agent-1", {
|
||||
provider: "copilot",
|
||||
model: "gpt-5",
|
||||
thinkingOptionId: null,
|
||||
modeId: null,
|
||||
providerOptions: {},
|
||||
});
|
||||
settleStagedProviderSwitch("srv-1", "agent-1", sentDraft);
|
||||
const copilotDraft = getStagedProviderSwitch("srv-1", "agent-1")!;
|
||||
expect(copilotDraft.provider).toBe("copilot");
|
||||
|
||||
// Patching the draft also produces a newer revision that settling the older reference preserves.
|
||||
store.patch("srv-1", "agent-1", (current) => ({ ...current, thinkingOptionId: "high" }));
|
||||
settleStagedProviderSwitch("srv-1", "agent-1", copilotDraft);
|
||||
const patchedCopilot = getStagedProviderSwitch("srv-1", "agent-1")!;
|
||||
expect(patchedCopilot.thinkingOptionId).toBe("high");
|
||||
|
||||
// Settling the current draft clears it cleanly.
|
||||
settleStagedProviderSwitch("srv-1", "agent-1", patchedCopilot);
|
||||
expect(getStagedProviderSwitch("srv-1", "agent-1")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,418 +0,0 @@
|
||||
import { create } from "zustand";
|
||||
import type { AgentProvider, ProviderOptions } from "@getpaseo/protocol/agent-types";
|
||||
import type { AgentConfigApply, QueuedProviderSwitch } from "@getpaseo/protocol/messages";
|
||||
|
||||
export interface StagedProviderSwitch {
|
||||
provider: AgentProvider;
|
||||
model: string | null;
|
||||
thinkingOptionId: string | null;
|
||||
modeId: string | null;
|
||||
providerOptions: ProviderOptions;
|
||||
}
|
||||
|
||||
function stagedKey(serverId: string, agentId: string): string {
|
||||
return `${serverId}:${agentId}`;
|
||||
}
|
||||
|
||||
export interface LiveAgentSettingsWriter {
|
||||
applyAgentConfig?: (
|
||||
agentId: string,
|
||||
config: AgentConfigApply,
|
||||
options?: { expectedProvider?: AgentProvider },
|
||||
) => Promise<unknown>;
|
||||
setAgentModel?: (
|
||||
agentId: string,
|
||||
modelId: string | null,
|
||||
options?: { expectedProvider?: AgentProvider },
|
||||
) => Promise<unknown>;
|
||||
setAgentMode?: (
|
||||
agentId: string,
|
||||
modeId: string,
|
||||
options?: { expectedProvider?: AgentProvider },
|
||||
) => Promise<unknown>;
|
||||
setAgentThinkingOption?: (
|
||||
agentId: string,
|
||||
thinkingOptionId: string,
|
||||
options?: { expectedProvider?: AgentProvider },
|
||||
) => Promise<unknown>;
|
||||
setAgentOptions?: (
|
||||
agentId: string,
|
||||
options: ProviderOptions,
|
||||
mutationOptions?: { expectedProvider?: AgentProvider },
|
||||
) => Promise<unknown>;
|
||||
}
|
||||
|
||||
export interface FailedStartupSettings {
|
||||
provider: AgentProvider;
|
||||
bundle: AgentConfigApply;
|
||||
errorMessage: string;
|
||||
}
|
||||
|
||||
export type SettleCommittedProviderSwitchResult =
|
||||
| { applied: true }
|
||||
| { applied: false; errorMessage: string };
|
||||
|
||||
interface StagedProviderSwitchState {
|
||||
stagedByKey: Map<string, StagedProviderSwitch>;
|
||||
inFlightByKey: Map<string, number>;
|
||||
failedStartupSettingsByKey: Map<string, FailedStartupSettings>;
|
||||
stage: (serverId: string, agentId: string, draft: StagedProviderSwitch) => void;
|
||||
patch: (
|
||||
serverId: string,
|
||||
agentId: string,
|
||||
updater: (current: StagedProviderSwitch) => StagedProviderSwitch,
|
||||
) => void;
|
||||
beginSwitch: (serverId: string, agentId: string) => void;
|
||||
endSwitch: (serverId: string, agentId: string) => void;
|
||||
setFailedStartupSettings: (
|
||||
serverId: string,
|
||||
agentId: string,
|
||||
failed: FailedStartupSettings | null,
|
||||
) => void;
|
||||
settle: (serverId: string, agentId: string, sentDraft: StagedProviderSwitch) => void;
|
||||
clear: (serverId: string, agentId: string) => void;
|
||||
clearForServer: (serverId: string) => void;
|
||||
}
|
||||
|
||||
export const useStagedProviderSwitchStore = create<StagedProviderSwitchState>((set) => ({
|
||||
stagedByKey: new Map(),
|
||||
inFlightByKey: new Map(),
|
||||
failedStartupSettingsByKey: new Map(),
|
||||
|
||||
stage: (serverId, agentId, draft) =>
|
||||
set((state) => {
|
||||
const next = new Map(state.stagedByKey);
|
||||
next.set(stagedKey(serverId, agentId), draft);
|
||||
return { stagedByKey: next };
|
||||
}),
|
||||
|
||||
patch: (serverId, agentId, updater) =>
|
||||
set((state) => {
|
||||
const key = stagedKey(serverId, agentId);
|
||||
const current = state.stagedByKey.get(key);
|
||||
if (!current) return state;
|
||||
const updated = updater(current);
|
||||
if (updated === current) return state;
|
||||
const next = new Map(state.stagedByKey);
|
||||
next.set(key, updated);
|
||||
return { stagedByKey: next };
|
||||
}),
|
||||
|
||||
beginSwitch: (serverId, agentId) =>
|
||||
set((state) => {
|
||||
const key = stagedKey(serverId, agentId);
|
||||
const next = new Map(state.inFlightByKey);
|
||||
next.set(key, (next.get(key) ?? 0) + 1);
|
||||
return { inFlightByKey: next };
|
||||
}),
|
||||
|
||||
endSwitch: (serverId, agentId) =>
|
||||
set((state) => {
|
||||
const key = stagedKey(serverId, agentId);
|
||||
const count = state.inFlightByKey.get(key) ?? 0;
|
||||
if (count <= 0) return state;
|
||||
const next = new Map(state.inFlightByKey);
|
||||
if (count === 1) {
|
||||
next.delete(key);
|
||||
} else {
|
||||
next.set(key, count - 1);
|
||||
}
|
||||
return { inFlightByKey: next };
|
||||
}),
|
||||
|
||||
setFailedStartupSettings: (serverId, agentId, failed) =>
|
||||
set((state) => {
|
||||
const key = stagedKey(serverId, agentId);
|
||||
const next = new Map(state.failedStartupSettingsByKey);
|
||||
if (failed === null) {
|
||||
if (!next.has(key)) return state;
|
||||
next.delete(key);
|
||||
} else {
|
||||
next.set(key, failed);
|
||||
}
|
||||
return { failedStartupSettingsByKey: next };
|
||||
}),
|
||||
|
||||
settle: (serverId, agentId, sentDraft) =>
|
||||
set((state) => {
|
||||
const key = stagedKey(serverId, agentId);
|
||||
const current = state.stagedByKey.get(key);
|
||||
if (!current || current !== sentDraft) return state;
|
||||
const next = new Map(state.stagedByKey);
|
||||
next.delete(key);
|
||||
return { stagedByKey: next };
|
||||
}),
|
||||
|
||||
clear: (serverId, agentId) =>
|
||||
set((state) => {
|
||||
const key = stagedKey(serverId, agentId);
|
||||
if (!state.stagedByKey.has(key)) return state;
|
||||
const next = new Map(state.stagedByKey);
|
||||
next.delete(key);
|
||||
return { stagedByKey: next };
|
||||
}),
|
||||
|
||||
clearForServer: (serverId) =>
|
||||
set((state) => {
|
||||
const prefix = `${serverId}:`;
|
||||
let changed = false;
|
||||
const next = new Map(state.stagedByKey);
|
||||
for (const key of next.keys()) {
|
||||
if (key.startsWith(prefix)) {
|
||||
next.delete(key);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
const nextInFlight = new Map(state.inFlightByKey);
|
||||
for (const key of nextInFlight.keys()) {
|
||||
if (key.startsWith(prefix)) {
|
||||
nextInFlight.delete(key);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
const nextFailed = new Map(state.failedStartupSettingsByKey);
|
||||
for (const key of nextFailed.keys()) {
|
||||
if (key.startsWith(prefix)) {
|
||||
nextFailed.delete(key);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
return changed
|
||||
? {
|
||||
stagedByKey: next,
|
||||
inFlightByKey: nextInFlight,
|
||||
failedStartupSettingsByKey: nextFailed,
|
||||
}
|
||||
: state;
|
||||
}),
|
||||
}));
|
||||
|
||||
/** A switch the host holds in its queue, as the composer stages it. */
|
||||
export function toStagedProviderSwitch(queued: QueuedProviderSwitch): StagedProviderSwitch {
|
||||
return {
|
||||
provider: queued.provider,
|
||||
model: queued.model ?? null,
|
||||
modeId: queued.modeId ?? null,
|
||||
thinkingOptionId: queued.thinkingOptionId ?? null,
|
||||
providerOptions: queued.providerOptions ?? {},
|
||||
};
|
||||
}
|
||||
|
||||
export function getStagedProviderSwitch(
|
||||
serverId: string,
|
||||
agentId: string,
|
||||
): StagedProviderSwitch | null {
|
||||
return (
|
||||
useStagedProviderSwitchStore.getState().stagedByKey.get(stagedKey(serverId, agentId)) ?? null
|
||||
);
|
||||
}
|
||||
|
||||
export function beginStagedProviderSwitch(serverId: string, agentId: string): void {
|
||||
useStagedProviderSwitchStore.getState().beginSwitch(serverId, agentId);
|
||||
}
|
||||
|
||||
export function endStagedProviderSwitch(serverId: string, agentId: string): void {
|
||||
useStagedProviderSwitchStore.getState().endSwitch(serverId, agentId);
|
||||
}
|
||||
|
||||
export function isStagedProviderSwitchInFlight(serverId: string, agentId: string): boolean {
|
||||
return (
|
||||
(useStagedProviderSwitchStore.getState().inFlightByKey.get(stagedKey(serverId, agentId)) ?? 0) >
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
export function getFailedStartupSettings(
|
||||
serverId: string,
|
||||
agentId: string,
|
||||
): FailedStartupSettings | null {
|
||||
return (
|
||||
useStagedProviderSwitchStore
|
||||
.getState()
|
||||
.failedStartupSettingsByKey.get(stagedKey(serverId, agentId)) ?? null
|
||||
);
|
||||
}
|
||||
|
||||
export function useFailedStartupSettings(
|
||||
serverId: string,
|
||||
agentId: string,
|
||||
): FailedStartupSettings | null {
|
||||
return useStagedProviderSwitchStore(
|
||||
(state) => state.failedStartupSettingsByKey.get(stagedKey(serverId, agentId)) ?? null,
|
||||
);
|
||||
}
|
||||
|
||||
export function discardFailedStartupSettings(serverId: string, agentId: string): void {
|
||||
useStagedProviderSwitchStore.getState().setFailedStartupSettings(serverId, agentId, null);
|
||||
}
|
||||
|
||||
export function settleStagedProviderSwitch(
|
||||
serverId: string,
|
||||
agentId: string,
|
||||
sentDraft: StagedProviderSwitch,
|
||||
): void {
|
||||
useStagedProviderSwitchStore.getState().settle(serverId, agentId, sentDraft);
|
||||
}
|
||||
|
||||
function diffProviderOptions(
|
||||
sent: ProviderOptions,
|
||||
edited: ProviderOptions,
|
||||
): ProviderOptions | null {
|
||||
const patch: ProviderOptions = {};
|
||||
let hasDiff = false;
|
||||
for (const [key, value] of Object.entries(edited)) {
|
||||
if (sent[key] !== value) {
|
||||
patch[key] = value;
|
||||
hasDiff = true;
|
||||
}
|
||||
}
|
||||
return hasDiff ? patch : null;
|
||||
}
|
||||
|
||||
function buildEditedSettingsBundle(
|
||||
sentDraft: StagedProviderSwitch,
|
||||
editedDraft: StagedProviderSwitch,
|
||||
): AgentConfigApply | null {
|
||||
const config: AgentConfigApply = {};
|
||||
let hasChanges = false;
|
||||
if (editedDraft.model !== sentDraft.model) {
|
||||
config.modelId = editedDraft.model;
|
||||
hasChanges = true;
|
||||
}
|
||||
if (editedDraft.modeId !== sentDraft.modeId && editedDraft.modeId !== null) {
|
||||
config.modeId = editedDraft.modeId;
|
||||
hasChanges = true;
|
||||
}
|
||||
if (
|
||||
editedDraft.thinkingOptionId !== sentDraft.thinkingOptionId &&
|
||||
editedDraft.thinkingOptionId !== null
|
||||
) {
|
||||
config.thinkingOptionId = editedDraft.thinkingOptionId;
|
||||
hasChanges = true;
|
||||
}
|
||||
const optionsPatch = diffProviderOptions(sentDraft.providerOptions, editedDraft.providerOptions);
|
||||
if (optionsPatch) {
|
||||
config.options = optionsPatch;
|
||||
hasChanges = true;
|
||||
}
|
||||
return hasChanges ? config : null;
|
||||
}
|
||||
|
||||
async function applyEditedDraftSettingsToLiveAgent(
|
||||
agentId: string,
|
||||
bundle: AgentConfigApply,
|
||||
expectedProvider: AgentProvider,
|
||||
client: LiveAgentSettingsWriter,
|
||||
): Promise<void> {
|
||||
const providerGuard = { expectedProvider };
|
||||
if (client.applyAgentConfig) {
|
||||
await client.applyAgentConfig(agentId, bundle, providerGuard);
|
||||
return;
|
||||
}
|
||||
if (bundle.modelId !== undefined && client.setAgentModel) {
|
||||
await client.setAgentModel(agentId, bundle.modelId, providerGuard);
|
||||
}
|
||||
if (bundle.modeId !== undefined && client.setAgentMode) {
|
||||
await client.setAgentMode(agentId, bundle.modeId, providerGuard);
|
||||
}
|
||||
if (
|
||||
bundle.thinkingOptionId !== undefined &&
|
||||
bundle.thinkingOptionId !== null &&
|
||||
client.setAgentThinkingOption
|
||||
) {
|
||||
await client.setAgentThinkingOption(agentId, bundle.thinkingOptionId, providerGuard);
|
||||
}
|
||||
if (bundle.options && client.setAgentOptions) {
|
||||
await client.setAgentOptions(agentId, bundle.options, providerGuard);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Settles the staged draft captured by a committed switch and awaits any edited settings
|
||||
* for the provider that just became live before callers release queued follow-up prompts.
|
||||
* - Untouched draft: cleared.
|
||||
* - Newer draft targeting a different provider: preserved for the next switch.
|
||||
* - Newer draft editing settings of the provider that just became live: applied atomically
|
||||
* (via `applyAgentConfig` when available, else sequential setters) before settling the draft.
|
||||
* If the daemon rejects an edit, the draft is kept intact and `{ applied: false, errorMessage }`
|
||||
* is returned so callers surface the error and hold any queued follow-up prompt.
|
||||
*/
|
||||
export async function settleCommittedProviderSwitch(input: {
|
||||
serverId: string;
|
||||
agentId: string;
|
||||
sentDraft: StagedProviderSwitch;
|
||||
committedProvider?: AgentProvider | null;
|
||||
client?: LiveAgentSettingsWriter | null;
|
||||
}): Promise<SettleCommittedProviderSwitchResult> {
|
||||
const { serverId, agentId, sentDraft, committedProvider, client } = input;
|
||||
const store = useStagedProviderSwitchStore.getState();
|
||||
store.settle(serverId, agentId, sentDraft);
|
||||
const remaining = getStagedProviderSwitch(serverId, agentId);
|
||||
const liveProvider = committedProvider ?? sentDraft.provider;
|
||||
if (!remaining || remaining.provider !== liveProvider) {
|
||||
return { applied: true };
|
||||
}
|
||||
const bundle = buildEditedSettingsBundle(sentDraft, remaining);
|
||||
if (!bundle || !client) {
|
||||
store.settle(serverId, agentId, remaining);
|
||||
return { applied: true };
|
||||
}
|
||||
try {
|
||||
await applyEditedDraftSettingsToLiveAgent(agentId, bundle, liveProvider, client);
|
||||
store.settle(serverId, agentId, remaining);
|
||||
return { applied: true };
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
store.settle(serverId, agentId, remaining);
|
||||
store.setFailedStartupSettings(serverId, agentId, {
|
||||
provider: liveProvider,
|
||||
bundle,
|
||||
errorMessage,
|
||||
});
|
||||
console.warn("[ProviderSwitch] failed to forward edited settings after switch", error);
|
||||
return { applied: false, errorMessage };
|
||||
}
|
||||
}
|
||||
|
||||
/** Retries applying previously failed startup settings for a committed provider switch. */
|
||||
export async function applyFailedStartupSettings(input: {
|
||||
serverId: string;
|
||||
agentId: string;
|
||||
client: LiveAgentSettingsWriter;
|
||||
}): Promise<SettleCommittedProviderSwitchResult> {
|
||||
const { serverId, agentId, client } = input;
|
||||
const failed = getFailedStartupSettings(serverId, agentId);
|
||||
if (!failed) {
|
||||
return { applied: true };
|
||||
}
|
||||
const store = useStagedProviderSwitchStore.getState();
|
||||
try {
|
||||
await applyEditedDraftSettingsToLiveAgent(agentId, failed.bundle, failed.provider, client);
|
||||
store.setFailedStartupSettings(serverId, agentId, null);
|
||||
return { applied: true };
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
store.setFailedStartupSettings(serverId, agentId, { ...failed, errorMessage });
|
||||
console.warn("[ProviderSwitch] failed to retry startup settings", error);
|
||||
return { applied: false, errorMessage };
|
||||
}
|
||||
}
|
||||
|
||||
export function clearStagedProviderSwitch(serverId: string, agentId: string): void {
|
||||
useStagedProviderSwitchStore.getState().clear(serverId, agentId);
|
||||
}
|
||||
|
||||
export function useStagedProviderSwitch(
|
||||
serverId: string,
|
||||
agentId: string,
|
||||
): StagedProviderSwitch | null {
|
||||
return useStagedProviderSwitchStore(
|
||||
(state) => state.stagedByKey.get(stagedKey(serverId, agentId)) ?? null,
|
||||
);
|
||||
}
|
||||
|
||||
export function useIsStagedProviderSwitchInFlight(serverId: string, agentId: string): boolean {
|
||||
return useStagedProviderSwitchStore(
|
||||
(state) => (state.inFlightByKey.get(stagedKey(serverId, agentId)) ?? 0) > 0,
|
||||
);
|
||||
}
|
||||
@@ -1,148 +0,0 @@
|
||||
import type { PaseoAgentQueueItem, PaseoAgentQueueWithdrawResult } from "@getpaseo/client";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { createAgentQueueModel, type AgentQueuePort } from "@/agent-queue/model";
|
||||
import { cancelQueuedMessage, editQueuedMessage, sendQueuedMessageNow } from "./actions";
|
||||
|
||||
const upload = {
|
||||
type: "uploaded_file" as const,
|
||||
id: "upload-1",
|
||||
fileName: "photo.png",
|
||||
mimeType: "image/png",
|
||||
size: 1,
|
||||
path: "/tmp/photo.png",
|
||||
role: "image" as const,
|
||||
};
|
||||
|
||||
const queued: PaseoAgentQueueItem = {
|
||||
id: "a",
|
||||
seq: 1,
|
||||
enqueuedAt: "2026-11-30T00:00:00.000Z",
|
||||
text: "look at this",
|
||||
attachments: [upload],
|
||||
sender: { kind: "user" },
|
||||
held: false,
|
||||
state: "queued",
|
||||
};
|
||||
|
||||
/** A real queue model over a host that already holds one message. */
|
||||
async function queueHolding(withdraw: PaseoAgentQueueWithdrawResult) {
|
||||
const promoted: string[] = [];
|
||||
const port: AgentQueuePort = {
|
||||
list: async () => ({ held: false, items: [queued] }),
|
||||
withdraw: async () => withdraw,
|
||||
promote: async (messageId, behavior) => {
|
||||
promoted.push(`${messageId}:${behavior}`);
|
||||
return { promoted: true };
|
||||
},
|
||||
observe: ({ update }) => {
|
||||
update({ held: false, items: [queued] });
|
||||
return () => {};
|
||||
},
|
||||
};
|
||||
const model = createAgentQueueModel(port);
|
||||
model.subscribe(() => {});
|
||||
|
||||
const restored: Array<{ text: string; attachments: unknown[] }> = [];
|
||||
let alreadySending = 0;
|
||||
return {
|
||||
model,
|
||||
promoted,
|
||||
restored,
|
||||
alreadySendingCount: () => alreadySending,
|
||||
composer: {
|
||||
restore: (message: { text: string; attachments: unknown[] }) => restored.push(message),
|
||||
alreadySending: () => {
|
||||
alreadySending += 1;
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const withdrawn: PaseoAgentQueueWithdrawResult = { withdrawn: true, item: queued };
|
||||
|
||||
const dispatching: PaseoAgentQueueWithdrawResult = {
|
||||
withdrawn: false,
|
||||
reason: "already_dispatching",
|
||||
};
|
||||
|
||||
describe("editQueuedMessage", () => {
|
||||
it("puts the withdrawn text and attachments back in the composer", async () => {
|
||||
const queue = await queueHolding(withdrawn);
|
||||
|
||||
await editQueuedMessage({ model: queue.model, messageId: "a", ...queue.composer });
|
||||
|
||||
expect(queue.restored).toEqual([
|
||||
{
|
||||
text: "look at this",
|
||||
attachments: [{ kind: "agent_attachment", attachment: upload }],
|
||||
providerSwitch: null,
|
||||
},
|
||||
]);
|
||||
expect(queue.alreadySendingCount()).toBe(0);
|
||||
expect(queue.model.getSnapshot().items).toEqual([]);
|
||||
});
|
||||
|
||||
it("gives back the provider switch the message was queued with", async () => {
|
||||
const queue = await queueHolding({
|
||||
withdrawn: true,
|
||||
item: { ...queued, providerSwitch: { provider: "codex", model: "gpt-5.4" } },
|
||||
});
|
||||
|
||||
await editQueuedMessage({ model: queue.model, messageId: "a", ...queue.composer });
|
||||
|
||||
expect(queue.restored).toMatchObject([
|
||||
{
|
||||
providerSwitch: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
modeId: null,
|
||||
thinkingOptionId: null,
|
||||
providerOptions: {},
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("leaves the composer alone when the message already started sending", async () => {
|
||||
const queue = await queueHolding(dispatching);
|
||||
|
||||
await editQueuedMessage({ model: queue.model, messageId: "a", ...queue.composer });
|
||||
|
||||
expect(queue.restored).toEqual([]);
|
||||
expect(queue.alreadySendingCount()).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("cancelQueuedMessage", () => {
|
||||
it("withdraws the message without touching the composer", async () => {
|
||||
const queue = await queueHolding(withdrawn);
|
||||
|
||||
await cancelQueuedMessage({ model: queue.model, messageId: "a", ...queue.composer });
|
||||
|
||||
expect(queue.model.getSnapshot().items).toEqual([]);
|
||||
expect(queue.restored).toEqual([]);
|
||||
expect(queue.alreadySendingCount()).toBe(0);
|
||||
});
|
||||
|
||||
it("says so when the message already started sending", async () => {
|
||||
const queue = await queueHolding(dispatching);
|
||||
|
||||
await cancelQueuedMessage({ model: queue.model, messageId: "a", ...queue.composer });
|
||||
|
||||
expect(queue.alreadySendingCount()).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("sendQueuedMessageNow", () => {
|
||||
it.each([
|
||||
["steer", "a:steer"],
|
||||
["interrupt", "a:interrupt"],
|
||||
["queue", "a:interrupt"],
|
||||
] as const)("with the %s send behavior promotes as %s", async (sendBehavior, expected) => {
|
||||
const queue = await queueHolding(withdrawn);
|
||||
|
||||
await sendQueuedMessageNow({ model: queue.model, messageId: "a", sendBehavior });
|
||||
|
||||
expect(queue.promoted).toEqual([expected]);
|
||||
});
|
||||
});
|
||||
@@ -1,56 +0,0 @@
|
||||
import type { AgentQueueModel } from "@/agent-queue";
|
||||
import type { UserComposerAttachment } from "@/attachments/types";
|
||||
import type { SendBehavior } from "@/composer/input/state";
|
||||
import { toStagedProviderSwitch, type StagedProviderSwitch } from "@/composer/provider-switch";
|
||||
|
||||
export interface RestoredQueuedMessage {
|
||||
text: string;
|
||||
attachments: UserComposerAttachment[];
|
||||
/** The switch the message was queued with, to stage again. */
|
||||
providerSwitch: StagedProviderSwitch | null;
|
||||
}
|
||||
|
||||
interface WithdrawInput {
|
||||
model: Pick<AgentQueueModel, "withdraw">;
|
||||
messageId: string;
|
||||
/** The message left the queue before the host got the request. */
|
||||
alreadySending: () => void;
|
||||
}
|
||||
|
||||
/** Moves a queued message back into the composer. Only the host can say it is still queued. */
|
||||
export async function editQueuedMessage(
|
||||
input: WithdrawInput & { restore: (message: RestoredQueuedMessage) => void },
|
||||
): Promise<void> {
|
||||
const result = await input.model.withdraw(input.messageId);
|
||||
if (!result) return;
|
||||
if (!result.withdrawn) {
|
||||
input.alreadySending();
|
||||
return;
|
||||
}
|
||||
input.restore({
|
||||
text: result.item.text,
|
||||
attachments: (result.item.attachments ?? []).map((attachment) => ({
|
||||
kind: "agent_attachment",
|
||||
attachment,
|
||||
})),
|
||||
providerSwitch: result.item.providerSwitch
|
||||
? toStagedProviderSwitch(result.item.providerSwitch)
|
||||
: null,
|
||||
});
|
||||
}
|
||||
|
||||
export async function cancelQueuedMessage(input: WithdrawInput): Promise<void> {
|
||||
const result = await input.model.withdraw(input.messageId);
|
||||
if (result && !result.withdrawn) input.alreadySending();
|
||||
}
|
||||
|
||||
export async function sendQueuedMessageNow(input: {
|
||||
model: Pick<AgentQueueModel, "promote">;
|
||||
messageId: string;
|
||||
sendBehavior: SendBehavior;
|
||||
}): Promise<void> {
|
||||
await input.model.promote(
|
||||
input.messageId,
|
||||
input.sendBehavior === "steer" ? "steer" : "interrupt",
|
||||
);
|
||||
}
|
||||
@@ -1,334 +0,0 @@
|
||||
import { useCallback, useMemo, type ReactElement, type ReactNode } from "react";
|
||||
import { Text, View } from "react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { useShallow } from "zustand/shallow";
|
||||
import {
|
||||
ArrowRightLeft,
|
||||
ArrowUp,
|
||||
Bot,
|
||||
GitPullRequest,
|
||||
Paperclip,
|
||||
Pause,
|
||||
Pencil,
|
||||
X,
|
||||
} from "lucide-react-native";
|
||||
import type { PaseoAgentQueueItem } from "@getpaseo/client";
|
||||
import { useAgentQueue } from "@/agent-queue";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { mutedIconColorMapping } from "@/components/ui/icon-button-chrome";
|
||||
import { paneContentToolbarIconSize, ToolbarButton } from "@/components/ui/pane-content-toolbar";
|
||||
import { ScrollView } from "@/components/ui/scroll-view";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import type { SendBehavior } from "@/composer/input/state";
|
||||
import { COMPOSER_PADDING_HORIZONTAL } from "@/composer/input/toolbar-rails";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { ICON_SIZE } from "@/styles/theme";
|
||||
import {
|
||||
cancelQueuedMessage,
|
||||
editQueuedMessage,
|
||||
sendQueuedMessageNow,
|
||||
type RestoredQueuedMessage,
|
||||
} from "./actions";
|
||||
import { presentQueue, type QueueRowView } from "./view";
|
||||
|
||||
const ThemedArrowRightLeft = withUnistyles(ArrowRightLeft);
|
||||
const ThemedArrowUp = withUnistyles(ArrowUp);
|
||||
const ThemedBot = withUnistyles(Bot);
|
||||
const ThemedGitPullRequest = withUnistyles(GitPullRequest);
|
||||
const ThemedPaperclip = withUnistyles(Paperclip);
|
||||
const ThemedPause = withUnistyles(Pause);
|
||||
const ThemedPencil = withUnistyles(Pencil);
|
||||
const ThemedX = withUnistyles(X);
|
||||
|
||||
/** A few rows and the top of the next, so a longer queue reads as scrollable. */
|
||||
const QUEUE_MAX_HEIGHT = 240;
|
||||
/** Keep ~2 rows readable on phones without crowding the conversation or composer. */
|
||||
const QUEUE_MAX_HEIGHT_COMPACT = 140;
|
||||
|
||||
interface ComposerQueueTrackProps {
|
||||
serverId: string;
|
||||
agentId: string;
|
||||
/** The user's send behavior setting. Send now steers or interrupts accordingly. */
|
||||
sendBehavior: SendBehavior;
|
||||
providerLabel: (provider: string) => string;
|
||||
onRestore: (message: RestoredQueuedMessage) => void;
|
||||
onAlreadySending: () => void;
|
||||
onError: (error: unknown) => void;
|
||||
}
|
||||
|
||||
/** The messages the host holds for this agent, in the order it will send them. */
|
||||
export function ComposerQueueTrack({
|
||||
serverId,
|
||||
agentId,
|
||||
sendBehavior,
|
||||
providerLabel,
|
||||
onRestore,
|
||||
onAlreadySending,
|
||||
onError,
|
||||
}: ComposerQueueTrackProps): ReactElement | null {
|
||||
const { t } = useTranslation();
|
||||
const isCompact = useIsCompactFormFactor();
|
||||
const { model, queue } = useAgentQueue(serverId, agentId);
|
||||
const titles = useSessionStore(useShallow(selectSenderTitles(queue.items, serverId)));
|
||||
const view = useMemo(
|
||||
() =>
|
||||
presentQueue(queue, {
|
||||
t,
|
||||
agentTitle: (senderId) => titles[senderId] ?? null,
|
||||
providerLabel,
|
||||
}),
|
||||
[providerLabel, queue, t, titles],
|
||||
);
|
||||
|
||||
const handleEdit = useCallback(
|
||||
(messageId: string) => {
|
||||
editQueuedMessage({
|
||||
model,
|
||||
messageId,
|
||||
restore: onRestore,
|
||||
alreadySending: onAlreadySending,
|
||||
}).catch(onError);
|
||||
},
|
||||
[model, onRestore, onAlreadySending, onError],
|
||||
);
|
||||
const handleCancel = useCallback(
|
||||
(messageId: string) => {
|
||||
cancelQueuedMessage({ model, messageId, alreadySending: onAlreadySending }).catch(onError);
|
||||
},
|
||||
[model, onAlreadySending, onError],
|
||||
);
|
||||
const handleSendNow = useCallback(
|
||||
(messageId: string) => {
|
||||
sendQueuedMessageNow({ model, messageId, sendBehavior }).catch(onError);
|
||||
},
|
||||
[model, sendBehavior, onError],
|
||||
);
|
||||
|
||||
const failedToLoad = queue.status === "error";
|
||||
if (view.rows.length === 0 && !failedToLoad) return null;
|
||||
|
||||
return (
|
||||
<View style={styles.track}>
|
||||
{failedToLoad ? (
|
||||
<View style={styles.status}>
|
||||
<Text style={styles.muted}>{t("composer.queue.loadFailed")}</Text>
|
||||
<Button variant="ghost" size="sm" onPress={model.retry}>
|
||||
{t("composer.queue.retry")}
|
||||
</Button>
|
||||
</View>
|
||||
) : null}
|
||||
{view.notice ? (
|
||||
<View style={styles.status}>
|
||||
<LineIcon>
|
||||
<ThemedPause size={ICON_SIZE.xs} uniProps={mutedIconColorMapping} />
|
||||
</LineIcon>
|
||||
<Text style={styles.muted}>{view.notice}</Text>
|
||||
</View>
|
||||
) : null}
|
||||
{/* The frame sizes the list: a style on this ScrollView is dropped on web. */}
|
||||
<View style={[styles.rowsFrame, isCompact && styles.rowsFrameCompact]}>
|
||||
<ScrollView keyboardShouldPersistTaps="handled" nestedScrollEnabled>
|
||||
<View style={styles.rows} role="list" aria-label={t("composer.queue.title")}>
|
||||
{view.rows.map((row) => (
|
||||
<QueueRow
|
||||
key={row.id}
|
||||
row={row}
|
||||
onEdit={handleEdit}
|
||||
onCancel={handleCancel}
|
||||
onSendNow={handleSendNow}
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
</ScrollView>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
/** An icon beside text that truncates keeps its size; the text gives up the width. */
|
||||
function LineIcon({ children }: { children: ReactNode }): ReactElement {
|
||||
return <View style={styles.lineIcon}>{children}</View>;
|
||||
}
|
||||
|
||||
function selectSenderTitles(items: PaseoAgentQueueItem[], hostId: string) {
|
||||
return (state: ReturnType<typeof useSessionStore.getState>): Record<string, string> => {
|
||||
const titles: Record<string, string> = {};
|
||||
for (const { sender } of items) {
|
||||
if (sender.kind !== "agent_message" && sender.kind !== "agent_notification") continue;
|
||||
const session = state.sessions[sender.serverId ?? hostId];
|
||||
const agent =
|
||||
session?.agents.get(sender.agentId) ?? session?.agentDetails.get(sender.agentId);
|
||||
if (agent?.title) titles[sender.agentId] = agent.title;
|
||||
}
|
||||
return titles;
|
||||
};
|
||||
}
|
||||
|
||||
function QueueRow({
|
||||
row,
|
||||
onEdit,
|
||||
onCancel,
|
||||
onSendNow,
|
||||
}: {
|
||||
row: QueueRowView;
|
||||
onEdit: (messageId: string) => void;
|
||||
onCancel: (messageId: string) => void;
|
||||
onSendNow: (messageId: string) => void;
|
||||
}): ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const isCompact = useIsCompactFormFactor();
|
||||
const iconSize = paneContentToolbarIconSize(isCompact);
|
||||
const handleEdit = useCallback(() => onEdit(row.id), [onEdit, row.id]);
|
||||
const handleCancel = useCallback(() => onCancel(row.id), [onCancel, row.id]);
|
||||
const handleSendNow = useCallback(() => onSendNow(row.id), [onSendNow, row.id]);
|
||||
|
||||
return (
|
||||
<View style={styles.row} role="listitem">
|
||||
<View style={styles.body}>
|
||||
{row.label ? (
|
||||
<View style={styles.meta}>
|
||||
<LineIcon>
|
||||
{row.icon === "change_request" ? (
|
||||
<ThemedGitPullRequest size={ICON_SIZE.xs} uniProps={mutedIconColorMapping} />
|
||||
) : (
|
||||
<ThemedBot size={ICON_SIZE.xs} uniProps={mutedIconColorMapping} />
|
||||
)}
|
||||
</LineIcon>
|
||||
<Text style={styles.metaText} numberOfLines={1}>
|
||||
{row.label}
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
{row.preview ? (
|
||||
<Text style={styles.preview} numberOfLines={2} ellipsizeMode="tail">
|
||||
{row.preview}
|
||||
</Text>
|
||||
) : null}
|
||||
{row.attachmentLabel ? (
|
||||
<View style={styles.meta}>
|
||||
<LineIcon>
|
||||
<ThemedPaperclip size={ICON_SIZE.xs} uniProps={mutedIconColorMapping} />
|
||||
</LineIcon>
|
||||
<Text style={styles.metaText}>{row.attachmentLabel}</Text>
|
||||
</View>
|
||||
) : null}
|
||||
{row.switchLabel ? (
|
||||
<View style={styles.meta}>
|
||||
<LineIcon>
|
||||
<ThemedArrowRightLeft size={ICON_SIZE.xs} uniProps={mutedIconColorMapping} />
|
||||
</LineIcon>
|
||||
<Text style={styles.metaText} numberOfLines={1}>
|
||||
{row.switchLabel}
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
<View style={styles.actions}>
|
||||
{row.canEdit ? (
|
||||
<ToolbarButton
|
||||
label={t("composer.queue.edit")}
|
||||
tooltipSide="top"
|
||||
compact={isCompact}
|
||||
disabled={row.disabled}
|
||||
onPress={handleEdit}
|
||||
>
|
||||
<ThemedPencil size={iconSize} uniProps={mutedIconColorMapping} />
|
||||
</ToolbarButton>
|
||||
) : null}
|
||||
<ToolbarButton
|
||||
label={t("composer.queue.sendNow")}
|
||||
tooltipSide="top"
|
||||
compact={isCompact}
|
||||
disabled={row.disabled}
|
||||
onPress={handleSendNow}
|
||||
>
|
||||
<ThemedArrowUp size={iconSize} uniProps={mutedIconColorMapping} />
|
||||
</ToolbarButton>
|
||||
<ToolbarButton
|
||||
label={t("composer.queue.cancel")}
|
||||
tooltipSide="top"
|
||||
compact={isCompact}
|
||||
disabled={row.disabled}
|
||||
onPress={handleCancel}
|
||||
>
|
||||
<ThemedX size={iconSize} uniProps={mutedIconColorMapping} />
|
||||
</ToolbarButton>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
// The composer's height is capped. When it runs out, the queue gives up height and its rows
|
||||
// scroll before the message input shrinks.
|
||||
track: {
|
||||
flexShrink: 1000,
|
||||
minHeight: 0,
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
// Rows put their text on the composer's text rail: the same border, then the same padding.
|
||||
// The status line carries a clear border to land there too.
|
||||
status: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
paddingHorizontal: COMPOSER_PADDING_HORIZONTAL,
|
||||
borderLeftWidth: theme.borderWidth[1],
|
||||
borderColor: "transparent",
|
||||
},
|
||||
muted: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
},
|
||||
rowsFrame: {
|
||||
flexShrink: 1,
|
||||
minHeight: 0,
|
||||
maxHeight: QUEUE_MAX_HEIGHT,
|
||||
},
|
||||
rowsFrameCompact: {
|
||||
maxHeight: QUEUE_MAX_HEIGHT_COMPACT,
|
||||
},
|
||||
rows: {
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
row: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
paddingLeft: COMPOSER_PADDING_HORIZONTAL,
|
||||
paddingRight: theme.spacing[2],
|
||||
paddingVertical: theme.spacing[2],
|
||||
backgroundColor: theme.colors.surface1,
|
||||
borderRadius: theme.borderRadius.lg,
|
||||
borderWidth: theme.borderWidth[1],
|
||||
borderColor: theme.colors.border,
|
||||
},
|
||||
body: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
gap: theme.spacing[1],
|
||||
},
|
||||
meta: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[1],
|
||||
},
|
||||
lineIcon: {
|
||||
flexShrink: 0,
|
||||
},
|
||||
metaText: {
|
||||
flexShrink: 1,
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
},
|
||||
preview: {
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.base,
|
||||
},
|
||||
actions: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[1],
|
||||
},
|
||||
}));
|
||||
@@ -1,156 +0,0 @@
|
||||
import type { PaseoAgentQueueItem } from "@getpaseo/client";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import { presentQueue } from "./view";
|
||||
|
||||
function item(id: string, patch: Partial<PaseoAgentQueueItem> = {}): PaseoAgentQueueItem {
|
||||
return {
|
||||
id,
|
||||
seq: 1,
|
||||
enqueuedAt: "2026-11-30T00:00:00.000Z",
|
||||
text: `message ${id}`,
|
||||
sender: { kind: "user" },
|
||||
held: false,
|
||||
state: "queued",
|
||||
...patch,
|
||||
};
|
||||
}
|
||||
|
||||
function present(
|
||||
items: PaseoAgentQueueItem[],
|
||||
options: { held?: boolean; busy?: string[]; titles?: Record<string, string> } = {},
|
||||
) {
|
||||
return presentQueue(
|
||||
{
|
||||
status: "ready",
|
||||
held: options.held ?? false,
|
||||
items,
|
||||
busy: new Set(options.busy),
|
||||
},
|
||||
{
|
||||
t: i18n.t,
|
||||
agentTitle: (agentId) => options.titles?.[agentId] ?? null,
|
||||
providerLabel: (provider) => provider.toUpperCase(),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
describe("presentQueue", () => {
|
||||
it("lists a user message with its attachments and lets it be edited", () => {
|
||||
const queue = present([
|
||||
item("a", {
|
||||
text: "line one\nline two",
|
||||
attachments: [
|
||||
{
|
||||
type: "uploaded_file",
|
||||
id: "upload-1",
|
||||
fileName: "photo.png",
|
||||
mimeType: "image/png",
|
||||
size: 1,
|
||||
path: "/tmp/photo.png",
|
||||
role: "image",
|
||||
},
|
||||
],
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(queue.rows).toEqual([
|
||||
{
|
||||
id: "a",
|
||||
icon: null,
|
||||
label: null,
|
||||
preview: "line one\nline two",
|
||||
attachmentLabel: "1 attachment",
|
||||
switchLabel: null,
|
||||
canEdit: true,
|
||||
disabled: false,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("says which provider a queued message switches the chat to", () => {
|
||||
const [row] = present([item("a", { providerSwitch: { provider: "codex" } })]).rows;
|
||||
|
||||
expect(row).toMatchObject({ switchLabel: "Switches to CODEX" });
|
||||
});
|
||||
|
||||
it("names the agent that sent a message and does not offer Edit", () => {
|
||||
const sender = { kind: "agent_message" as const, agentId: "child", title: "Old title" };
|
||||
const [row] = present([item("a", { sender })], { titles: { child: "Reviewer" } }).rows;
|
||||
|
||||
expect(row).toMatchObject({ icon: "agent", label: "Sent by Reviewer", canEdit: false });
|
||||
});
|
||||
|
||||
it("falls back to the title the host recorded, then to the agent id", () => {
|
||||
const rows = present([
|
||||
item("a", { sender: { kind: "agent_message", agentId: "one", title: "Recorded" } }),
|
||||
item("b", { sender: { kind: "agent_message", agentId: "two" } }),
|
||||
]).rows;
|
||||
|
||||
expect(rows.map((row) => row.label)).toEqual(["Sent by Recorded", "Sent by two"]);
|
||||
});
|
||||
|
||||
it("labels each agent notification with what happened", () => {
|
||||
const events = ["finished", "errored", "permission-required", "closed"] as const;
|
||||
const rows = present(
|
||||
events.map((event) =>
|
||||
item(event, {
|
||||
text: "Agent child (Builder) finished.\n\n<agent-response>\nDone\n</agent-response>",
|
||||
sender: { kind: "agent_notification", agentId: "child", title: "Builder", event },
|
||||
}),
|
||||
),
|
||||
).rows;
|
||||
|
||||
expect(rows.map((row) => row.label)).toEqual([
|
||||
"Builder finished",
|
||||
"Builder errored",
|
||||
"Builder needs permission",
|
||||
"Builder closed",
|
||||
]);
|
||||
expect(rows[0]).toMatchObject({
|
||||
icon: "agent",
|
||||
canEdit: false,
|
||||
preview: "Agent child (Builder) finished. <agent-response> Done </agent-response>",
|
||||
});
|
||||
});
|
||||
|
||||
it("shows a change request update with its URL, named for the forge", () => {
|
||||
const rows = present([
|
||||
item("pr", {
|
||||
sender: { kind: "change_request_update", url: "https://github.com/acme/app/pull/4" },
|
||||
}),
|
||||
item("mr", {
|
||||
sender: {
|
||||
kind: "change_request_update",
|
||||
url: "https://gitlab.com/acme/app/-/merge_requests/4",
|
||||
},
|
||||
}),
|
||||
]).rows;
|
||||
|
||||
expect(rows).toMatchObject([
|
||||
{
|
||||
icon: "change_request",
|
||||
label: "PR update",
|
||||
preview: "https://github.com/acme/app/pull/4",
|
||||
canEdit: false,
|
||||
},
|
||||
{ icon: "change_request", label: "MR update" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("disables a row that is dispatching or already running a command", () => {
|
||||
const rows = present([item("a", { state: "dispatching" }), item("b"), item("c")], {
|
||||
busy: ["b"],
|
||||
}).rows;
|
||||
|
||||
expect(rows.map((row) => row.disabled)).toEqual([true, true, false]);
|
||||
});
|
||||
|
||||
it("says the queue is paused without naming a cause", () => {
|
||||
expect(present([item("a", { held: true })], { held: true }).notice).toBe(
|
||||
"Queue paused until you send a message",
|
||||
);
|
||||
expect(present([item("a")]).notice).toBeNull();
|
||||
expect(present([], { held: true }).notice).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,82 +0,0 @@
|
||||
import type { PaseoAgentQueueItem } from "@getpaseo/client";
|
||||
import type { TFunction } from "i18next";
|
||||
import type { AgentQueueSnapshot } from "@/agent-queue";
|
||||
|
||||
export interface QueueRowView {
|
||||
id: string;
|
||||
icon: "agent" | "change_request" | null;
|
||||
/** Who or what queued the message. Null for the user's own messages. */
|
||||
label: string | null;
|
||||
preview: string;
|
||||
attachmentLabel: string | null;
|
||||
/** Names the provider the chat moves to when this message is sent. */
|
||||
switchLabel: string | null;
|
||||
canEdit: boolean;
|
||||
disabled: boolean;
|
||||
}
|
||||
|
||||
export interface QueueView {
|
||||
/** In send order: the first row goes next. */
|
||||
rows: QueueRowView[];
|
||||
notice: string | null;
|
||||
}
|
||||
|
||||
interface PresentQueueContext {
|
||||
t: TFunction;
|
||||
/** The current title of an agent this app knows about. */
|
||||
agentTitle: (agentId: string, serverId?: string) => string | null;
|
||||
providerLabel: (provider: string) => string;
|
||||
}
|
||||
|
||||
export function presentQueue(queue: AgentQueueSnapshot, context: PresentQueueContext): QueueView {
|
||||
return {
|
||||
rows: queue.items.map((item) => ({
|
||||
id: item.id,
|
||||
...presentSender(item, context),
|
||||
attachmentLabel: item.attachments?.length
|
||||
? context.t("composer.queue.attachmentCount", { count: item.attachments.length })
|
||||
: null,
|
||||
switchLabel: item.providerSwitch
|
||||
? context.t("composer.queue.switchesTo", {
|
||||
provider: context.providerLabel(item.providerSwitch.provider),
|
||||
})
|
||||
: null,
|
||||
canEdit: item.sender.kind === "user",
|
||||
disabled: item.state === "dispatching" || queue.busy.has(item.id),
|
||||
})),
|
||||
notice: queue.held && queue.items.length > 0 ? context.t("composer.queue.paused") : null,
|
||||
};
|
||||
}
|
||||
|
||||
function presentSender(
|
||||
item: PaseoAgentQueueItem,
|
||||
{ t, agentTitle }: PresentQueueContext,
|
||||
): Pick<QueueRowView, "icon" | "label" | "preview"> {
|
||||
const { sender } = item;
|
||||
if (sender.kind === "user") {
|
||||
return { icon: null, label: null, preview: item.text };
|
||||
}
|
||||
if (sender.kind === "change_request_update") {
|
||||
const isMergeRequest = sender.url.includes("/merge_requests/");
|
||||
return {
|
||||
icon: "change_request",
|
||||
label: t("composer.queue.changeRequestUpdate", { context: isMergeRequest ? "mr" : "" }),
|
||||
preview: sender.url,
|
||||
};
|
||||
}
|
||||
const title = agentTitle(sender.agentId, sender.serverId) || sender.title || sender.agentId;
|
||||
// Messages written for agents open with blank lines and markup. Run them together so the
|
||||
// two preview lines carry text.
|
||||
const preview = item.text.replace(/\s+/g, " ").trim();
|
||||
if (sender.kind === "agent_message") {
|
||||
return { icon: "agent", label: t("composer.queue.sentBy", { title }), preview };
|
||||
}
|
||||
return { icon: "agent", label: t(NOTIFICATION_KEYS[sender.event], { title }), preview };
|
||||
}
|
||||
|
||||
const NOTIFICATION_KEYS = {
|
||||
finished: "composer.queue.agentFinished",
|
||||
errored: "composer.queue.agentErrored",
|
||||
"permission-required": "composer.queue.agentNeedsPermission",
|
||||
closed: "composer.queue.agentClosed",
|
||||
} as const;
|
||||
@@ -3,30 +3,17 @@ import { useSessionStore } from "@/stores/session-store";
|
||||
import {
|
||||
appendSubmittedUserMessage,
|
||||
removeSubmittedUserMessage,
|
||||
type ProviderSwitchItem,
|
||||
type UserMessageItem,
|
||||
} from "@/types/stream";
|
||||
|
||||
function appendUntrackedSubmission(
|
||||
serverId: string,
|
||||
agentId: string,
|
||||
message: UserMessageItem,
|
||||
options?: { providerSwitch?: ProviderSwitchItem },
|
||||
) {
|
||||
function appendUntrackedSubmission(serverId: string, agentId: string, message: UserMessageItem) {
|
||||
const session = useSessionStore.getState().sessions[serverId];
|
||||
if (!session) return;
|
||||
const tail = session.agentStreamTail.get(agentId) ?? [];
|
||||
const head = session.agentStreamHead.get(agentId) ?? [];
|
||||
useSessionStore.getState().setAgentStreamState(
|
||||
serverId,
|
||||
agentId,
|
||||
appendSubmittedUserMessage({
|
||||
tail,
|
||||
head,
|
||||
message,
|
||||
providerSwitch: options?.providerSwitch,
|
||||
}),
|
||||
);
|
||||
useSessionStore
|
||||
.getState()
|
||||
.setAgentStreamState(serverId, agentId, appendSubmittedUserMessage({ tail, head, message }));
|
||||
}
|
||||
|
||||
function removeUntrackedSubmission(
|
||||
@@ -49,8 +36,7 @@ function removeUntrackedSubmission(
|
||||
|
||||
function createUntrackedMessageSubmissionWriter(serverId: string): MessageSubmissionWriter {
|
||||
return {
|
||||
begin: (agentId, message, options) =>
|
||||
appendUntrackedSubmission(serverId, agentId, message, options),
|
||||
begin: (agentId, message) => appendUntrackedSubmission(serverId, agentId, message),
|
||||
accept: () => undefined,
|
||||
reject: (agentId, clientMessageId) => {
|
||||
removeUntrackedSubmission(serverId, agentId, clientMessageId);
|
||||
@@ -68,8 +54,8 @@ export function createMessageSubmissionWriter(serverId: string): MessageSubmissi
|
||||
return createUntrackedMessageSubmissionWriter(serverId);
|
||||
}
|
||||
return {
|
||||
begin: (agentId, message, options) =>
|
||||
useSessionStore.getState().beginAgentMessageSubmission(serverId, agentId, message, options),
|
||||
begin: (agentId, message) =>
|
||||
useSessionStore.getState().beginAgentMessageSubmission(serverId, agentId, message),
|
||||
accept: (agentId, clientMessageId) =>
|
||||
useSessionStore.getState().acceptAgentMessageSubmission(serverId, agentId, clientMessageId),
|
||||
reject: (agentId, clientMessageId) =>
|
||||
|
||||
@@ -104,71 +104,41 @@ describe("submitAgentInput", () => {
|
||||
expect(clearDraft).toHaveBeenCalledWith("sent");
|
||||
});
|
||||
|
||||
function queueingComposer(queueMessage: () => Promise<void>) {
|
||||
const composer = {
|
||||
text: " queued message ",
|
||||
attachments: [{ id: "img-1" }],
|
||||
error: null as string | null,
|
||||
draft: "active",
|
||||
isProcessing: false,
|
||||
};
|
||||
const sent: string[] = [];
|
||||
const submit = () =>
|
||||
it("queues while the agent is running and clears the composer immediately", async () => {
|
||||
const queueMessage = vi.fn();
|
||||
const submitMessage = vi.fn();
|
||||
const clearDraft = vi.fn();
|
||||
const setUserInput = vi.fn();
|
||||
const setAttachments = vi.fn();
|
||||
const setSendError = vi.fn();
|
||||
const setIsProcessing = vi.fn();
|
||||
|
||||
await expect(
|
||||
submitAgentInput({
|
||||
message: composer.text,
|
||||
attachments: composer.attachments,
|
||||
message: " queued message ",
|
||||
attachments: [{ id: "img-1" }],
|
||||
isAgentRunning: true,
|
||||
canSubmit: true,
|
||||
queueMessage,
|
||||
submitMessage: async ({ message }) => {
|
||||
sent.push(message);
|
||||
},
|
||||
clearDraft: (lifecycle) => {
|
||||
composer.draft = lifecycle;
|
||||
},
|
||||
setUserInput: (text) => {
|
||||
composer.text = text;
|
||||
},
|
||||
setAttachments: (attachments) => {
|
||||
composer.attachments = attachments;
|
||||
},
|
||||
setSendError: (message) => {
|
||||
composer.error = message;
|
||||
},
|
||||
setIsProcessing: (isProcessing) => {
|
||||
composer.isProcessing = isProcessing;
|
||||
},
|
||||
});
|
||||
return { composer, sent, submit };
|
||||
}
|
||||
submitMessage,
|
||||
clearDraft,
|
||||
setUserInput,
|
||||
setAttachments,
|
||||
setSendError,
|
||||
setIsProcessing,
|
||||
}),
|
||||
).resolves.toBe("queued");
|
||||
|
||||
it("queues while the agent is running and stays busy until the host accepts", async () => {
|
||||
const accepted = createDeferredPromise<void>();
|
||||
const { composer, sent, submit } = queueingComposer(() => accepted.promise);
|
||||
|
||||
const result = submit();
|
||||
|
||||
expect(composer).toMatchObject({ text: "", attachments: [], isProcessing: true });
|
||||
accepted.resolve();
|
||||
await expect(result).resolves.toBe("queued");
|
||||
expect(composer).toMatchObject({ draft: "sent", isProcessing: false, error: null });
|
||||
expect(sent).toEqual([]);
|
||||
});
|
||||
|
||||
it("restores the composer when the host does not accept a queued message", async () => {
|
||||
const { composer, submit } = queueingComposer(async () => {
|
||||
throw new Error("Host disconnected");
|
||||
});
|
||||
|
||||
await expect(submit()).resolves.toBe("failed");
|
||||
|
||||
expect(composer).toEqual({
|
||||
text: "queued message",
|
||||
expect(queueMessage).toHaveBeenCalledWith({
|
||||
message: "queued message",
|
||||
attachments: [{ id: "img-1" }],
|
||||
error: "Host disconnected",
|
||||
draft: "active",
|
||||
isProcessing: false,
|
||||
});
|
||||
expect(submitMessage).not.toHaveBeenCalled();
|
||||
expect(setUserInput).toHaveBeenCalledWith("");
|
||||
expect(setAttachments).toHaveBeenCalledWith([]);
|
||||
expect(setSendError).not.toHaveBeenCalled();
|
||||
expect(setIsProcessing).not.toHaveBeenCalled();
|
||||
expect(clearDraft).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("restores the composer when submit fails", async () => {
|
||||
|
||||
@@ -11,8 +11,7 @@ export interface AgentInputSubmitActionInput<TAttachment> {
|
||||
forceSend?: boolean;
|
||||
isAgentRunning: boolean;
|
||||
canSubmit: boolean;
|
||||
/** Resolves once the host has the message in its queue. */
|
||||
queueMessage: (input: { message: string; attachments: TAttachment[] }) => Promise<void>;
|
||||
queueMessage: (input: { message: string; attachments: TAttachment[] }) => void;
|
||||
submitMessage: (input: { message: string; attachments: TAttachment[] }) => Promise<void>;
|
||||
clearDraft: (lifecycle: "sent" | "abandoned") => void;
|
||||
setUserInput: (text: string) => void;
|
||||
@@ -43,7 +42,14 @@ export async function submitAgentInput<TAttachment>(
|
||||
return "noop";
|
||||
}
|
||||
|
||||
const shouldQueue = input.isAgentRunning && !input.forceSend;
|
||||
if (input.isAgentRunning && !input.forceSend) {
|
||||
input.queueMessage({ message: trimmedMessage, attachments });
|
||||
if (shouldClearOnSubmit) {
|
||||
input.setUserInput("");
|
||||
input.setAttachments([]);
|
||||
}
|
||||
return "queued";
|
||||
}
|
||||
|
||||
// Clear immediately so the submitted timeline row and composer state stay in sync.
|
||||
if (shouldClearOnSubmit) {
|
||||
@@ -54,11 +60,10 @@ export async function submitAgentInput<TAttachment>(
|
||||
input.setIsProcessing(true);
|
||||
|
||||
try {
|
||||
const deliver = shouldQueue ? input.queueMessage : input.submitMessage;
|
||||
await deliver({ message: trimmedMessage, attachments });
|
||||
await input.submitMessage({ message: trimmedMessage, attachments });
|
||||
input.clearDraft("sent");
|
||||
input.setIsProcessing(false);
|
||||
return shouldQueue ? "queued" : "submitted";
|
||||
return "submitted";
|
||||
} catch (error) {
|
||||
input.onSubmitError?.(error);
|
||||
if (shouldClearOnSubmit) {
|
||||
|
||||
@@ -293,16 +293,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,
|
||||
@@ -313,7 +303,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;
|
||||
|
||||
@@ -6,13 +6,9 @@ import { createProviderSnapshotCache, type ProviderSnapshotCache } from "./provi
|
||||
|
||||
const SNAPSHOT_KEY_PREFIX = "@paseo/provider-snapshot/v2:";
|
||||
const SNAPSHOT_INDEX_KEY = "@paseo/provider-snapshot-index/v2";
|
||||
const STORED_INDEX_KEY = "@paseo/provider-snapshot-index/v3";
|
||||
function createStorage(maxSnapshotBytes = Number.POSITIVE_INFINITY) {
|
||||
const values = new Map<string, string>();
|
||||
const stats = { getAllKeysCalls: 0, snapshotsRead: [] as string[] };
|
||||
function recordRead(key: string) {
|
||||
if (key.startsWith(SNAPSHOT_KEY_PREFIX)) stats.snapshotsRead.push(key);
|
||||
}
|
||||
const stats = { getAllKeysCalls: 0 };
|
||||
type Operation = "setItem" | "removeItem" | "multiRemove";
|
||||
let failure: { operation: Operation; timing: "before" | "after"; key?: string } | null = null;
|
||||
|
||||
@@ -35,7 +31,6 @@ function createStorage(maxSnapshotBytes = Number.POSITIVE_INFINITY) {
|
||||
failure = { operation, timing, key };
|
||||
},
|
||||
async getItem(key: string) {
|
||||
recordRead(key);
|
||||
return values.get(key) ?? null;
|
||||
},
|
||||
async setItem(key: string, value: string) {
|
||||
@@ -66,7 +61,6 @@ function createStorage(maxSnapshotBytes = Number.POSITIVE_INFINITY) {
|
||||
return [...values.keys()];
|
||||
},
|
||||
async multiGet(keys: readonly string[]) {
|
||||
keys.forEach(recordRead);
|
||||
return keys.map((key) => [key, values.get(key) ?? null] as const);
|
||||
},
|
||||
async multiRemove(keys: readonly string[]) {
|
||||
@@ -391,62 +385,6 @@ describe("provider snapshot cache", () => {
|
||||
expect(storage.stats.getAllKeysCalls).toBe(1);
|
||||
});
|
||||
|
||||
it("reads only the requested snapshot after a restart and still enforces the budget", async () => {
|
||||
const storage = createStorage();
|
||||
const cache = createProviderSnapshotCache(storage);
|
||||
for (const [day, label] of ["one", "two", "three"].entries()) {
|
||||
await writeSnapshot(cache, {
|
||||
cwd: `/${label}`,
|
||||
label,
|
||||
generatedAt: `2026-08-0${day + 1}T00:00:00.000Z`,
|
||||
});
|
||||
}
|
||||
const maxBytes = snapshotBytes(storage.values);
|
||||
storage.stats.snapshotsRead.length = 0;
|
||||
|
||||
const restarted = createProviderSnapshotCache(storage, { maxBytes });
|
||||
await expect(restarted.read("server-1", "/two")).resolves.toMatchObject({ hash: "two" });
|
||||
|
||||
expect(storage.stats.snapshotsRead).toEqual([
|
||||
`${SNAPSHOT_KEY_PREFIX}["server-1","cwd","/two"]`,
|
||||
`${SNAPSHOT_KEY_PREFIX}["server-1","hash","two"]`,
|
||||
]);
|
||||
await writeSnapshot(restarted, {
|
||||
cwd: "/four",
|
||||
label: "four",
|
||||
generatedAt: "2026-08-04T00:00:00.000Z",
|
||||
});
|
||||
await expect(restarted.read("server-1", "/one")).resolves.toBeNull();
|
||||
await expect(restarted.read("server-1", "/four")).resolves.not.toBeNull();
|
||||
expect(snapshotBytes(storage.values)).toBeLessThanOrEqual(maxBytes);
|
||||
expectConsistentSnapshots(storage.values);
|
||||
});
|
||||
|
||||
it("counts snapshots that another cache instance stored after a restart", async () => {
|
||||
const storage = createStorage();
|
||||
const first = createProviderSnapshotCache(storage);
|
||||
const second = createProviderSnapshotCache(storage);
|
||||
await second.read("server-1", "/none");
|
||||
await writeSnapshot(first, {
|
||||
cwd: "/first",
|
||||
label: "first",
|
||||
generatedAt: "2026-08-01T00:00:00.000Z",
|
||||
});
|
||||
await writeSnapshot(second, {
|
||||
cwd: "/second",
|
||||
label: "second",
|
||||
generatedAt: "2026-08-02T00:00:00.000Z",
|
||||
});
|
||||
const maxBytes = snapshotBytes(storage.values) - 1;
|
||||
|
||||
const restarted = createProviderSnapshotCache(storage, { maxBytes });
|
||||
|
||||
await expect(restarted.read("server-1", "/second")).resolves.toMatchObject({ hash: "second" });
|
||||
await expect(restarted.read("server-1", "/first")).resolves.toBeNull();
|
||||
expect(snapshotBytes(storage.values)).toBeLessThanOrEqual(maxBytes);
|
||||
expectConsistentSnapshots(storage.values);
|
||||
});
|
||||
|
||||
it("replaces an indexed snapshot without counting both versions", async () => {
|
||||
const storage = createStorage();
|
||||
const maxBytes = 1_000;
|
||||
@@ -621,13 +559,6 @@ describe("provider snapshot cache", () => {
|
||||
entries: [{ key: `${SNAPSHOT_KEY_PREFIX}phantom`, bytes: 999_999, writtenAt: "bad" }],
|
||||
}),
|
||||
);
|
||||
storage.values.set(
|
||||
STORED_INDEX_KEY,
|
||||
JSON.stringify({
|
||||
version: 3,
|
||||
entries: [{ key: `${SNAPSHOT_KEY_PREFIX}phantom`, bytes: 999_999, writtenAt: "bad" }],
|
||||
}),
|
||||
);
|
||||
|
||||
const restarted = createProviderSnapshotCache(storage, { maxBytes });
|
||||
await writeSnapshot(restarted, {
|
||||
|
||||
@@ -15,8 +15,7 @@ type SnapshotPayload = GetProvidersSnapshotResponseMessage["payload"];
|
||||
|
||||
const CACHE_VERSION = 2;
|
||||
const CACHE_KEY_PREFIX = "@paseo/provider-snapshot/v2";
|
||||
const CACHE_INDEX_VERSION = 3;
|
||||
const CACHE_INDEX_KEY = "@paseo/provider-snapshot-index/v3";
|
||||
const CACHE_INDEX_KEY = "@paseo/provider-snapshot-index/v2";
|
||||
const DEFAULT_MAX_CACHE_BYTES = 4 * 1024 * 1024;
|
||||
|
||||
interface ProviderSnapshotStorage {
|
||||
@@ -44,22 +43,8 @@ interface ProviderSnapshotIndexEntry {
|
||||
key: string;
|
||||
bytes: number;
|
||||
writtenAt: string;
|
||||
// A directory association names the body it depends on.
|
||||
body?: string;
|
||||
}
|
||||
|
||||
const ProviderSnapshotIndexSchema = z.object({
|
||||
version: z.literal(CACHE_INDEX_VERSION),
|
||||
entries: z.array(
|
||||
z.object({
|
||||
key: z.string(),
|
||||
bytes: z.number(),
|
||||
writtenAt: z.string(),
|
||||
body: z.string().optional(),
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
const StoredProviderSnapshotSchema: z.ZodType<StoredProviderSnapshot> = z.strictObject({
|
||||
version: z.literal(CACHE_VERSION),
|
||||
hash: z.string(),
|
||||
@@ -124,26 +109,14 @@ function decodeCacheKey(key: string) {
|
||||
return CacheKeySchema.parse(JSON.parse(key.slice(CACHE_KEY_PREFIX.length + 1)));
|
||||
}
|
||||
|
||||
// Timestamps and keys are machine strings: code-unit order is the intended order, and it spares
|
||||
// a collator call per comparison.
|
||||
function oldestFirst(left: ProviderSnapshotIndexEntry, right: ProviderSnapshotIndexEntry): number {
|
||||
if (left.writtenAt !== right.writtenAt) return left.writtenAt < right.writtenAt ? -1 : 1;
|
||||
const writtenAtOrder = left.writtenAt.localeCompare(right.writtenAt);
|
||||
if (writtenAtOrder !== 0) return writtenAtOrder;
|
||||
// References must be evicted before equally recent bodies, regardless of key encoding.
|
||||
const leftIsReference = left.body !== undefined;
|
||||
if (leftIsReference !== (right.body !== undefined)) return leftIsReference ? -1 : 1;
|
||||
if (left.key === right.key) return 0;
|
||||
return left.key < right.key ? -1 : 1;
|
||||
}
|
||||
|
||||
function parseStoredIndex(value: string | null): ProviderSnapshotIndexEntry[] {
|
||||
if (value === null) return [];
|
||||
try {
|
||||
const result = ProviderSnapshotIndexSchema.safeParse(JSON.parse(value));
|
||||
return result.success ? result.data.entries : [];
|
||||
} catch (error) {
|
||||
if (!(error instanceof SyntaxError)) throw error;
|
||||
return [];
|
||||
}
|
||||
const leftKind = decodeCacheKey(left.key)[1];
|
||||
const rightKind = decodeCacheKey(right.key)[1];
|
||||
if (leftKind !== rightKind) return leftKind === "cwd" ? -1 : 1;
|
||||
return left.key.localeCompare(right.key);
|
||||
}
|
||||
|
||||
function parseStoredProviderSnapshot(key: string, value: string): StoredProviderSnapshot | null {
|
||||
@@ -162,23 +135,9 @@ export function createProviderSnapshotCache(
|
||||
): ProviderSnapshotCache {
|
||||
const maxBytes = options.maxBytes ?? DEFAULT_MAX_CACHE_BYTES;
|
||||
let index: ProviderSnapshotIndexEntry[] | null = null;
|
||||
// The index value last read from or written to storage.
|
||||
let storedIndex: string | null = null;
|
||||
let operationQueue = Promise.resolve();
|
||||
const bodies = new Map<string, CachedProviderSnapshot>();
|
||||
|
||||
// The stored index spares a restart from reading every snapshot to learn its size and age.
|
||||
// Storage keys stay the authority on what exists: an indexed key that is gone is dropped, and
|
||||
// a stored key the index does not list is read and measured here.
|
||||
async function commitIndex(entries: ProviderSnapshotIndexEntry[]): Promise<void> {
|
||||
const serialized = JSON.stringify({ version: CACHE_INDEX_VERSION, entries });
|
||||
if (serialized !== storedIndex) {
|
||||
await storage.setItem(CACHE_INDEX_KEY, serialized);
|
||||
storedIndex = serialized;
|
||||
}
|
||||
index = entries;
|
||||
}
|
||||
|
||||
async function reconcileCache(): Promise<void> {
|
||||
const allKeys = await storage.getAllKeys();
|
||||
// COMPAT(providerSnapshotCache): added in v0.7.2, remove legacy cleanup after 2027-03-06.
|
||||
@@ -186,17 +145,14 @@ export function createProviderSnapshotCache(
|
||||
(key) =>
|
||||
key.startsWith("@paseo/provider-snapshot/v1:") ||
|
||||
key === "@paseo/provider-snapshot-index/v1" ||
|
||||
key === "@paseo/provider-snapshot-index/v2",
|
||||
key === CACHE_INDEX_KEY,
|
||||
);
|
||||
if (legacyKeys.length) await storage.multiRemove(legacyKeys);
|
||||
const keys = allKeys.filter((key) => key.startsWith(`${CACHE_KEY_PREFIX}:`));
|
||||
storedIndex = allKeys.includes(CACHE_INDEX_KEY) ? await storage.getItem(CACHE_INDEX_KEY) : null;
|
||||
const storedKeys = new Set(keys);
|
||||
const entries = parseStoredIndex(storedIndex).filter((entry) => storedKeys.has(entry.key));
|
||||
const indexedKeys = new Set(entries.map((entry) => entry.key));
|
||||
const unindexedKeys = keys.filter((key) => !indexedKeys.has(key));
|
||||
const values = unindexedKeys.length > 0 ? await storage.multiGet(unindexedKeys) : [];
|
||||
const values = await storage.multiGet(keys);
|
||||
const keysToRemove: string[] = [];
|
||||
const entries: ProviderSnapshotIndexEntry[] = [];
|
||||
const references: Array<{ key: string; body: string; writtenAt: string }> = [];
|
||||
for (const [key, value] of values) {
|
||||
if (value === null) continue;
|
||||
try {
|
||||
@@ -206,12 +162,13 @@ export function createProviderSnapshotCache(
|
||||
continue;
|
||||
}
|
||||
const [serverId, kind] = decodeCacheKey(key);
|
||||
entries.push({
|
||||
key,
|
||||
bytes: storedBytes(key, value),
|
||||
writtenAt: stored.generatedAt,
|
||||
...(kind === "cwd" ? { body: bodyKey(serverId, stored.hash) } : {}),
|
||||
});
|
||||
entries.push({ key, bytes: storedBytes(key, value), writtenAt: stored.generatedAt });
|
||||
if (kind === "cwd")
|
||||
references.push({
|
||||
key,
|
||||
body: bodyKey(serverId, stored.hash),
|
||||
writtenAt: stored.generatedAt,
|
||||
});
|
||||
} catch (error) {
|
||||
if (
|
||||
!(error instanceof SyntaxError) &&
|
||||
@@ -224,8 +181,7 @@ export function createProviderSnapshotCache(
|
||||
}
|
||||
|
||||
// Reconstruct the dependency ordering before applying a possibly smaller budget.
|
||||
for (const reference of entries) {
|
||||
if (reference.body === undefined) continue;
|
||||
for (const reference of references) {
|
||||
const body = entries.find((entry) => entry.key === reference.body);
|
||||
if (!body) keysToRemove.push(reference.key);
|
||||
else if (body.writtenAt < reference.writtenAt) body.writtenAt = reference.writtenAt;
|
||||
@@ -244,7 +200,7 @@ export function createProviderSnapshotCache(
|
||||
for (const removedKey of keysToRemove) bodies.delete(removedKey);
|
||||
await storage.multiRemove(keysToRemove);
|
||||
}
|
||||
await commitIndex(retainedEntries);
|
||||
index = retainedEntries;
|
||||
}
|
||||
|
||||
async function ensureCacheIndex(): Promise<ProviderSnapshotIndexEntry[]> {
|
||||
@@ -279,7 +235,7 @@ export function createProviderSnapshotCache(
|
||||
value,
|
||||
};
|
||||
}
|
||||
const incoming = { ...prepare(key, input), body: requiredBody?.key };
|
||||
const incoming = prepare(key, input);
|
||||
// The index is committed last: membership proves a body was stored. Reusing it
|
||||
// needs only its byte count, not another parse, expansion, or storage write.
|
||||
const body = requiredBody
|
||||
@@ -309,27 +265,29 @@ export function createProviderSnapshotCache(
|
||||
const keysToRemove = [...replacedKeys].filter(
|
||||
(replaced) => !admitted.some((entry) => entry.key === replaced),
|
||||
);
|
||||
if (projectedBytes > maxBytes) {
|
||||
for (const candidate of [...retainedEntries].sort(oldestFirst)) {
|
||||
if (projectedBytes <= maxBytes) break;
|
||||
projectedBytes -= candidate.bytes;
|
||||
keysToRemove.push(candidate.key);
|
||||
}
|
||||
for (const candidate of [...retainedEntries].sort(oldestFirst)) {
|
||||
if (projectedBytes <= maxBytes) break;
|
||||
projectedBytes -= candidate.bytes;
|
||||
keysToRemove.push(candidate.key);
|
||||
}
|
||||
const removedKeys = new Set(keysToRemove);
|
||||
if (keysToRemove.length > 0) {
|
||||
for (const removedKey of keysToRemove) bodies.delete(removedKey);
|
||||
await storage.multiRemove(keysToRemove);
|
||||
}
|
||||
// Body, then reference, then index. A failed write can leave a reusable
|
||||
// Body, then reference, then in-memory index. A failed write can leave a reusable
|
||||
// orphan body; reconciliation never retains a reference without its body.
|
||||
for (const entry of admitted) {
|
||||
if (entry.value !== undefined) await storage.setItem(entry.key, entry.value);
|
||||
}
|
||||
await commitIndex([
|
||||
index = [
|
||||
...retainedEntries.filter((entry) => !removedKeys.has(entry.key)),
|
||||
...admitted.map(({ value: _value, ...entry }) => entry),
|
||||
]);
|
||||
...admitted.map(({ key: recordKey, bytes, writtenAt }) => ({
|
||||
key: recordKey,
|
||||
bytes,
|
||||
writtenAt,
|
||||
})),
|
||||
];
|
||||
}
|
||||
|
||||
async function readRecord(key: string): Promise<StoredProviderSnapshot | null> {
|
||||
@@ -344,7 +302,7 @@ export function createProviderSnapshotCache(
|
||||
if (!(error instanceof SyntaxError) && !(error instanceof RangeError)) throw error;
|
||||
bodies.delete(key);
|
||||
await storage.removeItem(key);
|
||||
await commitIndex(currentIndex.filter((entry) => entry.key !== key));
|
||||
index = currentIndex.filter((entry) => entry.key !== key);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,7 +65,7 @@ const nativeRequire = createRequire(require.resolve("react-native/package.json")
|
||||
const { AbortController: NativeAbortController }: { AbortController: typeof AbortController } =
|
||||
nativeRequire("abort-controller/dist/abort-controller");
|
||||
|
||||
function createStorage(onWrite: (key: string) => void = () => {}) {
|
||||
function createStorage(onWrite: () => void = () => {}) {
|
||||
const values = new Map<string, string>();
|
||||
return {
|
||||
async getItem(key: string) {
|
||||
@@ -73,7 +73,7 @@ function createStorage(onWrite: (key: string) => void = () => {}) {
|
||||
},
|
||||
async setItem(key: string, value: string) {
|
||||
values.set(key, value);
|
||||
onWrite(key);
|
||||
onWrite();
|
||||
},
|
||||
async removeItem(key: string) {
|
||||
values.delete(key);
|
||||
@@ -164,9 +164,7 @@ describe.each([
|
||||
async ({ abortOnWrite, hasBody, hasReference }) => {
|
||||
const controller = new Controller();
|
||||
let writes = 0;
|
||||
const storage = createStorage((key) => {
|
||||
// The boundaries are the stored snapshots, not the cache's own index of them.
|
||||
if (!key.startsWith("@paseo/provider-snapshot/")) return;
|
||||
const storage = createStorage(() => {
|
||||
writes += 1;
|
||||
if (writes === abortOnWrite) controller.abort();
|
||||
});
|
||||
|
||||
@@ -5,10 +5,23 @@ import invariant from "tiny-invariant";
|
||||
import { BrowserPane } from "@/desktop/browser/pane";
|
||||
import { usePaneContext, usePaneFocus } from "@/panels/pane-context";
|
||||
import { definePanel, type PanelDescriptor, type PanelIconProps } from "@/panels/panel-registry";
|
||||
import { browserTabLabel } from "@/panels/tab-labels";
|
||||
import { useBrowserStore } from "@/desktop/browser/store";
|
||||
import { useWorkspaceDirectory } from "@/stores/session-store-hooks";
|
||||
|
||||
function getBrowserLabel(input: { title: string; url: string }): string {
|
||||
const title = input.title.trim();
|
||||
if (title) {
|
||||
return title;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = new URL(input.url);
|
||||
return parsed.hostname || input.url;
|
||||
} catch {
|
||||
return input.url;
|
||||
}
|
||||
}
|
||||
|
||||
function createBrowserTabIcon(faviconUrl: string | null) {
|
||||
return function BrowserTabIcon({ size, color }: PanelIconProps) {
|
||||
const source = useMemo(() => (faviconUrl ? { uri: faviconUrl } : undefined), []);
|
||||
@@ -29,7 +42,7 @@ function useBrowserPanelDescriptor(target: {
|
||||
const browser = useBrowserStore((state) => state.browsersById[target.browserId] ?? null);
|
||||
const url = browser?.url ?? "https://example.com";
|
||||
const icon = createBrowserTabIcon(browser?.faviconUrl ?? null);
|
||||
const label = browserTabLabel({ title: browser?.title ?? "", url });
|
||||
const label = getBrowserLabel({ title: browser?.title ?? "", url });
|
||||
|
||||
return {
|
||||
label,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user