Compare commits

..
Author SHA1 Message Date
Mohamed Boudra 623eb3685f fix(app): treat an agent of a removed workspace as archived
A workspace archive can finish while one of its agents keeps a row
without an archive timestamp. The timeline owner now also counts an
agent as archived when the hydrated workspace list lacks its workspace,
so its hidden transcript is released and its subscription dropped.
2026-11-26 02:43:15 +01:00
Mohamed Boudra 91be92fa69 fix(app): release archived chat timelines once nobody shows them
Archiving an agent or its workspace removed it from the active list but left its
transcript in the session store until reload, and so did opening an archived chat
from History and leaving it.

The viewed-timeline owner now owns transcript lifetime: an active agent's
transcript stays resident while hidden, so switching tabs needs no fetch; an
archived agent's transcript stays only while its chat is shown. Late history
pages, live events, and cache reads for a released chat are dropped, and the
chat leaves the opened chats so showing it again catches up afresh. Active-list
reconciliation still keeps the transcript, preserving the History invariant
from #4736.

Refs #6477
2026-11-26 02:25:15 +01:00
200 changed files with 4114 additions and 21634 deletions
-1
View File
@@ -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 |
+3 -6
View File
@@ -39,8 +39,8 @@ An unarchived agent may be `closed` without being deleted or archived. Closing r
processes and subscriptions while retaining its Paseo identity, persistence handle, timeline,
workspace, labels, title, usage, attention, timestamps, and parent relationship. Opening or prompting
the agent runs through `ensureAgentLoaded()`, which resumes the durable provider session under the
same Paseo agent ID. Resume does not read provider history when the agent already has a timeline;
see [owned history](timeline-sync.md#owned-history).
same Paseo agent ID. Provider history is not appended again when the canonical timeline is already
primed.
Reload releases the old runtime before resuming its durable session: an idle provider process can
still own an exclusive writer. A close failure retains that runtime for cleanup and blocks the
@@ -256,8 +256,7 @@ lifecycle is separate from public workspace visibility and is not a public creat
Archive is a **soft delete**: the agent record stays on disk with `archivedAt` set, the runtime is closed, and the agent disappears from active lists. Archive is **global** — it lives on the server and propagates to every connected client.
Archive sets `archivedAt`, invokes the provider's native archive hook, and cascades to managed
children. The timeline and the provider children stay, so an archived chat reads them without its
provider; deleting the agent removes them.
children.
`create_agent_request` can opt an agent into `autoArchive`. In that mode the daemon archives the agent after the first terminal turn event (`turn_completed`, `turn_failed`, or `turn_canceled`). When the agent owns an isolated workspace, auto-archive archives that workspace too; the managed worktree is removed when its final workspace reference is gone.
@@ -353,8 +352,6 @@ Workspace status is an aggregate activity signal computed **per `workspaceId`**.
Running provider-native subagents contribute `running` to the workspace owned by their parent agent. Their completed, failed, and canceled states stay in the parent's subagents track.
Only the parent's current runtime makes a provider child running. A child's stored status is the last report about it, and that report can come from provider history or from a runtime an earlier daemon ran, so a stored `running` child does not make the workspace running or keep the parent's runtime alive. It counts again once the live session reports it running. Closing a runtime cancels the children that runtime reported running; children it never reported keep their stored status.
A finished or failed workspace can be marked unread after it has been reviewed. The daemon restores
attention on its newest eligible workspace-root agent, `error` for an agent whose lifecycle is
`error` and `finished` otherwise, without sending a new notification. Opening a workspace restores
+1 -3
View File
@@ -94,7 +94,6 @@ workspace for a directory clears it. The store lives in memory and resets on dae
| `server/directory-sync/` | Daemon-global latest-state sequences for projects, workspaces, and agents |
| `server/workspace-labels/` | Host-local label catalog, assignment mutations, and explicit subscriptions |
| `server/agent/agent-manager.ts` | Agent lifecycle state machine, timeline tracking, subscriber management |
| `server/agent/timeline/` | Owned agent history, provider children, rewind retirements, behind a backend |
| `server/agent/agent-storage.ts` | File-backed JSON persistence at `$PASEO_HOME/agents/` |
| `server/agent/tools/` | Transport-neutral catalog for workspaces, agents, permissions, and automation |
| `server/agent/mcp-server.ts` | Thin MCP adapter that registers the Paseo tool catalog with the MCP SDK |
@@ -403,7 +402,7 @@ initializing → idle ⇄ running
client-side dedup; the default fetch page is 200 items.
- Timeline row `timestamp` values are canonical daemon-owned timestamps. Providers may supply original replay timestamps, but clients must not guess timestamp trust or hide time UI based on local clock heuristics.
- Events stream to connected clients in real time; correctness is backed by authoritative timeline fetches and paged-to-completion catch-up.
- Agent state persists to `$PASEO_HOME/agents/{cwd-with-dashes}/{agent-id}.json`. That storage path is derived from `cwd`, not from workspace id. Timeline rows persist in the daemon database, `$PASEO_HOME/paseo.db`. They are the transcript authority after the first import of provider history. See [owned history](timeline-sync.md#owned-history).
- Agent state persists to `$PASEO_HOME/agents/{cwd-with-dashes}/{agent-id}.json`. Timeline rows are runtime memory; provider history is the durable transcript authority and resumed agents rebuild from it. That storage path is derived from `cwd`, not from workspace id.
## Right-sidebar boundary: directory-backed vs workspace-owned
@@ -479,7 +478,6 @@ Providers that can accept native tool definitions should set `supportsNativePase
```
$PASEO_HOME/
├── agents/{cwd-with-dashes}/{agent-id}.json # Agent record
├── paseo.db # Daemon database (SQLite): agent timelines
├── projects/projects.json # Project registry
├── projects/workspaces.json # Workspace registry
├── projects/icons/ # Custom project icon images
+1 -41
View File
@@ -34,7 +34,7 @@ Workspace archive runs lifecycle teardown from the exact `cwd` but removes only
`worktreeRoot` after its last active reference disappears. Worktree recovery recreates that backing
checkout from `mainRepoRoot`, then restores the relative path from `worktreeRoot` to `cwd`.
Paseo persists most stores as JSON files, and agent timelines in the [daemon database](#daemon-database). JSON data is validated at runtime with Zod schemas. Most JSON stores write atomically (write to temp file, then rename); a few still use plain `writeFile` — see each section. JSON stores have no schema-versioning/migration framework — schemas rely on optional fields with defaults for forward compatibility, with a small amount of inline normalization in `persisted-config.ts` for legacy provider/speech entries.
Paseo uses **file-based JSON persistence** instead of a traditional database. All data is validated at runtime with Zod schemas. Most stores write atomically (write to temp file, then rename); a few still use plain `writeFile` — see each section. There is no schema-versioning/migration framework — schemas rely on optional fields with defaults for forward compatibility, with a small amount of inline normalization in `persisted-config.ts` for legacy provider/speech entries.
All server-side stores live under `$PASEO_HOME` (defaults to `~/.paseo`).
@@ -53,7 +53,6 @@ $PASEO_HOME/
├── daemon-keypair.json # E2EE keypair for relay (mode 0600)
├── paseo.pid # Daemon PID lock file
├── local-credential # Per-run local client credential (mode 0600)
├── paseo.db # Daemon database (SQLite, with -wal and -shm files)
├── daemon.log # Default log file (path configurable)
├── agents/
│ └── {sanitized-cwd}/
@@ -182,45 +181,6 @@ Terminal activity contributes to the workspace status bucket **per `workspaceId`
---
## Daemon database
`$PASEO_HOME/paseo.db` is one SQLite file that the daemon opens at startup with `node:sqlite`
(`packages/server/src/server/database/`). Agent timelines are its only store today. Each store is a
`SchemaModule`: its own table-name prefix and an append-only list of migrations.
- **Migrations.** Startup runs every module's pending migrations in one transaction, so a failed
migration leaves the file as it was. `schema_versions` records each module's version and
`min_reader_version`. Mark a migration `breaking` when an older daemon cannot read the result,
for example a dropped or renamed column. An older daemon then refuses to start with
`DatabaseSchemaTooNewError`. Additive migrations leave older daemons working, and they ignore
modules they do not know. This matters because the app and the daemon update separately, and a
user can run an older daemon on the same `$PASEO_HOME`.
- **Failure.** A file that SQLite cannot open stops the daemon with `DatabaseOpenError`, which
names the path. The daemon does not delete or recreate the file.
- **Access.** The file holds every prompt and reply, so the daemon sets it and its `-wal` and `-shm`
files to mode `0600` on every open. SQLite gives the WAL files it creates the mode of the database
file.
- **Durability.** The database uses WAL with `synchronous = NORMAL`. A power loss can drop the
last commits but does not corrupt the file.
- **Checkpoints.** A checkpoint syncs the file to disk and takes up to 100 ms. SQLite's
auto-checkpoint runs it on the committing thread, which stalled the event loop during streaming.
The daemon turns it off and checkpoints from a worker thread with its own connection. If the
worker exits, the daemon turns auto-checkpoint back on.
- **Transactions.** `write` and `read` callbacks are synchronous, so a transaction never spans an
`await` and transactions never interleave.
- **Node.** `node:sqlite` needs Node 22.16 or later. Node 22 prints an experimental warning once,
when the daemon opens the database.
### Agent timelines
`AgentTimeline` owns each agent's history, and its SQLite backend stores the projected rows, the
source ranges, retirements, the open rewind, and provider children in `timeline_*` tables. The text
of a streamed assistant or reasoning message is stored as one chunk per source event, beside its
row, so a chunk never rewrites the message. An earlier file store rewrote the whole transcript on
every update. See [owned history](timeline-sync.md#owned-history).
---
## 2. Daemon Configuration
**Path:** `$PASEO_HOME/config.json`
+28 -72
View File
@@ -5,9 +5,15 @@ Agent chat delivery has two paths:
1. **Live stream** — `agent_stream` WebSocket messages for immediacy. These may be delta-shaped lifecycle updates.
2. **Authoritative history** — `fetch_agent_timeline_request` for correctness. This always returns full projected timeline items, never lifecycle deltas.
Pagination bounds each read, not total resident history. Streaming overhead must remain
proportional to the retained transcript. Cumulative text snapshots must be released after their
deltas have been consumed.
The daemon retains projected items in memory. Each source event advances the stream sequence,
then replaces the previous tool state or merges into the current text item. Intermediate payloads
are never retained for history or catch-up. Provider history is the durable transcript authority
and rebuilds the projection when an agent resumes.
Pagination bounds each read, not total resident history. Active and idle agents retain their
projected transcript; archive releases it and later history reads rebuild it from the provider.
Streaming overhead must remain proportional to the retained transcript. Cumulative text snapshots
must be released after their deltas have been consumed.
The invariants are:
@@ -26,50 +32,6 @@ bounded item is used for runtime timeline rows and live stream events. Provider
applies the same rule so reopening an agent cannot restore an oversized payload. Fetches apply it
again to assistant and reasoning rows the projection merges from many chunks.
## Owned history
The daemon owns each agent's history in `AgentTimeline`
(`packages/server/src/server/agent/timeline/`): one ordered history per agent, with each provider
child's descriptor and history in a child scope of the same agent. Each source event advances the
stream sequence, then replaces the previous tool state or merges into the current text item.
Intermediate payloads are never retained for history or catch-up.
History is append-only: rewind, import, reload and archive never delete or rewrite a row. Only
deleting the agent, or a provider removing one of its own children, deletes history.
- **Rewind** retires a range of rows. They leave the conversation and stay stored, in the same
epoch. See [Rewind retires rows](#rewind-retires-rows).
- **Provider history** is imported only into an agent that has no history. After that, resume
does not read it. Reload agent and Unarchive require the provider history to start with the
same prompt IDs and text in order. They then append whole new turns, starting at the next
prompt. Existing replies, including partial replies, stay as recorded. If the prompts differ,
for example because the provider stored expanded attachment text, the chat stays unchanged and
Paseo reports a mismatch. A provider child Paseo already holds, listed or retired, is never imported again.
- **Archive and reload** keep the history and the provider children. An archived chat reads them
without its provider. Opening a stored agent that has no provider session to resume starts its
first session on the same history.
- **Delete** removes the agent's history and every child's, retired ones included, before the
agent record. If the history cannot be removed, the request fails and the agent stays listed. The
user can keep using it and delete it again.
`epoch` is the stored history's identity, minted once when the history is created.
`AgentTimeline` serializes every operation of one agent, child scopes included, and keeps its
state in an `AgentTimelineBackend`: the sequence, the rows and retirements, prompt identities, the
open rewind, and the children. The backend contract suite is `agent-timeline.test.ts`, run over
`TIMELINE_CONTRACT_BACKENDS` in `timeline/testing.ts`. The daemon uses the SQLite backend in the
[daemon database](data-model.md#daemon-database). History, retirements, the open rewind, and
provider children survive a daemon restart in the same epoch, so clients keep their cursors. A
closed or archived agent holds no history in memory. Each fetch reads the page from the database
and starts no provider. An internal agent, such as the one that writes a commit message, keeps its
history in a memory backend instead, so it leaves nothing on disk. The memory backend also serves
tests.
An open rewind is stored with the history. Resuming an agent whose history holds one settles it
before the agent takes prompts: a recorded provider cut is committed, and an unknown outcome is
judged from the resumed provider history. When that history proves nothing, the rewind stays open
and the agent refuses prompts with the unknown-outcome error.
## Presence is not delivery
Client heartbeat reports presence:
@@ -206,7 +168,7 @@ or retry backoff. This cannot keep a mobile socket alive after the operating sys
bookkeeping without replacing timeline arrays, preserving an upward-scrolled viewport.
- When the page overlaps or is adjacent to the local end cursor, only projected items newer than
that cursor are applied. Already-covered rows are not replayed.
- A true middle gap or epoch change atomically replaces stale canonical history with the
- A true middle gap, epoch change, or rewind atomically replaces stale canonical history with the
latest tail. The replacement reconciles positioned live rows beyond its coverage and unresolved
local submissions; it never retains two discontiguous canonical ranges.
@@ -219,24 +181,6 @@ history replay. The pending approval UI can hide that tool from presentation, bu
must retain its position. Creating a new history card on rejection places it after the prompt that
rejected it; changing steer-event ordering would also put new assistant output before that prompt.
## Rewind retires rows
A conversation rewind commits a retirement `{ seq, retireFromSeq }`: active rows anchored in
`[retireFromSeq, seq)` leave the conversation, and `seq` is the retirement's own position in the
sequence. The provider children spawned by retired tool calls, and their descendants, are retired
in the same commit. They leave the listing, keep their history, and drop late provider events.
Clients learn of a retirement live through `agent.timeline.rewind`, and on pages through
`retirements`, which lists the retirements whose `seq` lies inside the page's span. The client
drops the rows it holds in that range; rows without a timeline position are unechoed local sends
and stay. Retired ranges and the retirement's `seq` count as covered, so forward cursors advance
through them. Tail, before and prompt-jump pages are served from active rows, so one served before
a retirement the client already applied is stale and is refetched (`viewed-timeline-sync.ts`).
Clients without `timeline_rewind_operations` cannot drop retired rows. For them the session derives
a wire epoch that changes with each retirement, so they take the destructive replacement they
always took on rewind. The shim is tagged `COMPAT(timelineRewindOperations)`.
## Provider child history
Child transcripts use the same projected-page reconciliation as the main conversation. The client
@@ -258,10 +202,23 @@ owner wraps cached preparation, network catch-up, accepted timeline application,
behind one interface. React supplies transport and projection operations without selecting a cache
path or issuing a separate persistence notification.
Active-agent list reconciliation does not own transcript lifetime. An archived agent's fresh
history response can arrive before the active-list response that omits it. Clearing history there
would discard accepted rows while the viewed owner still considers them synchronized. Entity
deletion clears the transcript; list membership changes do not.
The viewed-timeline owner also owns how long a transcript stays in memory. An active agent's
transcript stays resident while its chat is hidden, so switching back to it needs no fetch. An
archived agent's transcript stays resident only while its chat is shown, for example when it is
opened from History. When an agent is archived, or the active list drops it because its workspace
was archived, the owner releases the transcript unless the chat is shown. It also releases the
transcript when the chat stops being shown. A released chat leaves the opened chats. When it is
shown again, it reads the replica cache and catches up again. A history page, live event, or cache
read that arrives after the release is dropped.
The active-list reconciliation does not release transcripts itself. An archived agent's fresh
history response can arrive before the active-list response that omits it, while the chat is
open in History. Clearing history there would discard rows the user is reading.
An agent counts as archived when the active list omits it, when its row has an archive timestamp,
or when the workspace list omits its workspace. The workspace check matters because a workspace
archive can complete while one of its agents keeps a row with no archive timestamp. Until a list
first hydrates, it marks no agent as archived. Deleting the agent clears the transcript.
Removing the host from the registry is the destructive boundary: it stops the runtime and clears the
session and host-scoped setup state together.
@@ -401,7 +358,7 @@ the draft-create handoff is the one boundary that also permits the legacy canoni
arrived first. Generic reducers and consumers do not reimplement message identity matching.
Ordinary bootstrap, same-epoch reset, and catch-up replacement preserve unmatched locally submitted
rows because a provider may never echo them. A known epoch change replaces history and
rows because a provider may never echo them. A known epoch change or rewind replaces history and
drops acknowledged local rows omitted by the new canonical epoch; every transaction not yet
acknowledged by the provider, and no other local row, crosses that destructive boundary. A cold
reset without an existing epoch is destructive because the client has no continuity anchor.
@@ -417,7 +374,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
View File
@@ -1 +1 @@
sha256-IAhKhkolW4xvFvMaAEFdhYvPAhTm2azsqbGMKCKL3q0=
sha256-TAVzJzziWDAapQkG4TLkLzOlodkdFNKSl3y/Tm9HB28=
+1 -20
View File
@@ -45,9 +45,6 @@
"react-dom": "19.2.3",
"typescript": "^5.9.3",
"ws": "^8.20.0"
},
"engines": {
"node": ">=22.16.0"
}
},
"node_modules/@0no-co/graphql.web": {
@@ -39722,9 +39719,6 @@
"typescript": "^5.2.2",
"vitest": "^4.1.6",
"zx": "^8.8.5"
},
"engines": {
"node": ">=22.16.0"
}
},
"packages/cli/node_modules/@vitest/expect": {
@@ -40652,7 +40646,7 @@
"@playwright/test": "^1.56.1",
"@types/express": "^4.17.20",
"@types/markdown-it": "^14.2.0",
"@types/node": "^22.16.0",
"@types/node": "^20.9.0",
"@types/qrcode": "^1.5.6",
"@types/uuid": "^9.0.7",
"@types/ws": "^8.5.8",
@@ -40660,9 +40654,6 @@
"cross-env": "^10.1.0",
"tsx": "^4.6.0",
"vitest": "^4.1.6"
},
"engines": {
"node": ">=22.16.0"
}
},
"packages/server/node_modules/@esbuild/aix-ppc64": {
@@ -41110,16 +41101,6 @@
"@types/mdurl": "^2"
}
},
"packages/server/node_modules/@types/node": {
"version": "22.20.5",
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz",
"integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~6.21.0"
}
},
"packages/server/node_modules/@vitest/expect": {
"version": "4.1.6",
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.6.tgz",
-3
View File
@@ -169,8 +169,5 @@
"tiny-async-pool": {
"semver@^5": "5.7.2"
}
},
"engines": {
"node": ">=22.16.0"
}
}
@@ -13,13 +13,6 @@ import {
import { expectNearBottom, scrollChatAwayFromBottom } from "../support/helpers/agent-bottom-anchor";
import { holdRewindCompletion } from "../support/helpers/agent-timeline-gate";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import { userScrollsTimelineToHistoryStart } from "../support/helpers/timeline-pagination";
import {
closeWorkspaceAgentTab,
fetchAgentArchivedAt,
primeAdditionalPage,
resetSeededPageState,
} from "../support/helpers/archive-tab";
async function completeSubmittedTurn(
page: Page,
@@ -55,102 +48,26 @@ async function expectTurnCompletesNormally(
await expectAgentIdle(page);
}
async function openAgentOnAnotherClient(
page: Page,
agent: Awaited<ReturnType<typeof seedMockAgentWorkspace>>,
): Promise<void> {
await primeAdditionalPage(page);
await resetSeededPageState(page);
await openAgentRoute(page, agent);
await expectComposerVisible(page);
}
/** The prompts the chat shows, in order, each exactly once. */
async function expectPrompts(page: Page, prompts: string[]): Promise<void> {
const messages = page.getByTestId("user-message");
await expect(messages).toHaveCount(prompts.length);
await expect(messages).toContainText(prompts);
}
async function reloadAgentFromTabMenu(page: Page, agentId: string): Promise<void> {
const tabId = `workspace-tab-agent_${agentId}`;
await page.getByTestId(tabId).filter({ visible: true }).first().click({ button: "right" });
await page.getByTestId(`workspace-tab-context-agent_${agentId}-reload-agent`).click();
}
async function archiveAgentByClosingTab(
page: Page,
agent: Awaited<ReturnType<typeof seedMockAgentWorkspace>>,
): Promise<void> {
await closeWorkspaceAgentTab(page, agent.agentId);
await expect.poll(() => fetchAgentArchivedAt(agent.client, agent.agentId)).not.toBeNull();
}
async function unarchiveAgent(page: Page): Promise<void> {
await page.getByRole("button", { name: "Unarchive", exact: true }).click();
await expect(page.getByText("This agent is archived", { exact: true })).toHaveCount(0, {
timeout: 30_000,
});
}
async function expectToast(page: Page, message: string): Promise<void> {
await expect(page.getByTestId("app-toast-message")).toHaveText(message, { timeout: 30_000 });
}
// The mock provider's resumed session holds no history, so it never matches what Paseo shows.
const UNSYNCED_RELOAD =
"Reloaded agent, but the provider's history doesn't match this chat, so it wasn't synced";
/** The prompts of the whole conversation, after scrolling up through its older pages. */
async function expectConversationPrompts(page: Page, prompts: string[]): Promise<void> {
const messages = page.getByTestId("user-message");
await expect
.poll(async () => {
await userScrollsTimelineToHistoryStart(page);
return await messages.count();
})
.toBe(prompts.length);
await expect(messages).toContainText(prompts);
}
// A row React remounts loses this attribute; one that stays mounted keeps it.
async function markMounted(row: Locator): Promise<void> {
await row.evaluate((element) => element.setAttribute("data-e2e-mounted", "before-rewind"));
}
async function expectStillMounted(row: Locator): Promise<void> {
await expect(row).toHaveAttribute("data-e2e-mounted", "before-rewind");
}
test.describe("Agent message rewind", () => {
test("rewinds a prompt in place on every open client and keeps a human draft", async ({
test("rewinds a submitted prompt without replaying history and preserves a human draft", async ({
page,
}) => {
test.setTimeout(150_000);
test.setTimeout(90_000);
const retainedPrompt = "Keep this completed turn after rewind.";
const rewoundPrompt = "Remove this completed turn after rewind.";
const nextPrompt = "Continue after the rewind.";
const preservedDraft = "Keep this human draft after rewind.";
const agent = await seedMockAgentWorkspace({
repoPrefix: "message-rewind-roundtrip-",
title: "Message rewind roundtrip",
model: "ten-second-stream",
});
const otherClient = await page.context().newPage();
try {
const rewindCompletion = await holdRewindCompletion(page, agent.agentId);
await openAgentRoute(page, agent);
await expectComposerVisible(page);
const retainedMessage = await completeSubmittedTurn(page, agent, retainedPrompt);
await completeSubmittedTurn(page, agent, retainedPrompt);
const userMessage = await completeSubmittedTurn(page, agent, rewoundPrompt);
await test.step("a second client opens the same chat", async () => {
await openAgentOnAnotherClient(otherClient, agent);
await expectPrompts(otherClient, [retainedPrompt, rewoundPrompt]);
});
await markMounted(retainedMessage);
await scrollChatAwayFromBottom(page, {
deltaY: -900,
minDistanceFromBottom: 300,
@@ -159,92 +76,19 @@ test.describe("Agent message rewind", () => {
await blurComposerInput(page);
rewindCompletion.clearTimelineStreamCount();
await test.step("the rewind stays pending until the daemon answers", async () => {
const rewind = rewindConversation(page, userMessage, rewoundPrompt);
await rewindCompletion.waitForDelayedResponse();
await expect(page.getByTestId("rewind-menu-conversation")).toBeDisabled();
expect(rewindCompletion.timelineStreamCount()).toBe(0);
rewindCompletion.release();
await rewind;
});
const rewind = rewindConversation(page, userMessage, rewoundPrompt);
await rewindCompletion.waitForDelayedResponse();
await expect(page.getByTestId("rewind-menu-conversation")).toBeDisabled();
expect(rewindCompletion.timelineStreamCount()).toBe(0);
rewindCompletion.release();
await rewind;
await test.step("the rewound turn leaves without reloading the chat", async () => {
await expectPrompts(page, [retainedPrompt]);
await expectStillMounted(retainedMessage);
expect(rewindCompletion.timelineFetchCount()).toBe(0);
await expectComposerDraft(page, preservedDraft);
await expectComposerNotFocused(page);
await expectNearBottom(page);
await expectPrompts(otherClient, [retainedPrompt]);
});
await test.step("the next prompt appears once on both clients", async () => {
await completeSubmittedTurn(otherClient, agent, nextPrompt);
await expectPrompts(otherClient, [retainedPrompt, nextPrompt]);
await expectPrompts(page, [retainedPrompt, nextPrompt]);
});
await test.step("a reconnecting client loads the rewound conversation", async () => {
await otherClient.reload();
await expectPrompts(otherClient, [retainedPrompt, nextPrompt]);
});
} finally {
await otherClient.close();
await agent.cleanup();
}
});
test("keeps the rewound conversation through Reload agent, archive and unarchive", async ({
page,
}) => {
test.setTimeout(150_000);
const keptPrompt = "Keep this turn through reload and archive.";
const rewoundPrompt = "Rewind this turn before reloading.";
const nextPrompt = "Continue after the rewind, then reload.";
const agent = await seedMockAgentWorkspace({
repoPrefix: "message-rewind-reload-archive-",
title: "Message rewind reload archive",
model: "ten-second-stream",
});
try {
await openAgentRoute(page, agent);
await expectComposerVisible(page);
await completeSubmittedTurn(page, agent, keptPrompt);
const rewound = await completeSubmittedTurn(page, agent, rewoundPrompt);
await rewindConversation(page, rewound, rewoundPrompt);
await expectPrompts(page, [keptPrompt]);
await completeSubmittedTurn(page, agent, nextPrompt);
await expectPrompts(page, [keptPrompt, nextPrompt]);
await test.step("Reload agent keeps the chat and says the provider's history was not synced", async () => {
await reloadAgentFromTabMenu(page, agent.agentId);
await expectToast(page, UNSYNCED_RELOAD);
await expectPrompts(page, [keptPrompt, nextPrompt]);
await expectComposerVisible(page);
});
await test.step("the archived chat shows the rewound conversation", async () => {
await archiveAgentByClosingTab(page, agent);
await openAgentRoute(page, agent);
await expect(page.getByText("This agent is archived", { exact: true })).toBeVisible({
timeout: 30_000,
});
await expectConversationPrompts(page, [keptPrompt, nextPrompt]);
});
await test.step("unarchiving keeps the rewound conversation", async () => {
await unarchiveAgent(page);
await expectToast(page, UNSYNCED_RELOAD);
await expectComposerVisible(page);
await expectConversationPrompts(page, [keptPrompt, nextPrompt]);
});
await test.step("a reconnecting client loads the same conversation", async () => {
await page.reload();
await expectComposerVisible(page);
await expectConversationPrompts(page, [keptPrompt, nextPrompt]);
});
await expect(page.getByTestId("user-message").filter({ hasText: rewoundPrompt })).toHaveCount(
0,
);
await expectComposerDraft(page, preservedDraft);
await expectComposerNotFocused(page);
await expectNearBottom(page);
} finally {
await agent.cleanup();
}
@@ -45,26 +45,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([]);
@@ -89,8 +69,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,509 +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 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 browserSheet = page.getByTestId("agent-controls-model-browser-sheet");
const browserViewport = page.getByTestId("agent-controls-model-browser-viewport");
await expect(browserViewport).toBeVisible({ timeout: 30_000 });
const backButton = browserSheet.getByTestId("sheet-header-back");
if (await backButton.isVisible()) {
await backButton.click();
}
await browserViewport.getByTestId(`model-provider-${DIRECT_PROVIDER.id}`).click();
await browserViewport
.getByTestId(`model-row-${DIRECT_PROVIDER.id}-${DIRECT_PROVIDER.modelId}`)
.click();
await expect(browserViewport).toHaveCount(0, { timeout: 30_000 });
// Dismiss the outer 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);
const switchedMessage = await completeDirectTurn(page, workspace, postSwitchPrompt);
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("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();
}
@@ -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,
};
}
@@ -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. */
@@ -147,16 +139,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;
@@ -166,11 +148,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);
@@ -56,7 +56,6 @@ export function ChatFind({
agentId,
serverId,
epoch,
rewindSeq,
items,
viewportRef,
revealLoadedMessage,
@@ -96,8 +95,8 @@ export function ChatFind({
);
const state = useSyncExternalStore(model.subscribe, model.getSnapshot, model.getSnapshot);
useEffect(() => {
model.updateHistory(epoch, items, rewindSeq);
}, [model, epoch, items, rewindSeq]);
model.updateHistory(epoch, items);
}, [model, epoch, items]);
useEffect(() => () => model.close(), [model]);
useEffect(() => {
if (!active) model.close();
@@ -18,7 +18,7 @@ function message(seq: number, text = "target"): StreamItem {
kind: "assistant_message",
text,
timestamp: new Date(0),
timelineCursor: { epoch: "epoch", seq, anchorSeq: seq },
timelineCursor: { epoch: "epoch", seq },
};
}
@@ -39,7 +39,7 @@ it("loads an older location and searches a response merged across suppressed tas
source.map((item, index) => ({
event: { type: "timeline" as const, provider: "claude" as const, item },
timestamp: new Date(0),
timelineCursor: { epoch: "epoch", seq: index + 1, anchorSeq: index + 1 },
timelineCursor: { epoch: "epoch", seq: index + 1 },
})),
{ source: "canonical" },
);
@@ -55,7 +55,7 @@ it("loads an older location and searches a response merged across suppressed tas
},
async load(_epoch, seq) {
loaded.push(seq);
model.updateHistory("epoch", history, null);
model.updateHistory("epoch", history);
},
async reveal(_id, _query, occurrence) {
revealed.push(occurrence);
@@ -64,7 +64,7 @@ it("loads an older location and searches a response merged across suppressed tas
clear() {},
});
try {
model.updateHistory("epoch", [], null);
model.updateHistory("epoch", []);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
@@ -99,7 +99,7 @@ it("skips a source-only candidate and highlights a displayed match", async () =>
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)], null);
model.updateHistory("epoch", [message(1), message(2)]);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().selectedItemId).toBe("row-2");
@@ -129,7 +129,7 @@ it("ignores replies after closing and does not navigate", async () => {
},
clear() {},
});
model.updateHistory("epoch", [message(1)], null);
model.updateHistory("epoch", [message(1)]);
model.open();
model.setQuery("target");
await expect.poll(() => calls).toEqual(["search"]);
@@ -155,7 +155,7 @@ it("retains a failed search for retry and distinguishes failure from zero matche
};
const model = new ChatFindModel(operations);
try {
model.updateHistory("epoch", [], null);
model.updateHistory("epoch", []);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("error");
@@ -185,7 +185,7 @@ it("reports a failed timeline load as a connection failure", async () => {
clear() {},
});
try {
model.updateHistory("epoch", [], null);
model.updateHistory("epoch", []);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("error");
@@ -207,160 +207,24 @@ it("reports a search result that outlived its epoch as a changed history", async
clear() {},
});
try {
model.updateHistory("epoch", [message(1)], null);
model.updateHistory("epoch", [message(1)]);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
model.updateHistory("epoch-2", [message(1)], null);
model.updateHistory("epoch-2", [message(1)]);
expect(model.getSnapshot()).toMatchObject({ phase: "error", failure: "historyChanged" });
} finally {
model.close();
}
});
it("reports results that a rewind took messages from as a changed history", async () => {
const model = new ChatFindModel({
async search() {
return response([{ seq: 2, role: "assistant" }]);
},
async load() {},
async reveal() {
return { count: 1, occurrence: 0 };
},
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
expect(model.getSnapshot()).toMatchObject({ selectedItemId: "row-2", count: 1 });
// Another client rewinds the turn holding the match; the epoch stays.
model.updateHistory("epoch", [message(1)], 3);
expect(model.getSnapshot()).toMatchObject({
phase: "error",
failure: "historyChanged",
selectedItemId: null,
});
} finally {
model.close();
}
});
it("stops a search still receiving pages when a rewind lands between them", async () => {
let pages = 0;
let releaseSecondPage!: () => void;
const secondPage = new Promise<void>((resolve) => {
releaseSecondPage = resolve;
});
const model = new ChatFindModel({
async search(_query, cursor) {
pages += 1;
if (cursor === undefined)
return { ...response([{ seq: 2, role: "assistant" }]), nextCursor: 2 };
await secondPage;
return response([{ seq: 1, role: "assistant" }]);
},
async load() {},
async reveal() {
return { count: 1, occurrence: 0 };
},
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)], null);
model.open();
model.setQuery("target");
await expect.poll(() => pages).toBe(2);
model.updateHistory("epoch", [message(1)], 3);
releaseSecondPage();
await expect.poll(() => model.getSnapshot().failure).toBe("historyChanged");
expect(model.getSnapshot()).toMatchObject({ phase: "error", selectedItemId: null });
} finally {
model.close();
}
});
it.each([
["Next", "next"],
["Previous", "previous"],
] as const)("reports a rewind after %s as a changed history", async (_label, step) => {
const model = new ChatFindModel({
async search() {
return response([
{ seq: 1, role: "assistant" },
{ seq: 2, role: "assistant" },
]);
},
async load() {},
async reveal() {
return { count: 1, occurrence: 0 };
},
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
model[step]();
await expect.poll(() => model.getSnapshot().selectedItemId).toBe("row-2");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
model.updateHistory("epoch", [message(1)], 3);
expect(model.getSnapshot()).toMatchObject({
phase: "error",
failure: "historyChanged",
selectedItemId: null,
});
} finally {
model.close();
}
});
it("stops a pending Next when a rewind lands before it reveals", async () => {
let reveals = 0;
let revealSecond!: () => void;
const secondReveal = new Promise<void>((resolve) => {
revealSecond = resolve;
});
const model = new ChatFindModel({
async search() {
return response([
{ seq: 1, role: "assistant" },
{ seq: 2, role: "assistant" },
]);
},
async load() {},
async reveal() {
reveals += 1;
if (reveals > 1) await secondReveal;
return { count: 1, occurrence: 0 };
},
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
model.next();
await expect.poll(() => reveals).toBe(2);
model.updateHistory("epoch", [message(1)], 3);
revealSecond();
await expect.poll(() => model.getSnapshot().failure).toBe("historyChanged");
expect(model.getSnapshot()).toMatchObject({ phase: "error", selectedItemId: null });
} finally {
model.close();
}
});
it("can load a search location before the initial chat history has arrived", async () => {
const model = new ChatFindModel({
async search() {
return response([{ seq: 1, role: "assistant" }]);
},
async load() {
model.updateHistory("epoch", [message(1)], null);
model.updateHistory("epoch", [message(1)]);
},
async reveal() {
return { count: 1, occurrence: 0 };
@@ -368,7 +232,7 @@ it("can load a search location before the initial chat history has arrived", asy
clear() {},
});
try {
model.updateHistory(null, [], null);
model.updateHistory(null, []);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
@@ -396,7 +260,7 @@ it("reports the position across the whole chat and corrects it with rendered cou
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)], null);
model.updateHistory("epoch", [message(1), message(2)]);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
@@ -433,7 +297,7 @@ it("counts one match per message from a host that reports no counts", async () =
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)], null);
model.updateHistory("epoch", [message(1), message(2)]);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
@@ -76,10 +76,6 @@ export class ChatFindModel {
private items: StreamItem[] = [];
private epoch: string | null = null;
private resultEpoch: string | null = null;
/** The latest rewind applied to the history. A rewind keeps the epoch and retires messages. */
private rewindSeq: number | null = null;
/** The latest rewind when the current result set's search started; undefined until a search starts. */
private searchedRewindSeq: number | null | undefined = undefined;
private locations: Location[] = [];
private resolved = new Map<Location, Target>();
private current = -1;
@@ -117,7 +113,6 @@ export class ChatFindModel {
this.cancel();
this.locations = [];
this.resultEpoch = null;
this.searchedRewindSeq = undefined;
this.resolved.clear();
this.current = -1;
this.inMessage = { occurrence: 0, count: 0 };
@@ -149,7 +144,6 @@ export class ChatFindModel {
});
}
private async search(signal: AbortSignal) {
this.searchedRewindSeq = this.rewindSeq;
try {
let cursor: number | undefined;
do {
@@ -174,14 +168,15 @@ export class ChatFindModel {
this.fail(error, signal);
}
}
/** `rewindSeq` is the sequence number of the latest rewind applied to this history. */
updateHistory(epoch: string | null, items: StreamItem[], rewindSeq: number | null) {
const replaced = this.resultEpoch !== null && epoch !== null && epoch !== this.resultEpoch;
const rewound = this.searchedRewindSeq !== undefined && rewindSeq !== this.searchedRewindSeq;
if ((replaced || rewound) && this.state.open) {
updateHistory(epoch: string | null, items: StreamItem[]) {
if (
this.resultEpoch !== null &&
epoch !== null &&
epoch !== this.resultEpoch &&
this.state.open
) {
this.fail(new ChatFindFailureError("historyChanged"), this.abort.signal);
}
this.rewindSeq = rewindSeq;
this.epoch = epoch;
this.items = items;
this.historyListeners.forEach((listener) => listener());
@@ -9,8 +9,6 @@ export interface ChatFindProps {
agentId: string;
serverId: string;
epoch: string | null;
/** The sequence number of the latest rewind applied to this history, if any. */
rewindSeq: number | null;
items: StreamItem[];
viewportRef: RefObject<StreamViewportHandle | null>;
revealLoadedMessage(messageId: string): boolean;
@@ -139,7 +139,7 @@ describe("useChatOutline", () => {
kind: "user_message",
text: "live prompt",
timestamp: new Date(seq),
timelineCursor: { epoch: "epoch-1", seq, anchorSeq: seq },
timelineCursor: { epoch: "epoch-1", seq },
});
rerender({ tail: [loadedPrompt(2)] });
await waitFor(() => expect(runtime.listAgentTimelinePrompts).toHaveBeenCalledTimes(2));
@@ -198,7 +198,7 @@ describe("useChatOutline", () => {
kind: "assistant_message",
text: "chunk",
timestamp: new Date(),
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
timelineCursor: { epoch: "epoch-1", seq: 2 },
},
],
timelineEpoch: "epoch-1",
@@ -219,7 +219,7 @@ describe("useChatOutline", () => {
kind: "user_message",
text: "Replaced conversation",
timestamp: new Date(2),
timelineCursor: { epoch: "epoch-2", seq: 1, anchorSeq: 1 },
timelineCursor: { epoch: "epoch-2", seq: 1 },
},
],
timelineEpoch: "epoch-2",
@@ -275,7 +275,7 @@ describe("useChatOutline", () => {
kind: "user_message" as const,
text: "prompt",
timestamp: new Date(1),
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
timelineCursor: { epoch: "epoch-1", seq: 1 },
},
];
const { result, rerender } = renderHook(
@@ -326,7 +326,7 @@ describe("useChatOutline", () => {
kind: "user_message" as const,
text: "prompt",
timestamp: new Date(1),
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
timelineCursor: { epoch: "epoch-1", seq: 1 },
};
const { result, rerender } = renderHook(
({ tail, mountedHistoryMessageIds }) =>
@@ -381,7 +381,7 @@ describe("useChatOutline", () => {
kind: "user_message" as const,
text: "prompt",
timestamp: new Date(2),
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
timelineCursor: { epoch: "epoch-1", seq: 2 },
};
const revealLoadedMessage = vi.fn();
revealLoadedMessage.mockReturnValue(false);
@@ -320,7 +320,7 @@ describe("stream presentation through installed plugins", () => {
const source = harness.source();
const live = source.head[0];
if (live?.kind !== "assistant_message") throw new Error("Expected a live assistant message");
const canonical = { ...live, timelineCursor: { epoch: "epoch-1", seq: 42, anchorSeq: 42 } };
const canonical = { ...live, timelineCursor: { epoch: "epoch-1", seq: 42 } };
const present = createStreamPresentation();
present({ ...presentationOptions, tail: [], head: [live], transform: undefined });
const repointed = rows(
@@ -330,7 +330,7 @@ describe("stream presentation through installed plugins", () => {
{
id: streamed[0]!.id,
text: "Streamed answer",
timelineCursor: { epoch: "epoch-1", seq: 42, anchorSeq: 42 },
timelineCursor: { epoch: "epoch-1", seq: 42 },
},
]);
});
@@ -517,7 +517,7 @@ describe("timeline presentation", () => {
messageId: "provider-message",
clientMessageId: "client-message",
turnId: "turn-1",
timelineCursor: { epoch: "epoch", seq: 12, anchorSeq: 12 },
timelineCursor: { epoch: "epoch", seq: 12 },
});
const presentMessage = () =>
present({
@@ -33,7 +33,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
it("forks a failed assistant turn from its Paseo timeline cursor without a provider message id", () => {
const failedTurn = {
...assistantMessage("assistant-error", 2),
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
timelineCursor: { epoch: "timeline-1", seq: 42 },
};
expect(
@@ -50,7 +50,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
it("includes the provider message id with a supported timeline cursor", () => {
const selected = {
...assistantMessage("assistant-1", 2, "msg-assistant-1"),
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
timelineCursor: { epoch: "timeline-1", seq: 42 },
};
expect(
@@ -68,7 +68,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
it("falls back to the provider message id when timeline cursors are unsupported", () => {
const selected = {
...assistantMessage("assistant-1", 2, "msg-assistant-1"),
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
timelineCursor: { epoch: "timeline-1", seq: 42 },
};
expect(
@@ -116,7 +116,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
it("resolves a fork boundary from the reply a plugin card replaced", () => {
const reply = {
...assistantMessage("assistant-1", 2, "msg-assistant-1"),
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
timelineCursor: { epoch: "timeline-1", seq: 42 },
};
const card: StreamItem = {
kind: "plugin",
@@ -154,7 +154,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
const appended: StreamItem = {
kind: "plugin",
id: "plugin/card-1",
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
timelineCursor: { epoch: "timeline-1", seq: 42 },
timestamp: timestamp(2),
pluginId: "plugin",
pluginItemId: "card-1",
@@ -1,13 +1,7 @@
import { getAssistantReply, type StreamItem } from "@/types/stream";
/** The daemon's timeline cursor; the row's anchor stays in the client. */
interface TimelineBoundaryCursor {
epoch: string;
seq: number;
}
import { getAssistantReply, type StreamItem, type TimelinePosition } from "@/types/stream";
export type AssistantTurnForkBoundary =
| { boundaryCursor: TimelineBoundaryCursor; boundaryMessageId?: string }
| { boundaryCursor: TimelinePosition; boundaryMessageId?: string }
| { boundaryCursor?: undefined; boundaryMessageId: string };
export function resolveAssistantTurnForkBoundary(input: {
@@ -21,7 +15,7 @@ export function resolveAssistantTurnForkBoundary(input: {
}
if (input.supportsTimelineCursor && reply.timelineCursor) {
return {
boundaryCursor: { epoch: reply.timelineCursor.epoch, seq: reply.timelineCursor.seq },
boundaryCursor: reply.timelineCursor,
...(reply.messageId ? { boundaryMessageId: reply.messageId } : {}),
};
}
@@ -139,7 +139,7 @@ describe("collapseTurns", () => {
it("stands at its host's timeline position, taking a new row when that position lands", () => {
const live = collapse([user("u1"), shell("c1"), reply("r1")]);
expect(live.summaryRowsByHostId.get("u1")).not.toHaveProperty("timelineCursor");
const cursor = { epoch: "epoch-1", seq: 7, anchorSeq: 7 };
const cursor = { epoch: "epoch-1", seq: 7 };
const placed = [{ ...user("u1"), timelineCursor: cursor }, shell("c1"), reply("r1")];
const canonical = collapse(placed, { previousSummaryRowsByHostId: live.summaryRowsByHostId });
expect(canonical.summaryRowsByHostId.get("u1")).not.toBe(live.summaryRowsByHostId.get("u1"));
@@ -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",
+2 -35
View File
@@ -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(
@@ -961,18 +941,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} />
@@ -1198,7 +1166,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;
@@ -1,6 +1,4 @@
import { describe, expect, it } from "vitest";
import { resolveFilePreviewReadTarget } from "@/file-explorer/preview-target";
import { resolveWorkspaceFilePaths } from "@/workspace/file-open";
import {
classifyAssistantFileLink,
normalizeInlinePathTarget,
@@ -613,43 +611,3 @@ describe("encoded filename line markers", () => {
},
);
});
describe("slash-prefixed drive links in Windows workspaces", () => {
it.each([
["/E:/demo/repo/tools/tool.vbs", "E:/demo/repo/tools/tool.vbs", undefined],
["/E:/demo/repo/docs/my%20file.md#L12", "E:/demo/repo/docs/my file.md", 12],
["/E:/demo/repo/docs/guide.md:12", "E:/demo/repo/docs/guide.md", 12],
["E:/demo/repo/tools/tool.vbs", "E:/demo/repo/tools/tool.vbs", undefined],
["file:///E:/demo/repo/tools/tool.vbs", "E:/demo/repo/tools/tool.vbs", undefined],
])("resolves %s to the workspace read target", (href, path, lineStart) => {
const workspaceRoot = "E:\\demo\\repo";
const target = parseAssistantFileLink(href, {
workspaceRoot,
decodeHref: true,
explicitLink: true,
});
expect(target).toMatchObject({ raw: href, path });
expect(target?.lineStart).toBe(lineStart);
expect(resolveFilePreviewReadTarget({ path: target!.path, workspaceRoot })).toEqual({
cwd: workspaceRoot,
path,
});
expect(resolveWorkspaceFilePaths({ path: target!.path, workspaceRoot })).toEqual({
absolutePath: path,
relativePath: path.slice("E:/demo/repo/".length),
});
});
it.each(["/home/demo/repo", undefined])(
"preserves POSIX paths with workspace %s",
(workspaceRoot) => {
expect(
parseAssistantFileLink("/E:/demo/repo/tools/tool.vbs", {
workspaceRoot,
decodeHref: true,
explicitLink: true,
})?.path,
).toBe("/E:/demo/repo/tools/tool.vbs");
},
);
});
+2 -10
View File
@@ -260,7 +260,7 @@ export function parseAssistantFileLink(
return fileUrlTarget;
}
const trimmed = normalizeWindowsLinkPath(value?.trim(), options.workspaceRoot);
const trimmed = value?.trim();
if (!trimmed) {
return null;
}
@@ -271,7 +271,7 @@ export function parseAssistantFileLink(
const inlinePathTarget = parseAssistantInlinePathLink(trimmed, options);
if (inlinePathTarget) {
return { ...inlinePathTarget, raw: value };
return inlinePathTarget;
}
const windowsTarget = parseWindowsFileLink(trimmed, value, options);
@@ -350,14 +350,6 @@ export function isFileLookingAssistantToken(value: string): boolean {
return isPlausibleAssistantLocalPath(path);
}
// A drive-based workspace identifies the target host's path syntax, even when
// the client runs elsewhere. Preserve the same spelling on POSIX hosts.
function normalizeWindowsLinkPath(value: string, workspaceRoot?: string): string {
return /^[A-Za-z]:[\\/]/.test(workspaceRoot?.trim() ?? "") && /^\/[A-Za-z]:[\\/]/.test(value)
? value.slice(1)
: value;
}
function parseWindowsFileLink(
trimmed: string,
raw: string,
@@ -7,7 +7,6 @@ import { FOOTER_HEIGHT } from "@/constants/layout";
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
import { KeyboardTranslateView } from "@/keyboard/shift";
import { Button } from "@/components/ui/button";
import { useToast } from "@/contexts/toast-context";
import type { Theme } from "@/styles/theme";
import { toErrorMessage } from "@/utils/error-messages";
@@ -20,7 +19,6 @@ export function ArchivedAgentCallout({ serverId, agentId }: ArchivedAgentCallout
const { t } = useTranslation();
const client = useHostRuntimeClient(serverId);
const isConnected = useHostRuntimeIsConnected(serverId);
const toast = useToast();
const [isUnarchiving, setIsUnarchiving] = useState(false);
const [unarchiveError, setUnarchiveError] = useState<string | null>(null);
@@ -29,15 +27,12 @@ export function ArchivedAgentCallout({ serverId, agentId }: ArchivedAgentCallout
setIsUnarchiving(true);
setUnarchiveError(null);
try {
const refreshed = await client.refreshAgent(agentId);
if (refreshed.historyDiverged) {
toast.show(t("workspace.tabs.toasts.reloadedAgentHistoryDiverged"), { variant: "warning" });
}
await client.refreshAgent(agentId);
} catch (error) {
setUnarchiveError(toErrorMessage(error));
setIsUnarchiving(false);
}
}, [client, isConnected, isUnarchiving, agentId, toast, t]);
}, [client, isConnected, isUnarchiving, agentId]);
return (
<KeyboardTranslateView style={styles.container}>
-188
View File
@@ -19,11 +19,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";
@@ -42,17 +40,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,
@@ -1493,188 +1487,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],
paddingHorizontal: theme.spacing[4],
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,
},
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 = t("message.providerSwitch.contextSummary", {
count: context.includedItems,
chars: context.charCount.toLocaleString(),
budget: context.budgetChars.toLocaleString(),
});
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;
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={handleToggle}
accessibilityLabel={title}
testID="provider-switch-marker-toggle"
>
<View style={providerSwitchStylesheet.triggerContent}>
<StyledSwitchIcon size={12} />
<Text
style={providerSwitchStylesheet.triggerText}
numberOfLines={1}
ellipsizeMode="tail"
>
{title}
</Text>
{expanded ? <StyledChevronDownIcon size={12} /> : <StyledChevronRightIcon size={12} />}
</View>
</Button>
<View style={providerSwitchStylesheet.line} />
</View>
{expanded ? (
<View style={providerSwitchStylesheet.detailsCard} testID="provider-switch-marker-details">
<Text style={providerSwitchStylesheet.detailRow}>
{`${formatProviderSwitchEndpoint(fromLabel, fromModelLabel)} → ${formatProviderSwitchEndpoint(toLabel, toModelLabel)}`}
</Text>
<Text style={providerSwitchStylesheet.detailRow}>{contextLine}</Text>
{reasonsLine ? (
<Text style={providerSwitchStylesheet.detailRow}>{reasonsLine}</Text>
) : null}
</View>
) : null}
</View>
);
});
interface TodoListCardProps {
items: TodoEntry[];
activity: TaskActivity;
@@ -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.14.1, remove after 2027-05-10. A daemon with
// the feature delivers the rewind on the live timeline; an older one replaced the timeline
// and this client has to read it again.
const appliesLive =
input.serverId !== undefined &&
hostSupportsFeature(
useSessionStore.getState().sessions[input.serverId]?.serverInfo,
"timelineRewindOperations",
);
if (mode !== "files" && !appliesLive) {
if (mode !== "files") {
const cursor = input.serverId
? useSessionStore
.getState()
@@ -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<
+3 -44
View File
@@ -1,13 +1,7 @@
import type { SelectedFile } from "@/attachments/selected-file";
import { FILE_UPLOAD_MAX_BYTES } from "@/attachments/upload-limit";
import type { AgentProvider, ProviderOptions } from "@getpaseo/protocol/agent-types";
import type {
ActiveTurnBehavior,
AgentSnapshotPayload,
ForgeSearchItem,
} from "@getpaseo/protocol/messages";
import { AgentProviderSwitchError } from "@getpaseo/client/internal/daemon-client";
import type { StagedProviderSwitch } from "@/composer/provider-switch";
import type { ForgeSearchItem } from "@getpaseo/protocol/messages";
import type { ActiveTurnBehavior } from "@getpaseo/protocol/messages";
import type {
AttachmentMetadata,
ComposerAttachment,
@@ -62,20 +56,6 @@ export interface ComposerSendClient {
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"];
},
) => Promise<{ agent?: AgentSnapshotPayload }>;
uploadFile: (input: { fileName: string; mimeType: string; bytes: Uint8Array }) => Promise<{
requestId: string;
file: {
@@ -217,8 +197,6 @@ export interface DispatchComposerAgentMessageInput {
submission: MessageSubmissionWriter;
activeTurnBehavior?: ActiveTurnBehavior;
activeTurnId?: string;
stagedProviderSwitch?: StagedProviderSwitch | null;
onProviderSwitchCommitted?: (agent: AgentSnapshotPayload | undefined) => void | Promise<void>;
}
export async function dispatchComposerAgentMessage(
@@ -234,29 +212,13 @@ export async function dispatchComposerAgentMessage(
timestamp: new Date(),
images: wirePayload.images,
attachments: wirePayload.attachments,
...(input.activeTurnBehavior === "steer" && input.activeTurnId && !input.stagedProviderSwitch
...(input.activeTurnBehavior === "steer" && input.activeTurnId
? { turnId: input.activeTurnId }
: {}),
});
input.submission.begin(input.agentId, userMessage);
try {
const imagesData = await input.encodeImages(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,
images: imagesData ?? [],
attachments: wirePayload.attachments,
});
input.submission.accept(input.agentId, clientMessageId);
await input.onProviderSwitchCommitted?.(result.agent);
return;
}
await input.client.sendAgentMessage(input.agentId, input.text, {
messageId: clientMessageId,
...(input.activeTurnBehavior ? { activeTurnBehavior: input.activeTurnBehavior } : {}),
@@ -266,9 +228,6 @@ 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;
}
}
@@ -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 {
@@ -111,7 +102,6 @@ import {
type AgentProfilePicker,
type AgentProfileSeed,
type DraftAgentProfileControls,
type MaterializedAgentProfile,
} from "@/agent-profiles";
import { buildSettingsHostSectionRoute } from "@/utils/host-routes";
@@ -148,7 +138,6 @@ interface ControlledAgentControlsProps {
modeControl?: AgentModeControlValue | null;
modelSelectorServerId?: string | null;
isCompactLayout?: boolean;
openModelBrowserAtProviders?: boolean;
}
export interface DraftAgentControlsProps {
@@ -462,7 +451,6 @@ function ControlledAgentControls({
modeControl,
modelSelectorServerId = null,
isCompactLayout,
openModelBrowserAtProviders,
}: ControlledAgentControlsProps) {
const { t } = useTranslation();
const isCompactFormFactor = useIsCompactFormFactor();
@@ -722,7 +710,6 @@ function ControlledAgentControls({
showLabels={presentation.showModelLabel}
modelSelectorServerId={modelSelectorServerId}
canSwitchProvider={Boolean(onSelectProviderAndModel)}
openModelBrowserAtProviders={openModelBrowserAtProviders}
/>
)}
{!isCompact ? (
@@ -920,7 +907,6 @@ interface SheetAgentControlsContentProps extends AgentControlsContentProps {
displayThinking: string | null;
handleSheetModelSelect: (providerId: string, modelId: string) => void;
canSwitchProvider: boolean;
openModelBrowserAtProviders?: boolean;
}
function SheetAgentControlsContent(props: SheetAgentControlsContentProps) {
@@ -953,7 +939,6 @@ function SheetAgentControlsContent(props: SheetAgentControlsContentProps) {
showLabels,
modelSelectorServerId,
canSwitchProvider,
openModelBrowserAtProviders,
} = props;
const sheetControls = (
@@ -1003,7 +988,6 @@ function SheetAgentControlsContent(props: SheetAgentControlsContentProps) {
glyphs={glyphs}
showLabels={showLabels}
canSwitchProvider={canSwitchProvider}
openModelBrowserAtProviders={openModelBrowserAtProviders}
>
{sheetControls}
</CompactModelSheet>
@@ -1022,148 +1006,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,
@@ -1171,22 +1013,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,
@@ -1196,35 +1031,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)];
}
@@ -1232,19 +1056,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[]>(() => {
@@ -1261,71 +1080,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,
@@ -1340,147 +1101,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,
@@ -1493,13 +1128,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;
}
@@ -1520,35 +1148,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;
}
@@ -1565,36 +1176,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.
@@ -1618,12 +1208,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,
},
@@ -1642,7 +1232,7 @@ export const AgentControls = memo(function AgentControls({
client,
agentId,
agentModelSelectorProviders,
effectiveProvider,
agentProvider,
commandCenterModes,
handleSelectCommandCenterModel,
handleSelectThinkingOption,
@@ -1662,8 +1252,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) => {
@@ -1676,18 +1266,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}
@@ -1695,17 +1273,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}
@@ -1939,7 +1521,6 @@ export function DraftAgentControls({
modeControl={modeControl}
modelSelectorServerId={modelSelectorServerId}
isCompactLayout={isCompactLayout}
openModelBrowserAtProviders
/>
</>
) : null}
@@ -282,7 +282,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);
@@ -13,17 +13,17 @@ describe("model sheet opening", () => {
it("starts drafts at providers even when only one provider is available", () => {
expect(
resolveModelSheetOpening({
openAtProviders: true,
canSwitchProvider: true,
providers: [codex],
selectedProvider: "codex",
}),
).toEqual({ kind: "all" });
});
it("opens a running agent directly at its current provider even when other providers are available", () => {
it("opens a running agent directly at its fixed provider", () => {
expect(
resolveModelSheetOpening({
openAtProviders: false,
canSwitchProvider: false,
providers: [claude, codex],
selectedProvider: "codex",
}),
@@ -33,7 +33,7 @@ describe("model sheet opening", () => {
it("falls back to the only provider while live state catches up", () => {
expect(
resolveModelSheetOpening({
openAtProviders: false,
canSwitchProvider: false,
providers: [codex],
selectedProvider: "",
}),
@@ -2,16 +2,15 @@ import type { ModelBrowserView } from "@/components/model-browser-view";
import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection";
export function resolveModelSheetOpening({
openAtProviders,
canSwitchProvider,
providers,
selectedProvider,
}: {
/** Drafts open at the provider list; live agents open directly at their active provider. */
openAtProviders: boolean;
canSwitchProvider: boolean;
providers: ProviderSelectorProvider[];
selectedProvider: string;
}): ModelBrowserView {
if (openAtProviders) return { kind: "all" };
if (canSwitchProvider) return { kind: "all" };
const provider = providers.find((entry) => entry.id === selectedProvider) ?? providers[0] ?? null;
return provider
@@ -68,8 +68,6 @@ interface CompactModelSheetProps {
/** False when the toolbar is too narrow for labels: the trigger shows the provider glyph only. */
showLabels: boolean;
canSwitchProvider: boolean;
/** Drafts open the model browser at the all-providers list; live agents open at their active provider. */
openModelBrowserAtProviders?: boolean;
/** Carries the composer's contexts into the sheets, which draw away from it. */
contextBridge?: ContextBridge | null;
children: ReactNode;
@@ -162,7 +160,6 @@ export function CompactModelSheet({
glyphs,
showLabels,
canSwitchProvider,
openModelBrowserAtProviders = false,
contextBridge = null,
children,
}: CompactModelSheetProps) {
@@ -242,7 +239,7 @@ export function CompactModelSheet({
const openModelBrowser = useCallback(() => {
Keyboard.dismiss();
const destination = resolveModelSheetOpening({
openAtProviders: openModelBrowserAtProviders,
canSwitchProvider,
providers: availableProviders,
selectedProvider,
});
@@ -252,7 +249,7 @@ export function CompactModelSheet({
modelBrowser.drillDown(destination.providerId, destination.providerLabel);
}
setIsModelBrowserOpen(true);
}, [availableProviders, modelBrowser, openModelBrowserAtProviders, selectedProvider]);
}, [availableProviders, canSwitchProvider, modelBrowser, selectedProvider]);
const closeModelBrowser = useCallback(() => {
setIsModelBrowserOpen(false);
+31 -225
View File
@@ -9,20 +9,6 @@ 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,
useFailedStartupSettings,
useStagedProviderSwitch,
} 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,
@@ -62,7 +48,6 @@ import { usePanelStore, type MobilePanelView } from "@/stores/panel-store";
import { usePointerCapabilities } from "@/hooks/pointer-capabilities";
import { useShallow } from "zustand/shallow";
import {
ArrowRightLeft,
ArrowUp,
Square,
Pencil,
@@ -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,
};
};
}
@@ -1379,56 +1351,10 @@ 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 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;
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);
useSessionStore.getState().setQueuedSendError(serverId, agentId, 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 queuedMessagesRaw = useSessionStore((state) =>
state.sessions[serverId]?.queuedMessages?.get(agentId),
);
const queuedSendError = useSessionStore(
(state) => state.sessions[serverId]?.queuedSendErrors?.get(agentId) ?? null,
);
const queuedMessages = queuedMessagesRaw ?? EMPTY_ARRAY;
const setQueuedMessages = useSessionStore((state) => state.setQueuedMessages);
@@ -1783,62 +1709,25 @@ 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;
useSessionStore.getState().setQueuedSendError(serverId, targetAgentId, null);
if (stagedProviderSwitch) {
beginStagedProviderSwitch(serverId, targetAgentId);
}
try {
await dispatchComposerAgentMessage({
client,
agentId: targetAgentId,
text,
attachments: sendAttachments,
attachmentSubmitFormat: resolveComposerAttachmentSubmitFormat({
supportsForgeAttachments: supportsForgeSearch,
}),
encodeImages,
submission: createMessageSubmissionWriter(serverId),
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,
}),
encodeImages,
submission: createMessageSubmissionWriter(serverId),
activeTurnBehavior,
activeTurnId:
activeTurnBehavior === "steer"
? (selectAgentTurnPresentation(
useSessionStore.getState().sessions[serverId],
targetAgentId,
).turnId ?? undefined)
: undefined,
});
onAttentionPromptSend?.();
};
}, [appSettings.sendBehavior, client, onAttentionPromptSend, serverId, supportsForgeSearch, t]);
@@ -1914,7 +1803,7 @@ function ComposerContentImpl({
attachments: outgoingAttachments,
hasExternalContent,
allowEmptySubmit,
forceSend: stagedSwitch && isAgentRunning ? false : forceSend,
forceSend,
submitBehavior,
isAgentRunning,
// Parent-managed submits are still valid submit paths even when the
@@ -1956,7 +1845,6 @@ function ComposerContentImpl({
queueMessage,
setSelectedAttachments,
replaceUserInput,
stagedSwitch,
submitBehavior,
submitMessage,
t,
@@ -2191,17 +2079,15 @@ function ComposerContentImpl({
queue: queueWriter,
});
if (!result) return;
useSessionStore.getState().setQueuedSendError(serverId, agentId, null);
replaceUserInput(result.text);
setSelectedAttachments(result.attachments);
},
[agentId, queueWriter, replaceUserInput, serverId, setSelectedAttachments],
[agentId, queueWriter, replaceUserInput, setSelectedAttachments],
);
const handleSendQueuedNow = useCallback(
async (id: string) => {
if (!sendAgentMessageRef.current && !onSubmitMessageRef.current) return;
useSessionStore.getState().setQueuedSendError(serverId, agentId, null);
// Reuse the regular send path; server-side send atomically interrupts any active run.
const result = await sendQueuedComposerMessageNow({
agentId,
@@ -2215,7 +2101,7 @@ function ComposerContentImpl({
setSendError(result.errorMessage);
}
},
[agentId, queueWriter, serverId, submitMessage, t],
[agentId, queueWriter, submitMessage, t],
);
const handleQueue = useCallback(
@@ -2668,71 +2554,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 || queuedSendError;
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) 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, stagedProviderLabel, stagedSwitch, t]);
return (
<>
<ComposerKeyboardRegistration
@@ -2758,7 +2591,6 @@ function ComposerContentImpl({
>
<View style={inputAreaContentStyle}>
{isFullscreen ? null : queueList}
{isFullscreen ? null : stagedSwitchBannerNode}
{!isFullscreen && sendErrorNode}
<ComposerAutocompleteBinding
@@ -3014,35 +2846,9 @@ const styles = StyleSheet.create((theme: Theme) => ({
queueSendButton: {
backgroundColor: theme.colors.accent,
},
stagedSwitchBanner: {
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
paddingLeft: theme.spacing[3],
paddingRight: theme.spacing[1.5],
paddingVertical: theme.spacing[1],
backgroundColor: theme.colors.surface1,
borderRadius: theme.borderRadius.md,
borderWidth: theme.borderWidth[1],
borderColor: theme.colors.border,
gap: theme.spacing[2],
},
stagedSwitchLabelRow: {
flex: 1,
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[1.5],
minWidth: 0,
},
stagedSwitchText: {
flex: 1,
fontSize: theme.fontSize.sm,
color: theme.colors.foregroundMuted,
},
})) 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);
@@ -1,19 +0,0 @@
export {
applyFailedStartupSettings,
beginStagedProviderSwitch,
clearStagedProviderSwitch,
discardFailedStartupSettings,
endStagedProviderSwitch,
getFailedStartupSettings,
getStagedProviderSwitch,
isStagedProviderSwitchInFlight,
settleCommittedProviderSwitch,
settleStagedProviderSwitch,
useFailedStartupSettings,
useStagedProviderSwitch,
useStagedProviderSwitchStore,
type FailedStartupSettings,
type LiveAgentSettingsWriter,
type SettleCommittedProviderSwitchResult,
type StagedProviderSwitch,
} from "./store";
File diff suppressed because it is too large Load Diff
@@ -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,401 +0,0 @@
import { create } from "zustand";
import type { AgentProvider, ProviderOptions } from "@getpaseo/protocol/agent-types";
import type { AgentConfigApply } 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;
}),
}));
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,
);
}
@@ -385,16 +385,6 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
console.warn("[Session] timeline replacement refresh failed", { serverId, error });
});
};
const onRewind = (message: SessionOutboundMessage) => {
if (message.type !== "agent.timeline.rewind") return;
const { agentId, epoch, seq, retireFromSeq } = message.payload;
sync.applyStreamEvent(agentId, {
event: { type: "rewind", retireFromSeq },
seq,
epoch,
timestamp: new Date(),
});
};
const sync = getHostRuntimeStore().createViewedTimelineOwner(serverId, {
canCheckFreshness: () =>
client.getLastServerInfoMessage()?.features?.timelineFreshnessCheck === true,
@@ -405,7 +395,6 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
update: (message) => {
if (message.type === "agent_stream") onStream(message);
else if (message.type === "agent.timeline.replacement") onReplacement(message);
else if (message.type === "agent.timeline.rewind") onRewind(message);
},
});
return observation;
@@ -166,7 +166,7 @@ describe("ensureAgentIsInitialized", () => {
kind: "assistant_message",
id: "canonical-item",
text: "Canonical before restart",
timelineCursor: { epoch: "epoch-1", seq: 12, anchorSeq: 12 },
timelineCursor: { epoch: "epoch-1", seq: 12 },
timestamp: new Date("2026-07-27T10:00:00.000Z"),
},
],
-13
View File
@@ -205,10 +205,6 @@ export const ar: TranslationResources = {
pasteImageFailed: "تعذر لصق الصورة",
fileTooLarge: "{{fileName}} is too large (max {{size}})",
},
providerSwitch: {
switchingNextMessage: "التبديل إلى {{provider}} في الرسالة التالية",
switchingAfterTurn: "سيتم التبديل إلى {{provider}} بعد هذا الدور",
},
clientCommands: {
archiveAgent: "أرشفة الوكيل الحالي",
freshDraft: "أرشفة هذا الوكيل وابدأ مسودة جديدة",
@@ -440,13 +436,6 @@ export const ar: TranslationResources = {
turnFooter: {
workedFor: "عمل لمدة {{duration}}",
},
providerSwitch: {
switched: "تم التبديل من {{from}} إلى {{to}}",
contextSummary: "تم نقل {{count}} عنصر ({{chars}} / {{budget}} حرف)",
trimmed: "تم الاقتطاع: {{reasons}}",
reasonTailWindow: "سجل أقدم خارج النطاق",
reasonCharBudget: "حد الأحرف",
},
compaction: {
loading: "الضغط...",
auto: "يتم ضغط السياق تلقائيًا",
@@ -752,8 +741,6 @@ export const ar: TranslationResources = {
resumeCommandUnavailable: "أمر الاستئناف غير متوفر",
reloadingAgent: "وكيل إعادة التحميل...",
reloadedAgent: "وكيل إعادة تحميل",
reloadedAgentHistoryDiverged:
"تمت إعادة تحميل الوكيل، لكن سجل المزوّد لا يطابق هذه المحادثة، لذا لم تتم مزامنته",
failedToReloadAgent: "فشل في إعادة تحميل الوكيل",
failedToCloseAgent: "فشل في إغلاق الوكيل",
},
-13
View File
@@ -203,10 +203,6 @@ export const en = {
pasteImageFailed: "Failed to paste image",
fileTooLarge: "{{fileName}} is too large (max {{size}})",
},
providerSwitch: {
switchingNextMessage: "Switching to {{provider}} on next message",
switchingAfterTurn: "Will switch to {{provider}} after this turn",
},
clientCommands: {
archiveAgent: "Archive the current agent",
freshDraft: "Archive this agent and start a fresh draft",
@@ -439,13 +435,6 @@ export const en = {
turnFooter: {
workedFor: "Worked for {{duration}}",
},
providerSwitch: {
switched: "Switched from {{from}} to {{to}}",
contextSummary: "{{count}} items transferred ({{chars}} / {{budget}} chars)",
trimmed: "Trimmed: {{reasons}}",
reasonTailWindow: "older history beyond window",
reasonCharBudget: "character budget",
},
compaction: {
loading: "Compacting...",
auto: "Context automatically compacted",
@@ -751,8 +740,6 @@ export const en = {
resumeCommandUnavailable: "Resume command not available",
reloadingAgent: "Reloading agent...",
reloadedAgent: "Reloaded agent",
reloadedAgentHistoryDiverged:
"Reloaded agent, but the provider's history doesn't match this chat, so it wasn't synced",
failedToReloadAgent: "Failed to reload agent",
failedToCloseAgent: "Failed to close agent",
},
-13
View File
@@ -207,10 +207,6 @@ export const es: TranslationResources = {
pasteImageFailed: "No se pudo pegar la imagen",
fileTooLarge: "{{fileName}} is too large (max {{size}})",
},
providerSwitch: {
switchingNextMessage: "Cambiando a {{provider}} en el próximo mensaje",
switchingAfterTurn: "Se cambiará a {{provider}} después de este turno",
},
clientCommands: {
archiveAgent: "Archivar el agente actual",
freshDraft: "Archive este agente y comience un nuevo borrador",
@@ -445,13 +441,6 @@ export const es: TranslationResources = {
turnFooter: {
workedFor: "Trabajó durante {{duration}}",
},
providerSwitch: {
switched: "Cambiado de {{from}} a {{to}}",
contextSummary: "{{count}} elementos transferidos ({{chars}} / {{budget}} caracteres)",
trimmed: "Recortado: {{reasons}}",
reasonTailWindow: "historial anterior fuera de la ventana",
reasonCharBudget: "límite de caracteres",
},
compaction: {
loading: "Compactando...",
auto: "Contexto compactado automáticamente",
@@ -759,8 +748,6 @@ export const es: TranslationResources = {
resumeCommandUnavailable: "Comando de reanudación no disponible",
reloadingAgent: "Agente de recarga...",
reloadedAgent: "Agente recargado",
reloadedAgentHistoryDiverged:
"Agente recargado, pero el historial del proveedor no coincide con este chat, así que no se sincronizó",
failedToReloadAgent: "No se pudo recargar el agente",
failedToCloseAgent: "No se pudo cerrar el agente",
},
-13
View File
@@ -208,10 +208,6 @@ export const fr: TranslationResources = {
pasteImageFailed: "Impossible de coller l’image",
fileTooLarge: "{{fileName}} est trop volumineux (maximum {{size}})",
},
providerSwitch: {
switchingNextMessage: "Passage à {{provider}} au prochain message",
switchingAfterTurn: "Passage à {{provider}} après ce tour",
},
clientCommands: {
archiveAgent: "Archiver l’agent actuel",
freshDraft: "Archiver cet agent et démarrer un nouveau brouillon",
@@ -445,13 +441,6 @@ export const fr: TranslationResources = {
turnFooter: {
workedFor: "A travaillé pendant {{duration}}",
},
providerSwitch: {
switched: "Passé de {{from}} à {{to}}",
contextSummary: "{{count}} éléments transférés ({{chars}} / {{budget}} caractères)",
trimmed: "Tronqué : {{reasons}}",
reasonTailWindow: "historique antérieur hors fenêtre",
reasonCharBudget: "limite de caractères",
},
compaction: {
loading: "Compaction…",
auto: "Contexte compacté automatiquement",
@@ -759,8 +748,6 @@ export const fr: TranslationResources = {
resumeCommandUnavailable: "Commande de reprise indisponible",
reloadingAgent: "Rechargement de l’agent…",
reloadedAgent: "Agent rechargé",
reloadedAgentHistoryDiverged:
"Agent rechargé, mais l’historique du fournisseur ne correspond pas à cette conversation, il n’a donc pas été synchronisé",
failedToReloadAgent: "Impossible de recharger l’agent",
failedToCloseAgent: "Impossible de fermer l’agent",
},
-13
View File
@@ -207,10 +207,6 @@ export const ja: TranslationResources = {
pasteImageFailed: "画像を貼り付けられませんでした",
fileTooLarge: "{{fileName}}が大きすぎます(最大{{size}})",
},
providerSwitch: {
switchingNextMessage: "次のメッセージで {{provider}} に切り替えます",
switchingAfterTurn: "このターン終了後に {{provider}} に切り替えます",
},
clientCommands: {
archiveAgent: "現在のエージェントをアーカイブ",
freshDraft: "このエージェントをアーカイブして新しい下書きを開始",
@@ -445,13 +441,6 @@ export const ja: TranslationResources = {
turnFooter: {
workedFor: "作業時間 {{duration}}",
},
providerSwitch: {
switched: "{{from}} から {{to}} に切り替えました",
contextSummary: "{{count}} 件を引き継ぎました ({{chars}} / {{budget}} 文字)",
trimmed: "省略: {{reasons}}",
reasonTailWindow: "ウィンドウ外の古い履歴",
reasonCharBudget: "文字数上限",
},
compaction: {
loading: "コンテキストを圧縮中...",
auto: "コンテキストが自動的に圧縮されました",
@@ -759,8 +748,6 @@ export const ja: TranslationResources = {
resumeCommandUnavailable: "再開コマンドが利用できません",
reloadingAgent: "エージェントを再読み込み中...",
reloadedAgent: "エージェントを再読み込みしました",
reloadedAgentHistoryDiverged:
"エージェントを再読み込みしましたが、プロバイダーの履歴がこのチャットと一致しないため同期しませんでした",
failedToReloadAgent: "エージェントの再読み込みに失敗しました",
failedToCloseAgent: "エージェントを閉じられませんでした",
},
-13
View File
@@ -205,10 +205,6 @@ export const ko: TranslationResources = {
pasteImageFailed: "이미지를 붙여넣지 못했습니다.",
fileTooLarge: "{{fileName}}이(가) 너무 큽니다 (최대 {{size}})",
},
providerSwitch: {
switchingNextMessage: "다음 메시지에서 {{provider}}(으)로 전환합니다",
switchingAfterTurn: "이 턴이 끝난 후 {{provider}}(으)로 전환합니다",
},
clientCommands: {
archiveAgent: "현재 에이전트 보관",
freshDraft: "이 에이전트를 보관하고 새 초안을 시작합니다",
@@ -441,13 +437,6 @@ export const ko: TranslationResources = {
turnFooter: {
workedFor: "작업 시간 {{duration}}",
},
providerSwitch: {
switched: "{{from}}에서 {{to}}(으)로 전환됨",
contextSummary: "{{count}}개 항목 전달됨 ({{chars}} / {{budget}}자)",
trimmed: "생략됨: {{reasons}}",
reasonTailWindow: "창 범위를 벗어난 이전 기록",
reasonCharBudget: "문자 수 제한",
},
compaction: {
loading: "압축하는 중...",
auto: "컨텍스트가 자동으로 압축되었습니다",
@@ -754,8 +743,6 @@ export const ko: TranslationResources = {
resumeCommandUnavailable: "재개 명령을 사용할 수 없습니다",
reloadingAgent: "에이전트 다시 로드 중...",
reloadedAgent: "에이전트를 다시 로드했습니다",
reloadedAgentHistoryDiverged:
"에이전트를 다시 로드했지만 제공자 기록이 이 채팅과 일치하지 않아 동기화하지 않았습니다",
failedToReloadAgent: "에이전트를 다시 로드하지 못했습니다",
failedToCloseAgent: "에이전트를 닫지 못했습니다",
},
-13
View File
@@ -206,10 +206,6 @@ export const ptBR: TranslationResources = {
pasteImageFailed: "Falha ao colar a imagem",
fileTooLarge: "{{fileName}} é grande demais (máximo {{size}})",
},
providerSwitch: {
switchingNextMessage: "Trocando para {{provider}} na próxima mensagem",
switchingAfterTurn: "Trocará para {{provider}} após este turno",
},
clientCommands: {
archiveAgent: "Arquivar o agente atual",
freshDraft: "Arquivar este agente e iniciar um novo rascunho",
@@ -444,13 +440,6 @@ export const ptBR: TranslationResources = {
turnFooter: {
workedFor: "Trabalhou por {{duration}}",
},
providerSwitch: {
switched: "Trocado de {{from}} para {{to}}",
contextSummary: "{{count}} itens transferidos ({{chars}} / {{budget}} caracteres)",
trimmed: "Cortado: {{reasons}}",
reasonTailWindow: "histórico anterior além da janela",
reasonCharBudget: "limite de caracteres",
},
compaction: {
loading: "Compactando...",
auto: "Contexto compactado automaticamente",
@@ -757,8 +746,6 @@ export const ptBR: TranslationResources = {
resumeCommandUnavailable: "Comando de retomada indisponível",
reloadingAgent: "Recarregando agente...",
reloadedAgent: "Agente recarregado",
reloadedAgentHistoryDiverged:
"Agente recarregado, mas o histórico do provedor não corresponde a este chat, então não foi sincronizado",
failedToReloadAgent: "Falha ao recarregar agente",
failedToCloseAgent: "Falha ao fechar agente",
},
-13
View File
@@ -207,10 +207,6 @@ export const ru: TranslationResources = {
pasteImageFailed: "Не удалось вставить изображение",
fileTooLarge: "Файл {{fileName}} слишком большой (максимальный размер: {{size}})",
},
providerSwitch: {
switchingNextMessage: "Переключение на {{provider}} в следующем сообщении",
switchingAfterTurn: "Переключение на {{provider}} после этого хода",
},
clientCommands: {
archiveAgent: "Архивировать текущего агента",
freshDraft: "Архивировать этого агента и создать новый черновик",
@@ -444,13 +440,6 @@ export const ru: TranslationResources = {
turnFooter: {
workedFor: "Время работы: {{duration}}",
},
providerSwitch: {
switched: "Переключено с {{from}} на {{to}}",
contextSummary: "Передано элементов: {{count}} ({{chars}} / {{budget}} симв.)",
trimmed: "Сокращено: {{reasons}}",
reasonTailWindow: "более ранняя история вне окна",
reasonCharBudget: "лимит символов",
},
compaction: {
loading: "Сжатие контекста...",
auto: "Контекст сжат автоматически",
@@ -760,8 +749,6 @@ export const ru: TranslationResources = {
resumeCommandUnavailable: "Команда возобновления недоступна",
reloadingAgent: "Перезагрузка агента...",
reloadedAgent: "Агент перезагружен",
reloadedAgentHistoryDiverged:
"Агент перезагружен, но история провайдера не совпадает с этим чатом, поэтому она не синхронизирована",
failedToReloadAgent: "Не удалось перезагрузить агента",
failedToCloseAgent: "Не удалось закрыть агента",
},
-13
View File
@@ -205,10 +205,6 @@ export const zhCN: TranslationResources = {
pasteImageFailed: "无法粘贴图片",
fileTooLarge: "{{fileName}} is too large (max {{size}})",
},
providerSwitch: {
switchingNextMessage: "下一条消息将切换到 {{provider}}",
switchingAfterTurn: "本轮结束后将切换到 {{provider}}",
},
clientCommands: {
archiveAgent: "归档当前 Agent",
freshDraft: "归档此 Agent 并开始新的草稿",
@@ -440,13 +436,6 @@ export const zhCN: TranslationResources = {
turnFooter: {
workedFor: "工作了 {{duration}}",
},
providerSwitch: {
switched: "已从 {{from}} 切换到 {{to}}",
contextSummary: "已传递 {{count}} 项上下文({{chars}} / {{budget}} 字符)",
trimmed: "已裁剪:{{reasons}}",
reasonTailWindow: "超出窗口的早期历史",
reasonCharBudget: "字符预算限制",
},
compaction: {
loading: "正在压缩...",
auto: "上下文已自动压缩",
@@ -752,8 +741,6 @@ export const zhCN: TranslationResources = {
resumeCommandUnavailable: "恢复命令不可用",
reloadingAgent: "正在重新加载 Agent...",
reloadedAgent: "已重新加载 Agent",
reloadedAgentHistoryDiverged:
"已重新加载 Agent,但提供方的历史记录与此对话不一致,因此未同步",
failedToReloadAgent: "重新加载 Agent 失败",
failedToCloseAgent: "关闭 Agent 失败",
},
@@ -224,9 +224,8 @@ export function useOverlayRegistration({
activeRef.current && typeof window !== "undefined" && typeof document !== "undefined";
if (!shouldRegister) {
const shouldRestoreFocus = !activeRef.current;
const removeEntry = removeEntryRef.current ?? detachedRemoveEntryRef.current;
if (registeredRef.current || shouldRestoreFocus) {
removeEntry?.({ restoreFocus: shouldRestoreFocus });
removeEntryRef.current?.({ restoreFocus: shouldRestoreFocus });
}
registeredRef.current = false;
if (shouldRestoreFocus) {
@@ -269,14 +268,8 @@ export function useOverlayRegistration({
[syncRegistration],
);
// Run `active` transitions in layout effects (after React's `resetAfterCommit`), so closing a
// fading overlay restores focus after React's commit-time selection restoration instead of
// having `resetAfterCommit` pull focus back into the still-mounted closing dialog.
useLayoutEffect(() => {
syncRegistration();
}, [active, syncRegistration]);
useLayoutEffect(() => {
return () => {
const removeEntry = removeEntryRef.current ?? detachedRemoveEntryRef.current;
removeEntry?.();
@@ -284,7 +277,7 @@ export function useOverlayRegistration({
detachedRemoveEntryRef.current = null;
registeredRef.current = false;
};
}, [syncRegistration]);
}, [active, syncRegistration]);
return setScope;
}
@@ -74,74 +74,6 @@ describe("useOverlayRegistration in the browser", () => {
expect(openerFocusCalls).toBe(1);
});
it("restores focus to the non-first opener button when a fading upper overlay closes over a lower overlay", async () => {
function StackedHarness({ upperActive }: { upperActive: boolean }) {
const setLowerScope = useOverlayRegistration({
keys: ["Escape"],
active: true,
layer: 10,
onKeyDown: () => false,
});
const setUpperScope = useOverlayRegistration({
keys: ["Escape"],
active: upperActive,
layer: 30,
onKeyDown: () => false,
});
return (
<>
<div
data-testid="lower-scope"
ref={setLowerScope as RefCallback<HTMLDivElement>}
tabIndex={-1}
>
<button data-testid="lower-first" type="button">
Back
</button>
<button data-testid="lower-second" type="button">
Settings
</button>
</div>
<div
data-testid="upper-scope"
ref={setUpperScope as RefCallback<HTMLDivElement>}
tabIndex={-1}
>
<button data-testid="upper-close" type="button">
Close
</button>
</div>
</>
);
}
flushSync(() => {
root.render(<StackedHarness upperActive={false} />);
});
await nextFrame();
const lowerSecond = document.querySelector<HTMLButtonElement>('[data-testid="lower-second"]');
expect(lowerSecond).toBeTruthy();
lowerSecond?.focus();
expect(document.activeElement).toBe(lowerSecond);
flushSync(() => {
root.render(<StackedHarness upperActive />);
});
await nextFrame();
const upperClose = document.querySelector<HTMLButtonElement>('[data-testid="upper-close"]');
expect(document.activeElement).toBe(upperClose);
// Keep upper-scope mounted while closing (mirrors AdaptiveModalSheet's web fade-out).
flushSync(() => {
root.render(<StackedHarness upperActive={false} />);
});
await nextFrame();
expect(document.activeElement).toBe(lowerSecond);
});
});
describe("hasOpenDomPopover", () => {
@@ -197,7 +197,7 @@ describe("plugin timeline projection", () => {
kind: "assistant_message",
id: "assistant-1",
messageId: "provider-msg-1",
timelineCursor: { epoch: "e1", seq: 7, anchorSeq: 7 },
timelineCursor: { epoch: "e1", seq: 7 },
turnId: "turn-1",
text: 'Summary\n\n```ui\nCard("Hi", [])\n```',
timestamp: new Date("2026-01-01T00:00:02.000Z"),
@@ -226,13 +226,13 @@ describe("plugin timeline projection", () => {
{
kind: "plugin",
id: "genui/assistant-1/text",
timelineCursor: { epoch: "e1", seq: 7, anchorSeq: 7 },
timelineCursor: { epoch: "e1", seq: 7 },
turnId: "turn-1",
},
{
kind: "plugin",
id: "genui/assistant-1/card",
timelineCursor: { epoch: "e1", seq: 7, anchorSeq: 7 },
timelineCursor: { epoch: "e1", seq: 7 },
turnId: "turn-1",
},
]);
@@ -65,7 +65,6 @@ function sourceTimelineItem(item: StreamItem): AgentTimelineItem | null {
...(item.preTokens !== undefined ? { preTokens: item.preTokens } : {}),
};
case "plugin":
case "provider_switch":
case "turn_summary":
return null;
}
@@ -91,7 +91,7 @@ describe("AgentDirectoryReplica", () => {
id: "reply",
text: "server history",
timestamp: new Date(),
timelineCursor: { epoch: "e", seq: 1, anchorSeq: 1 },
timelineCursor: { epoch: "e", seq: 1 },
},
],
head: [],
@@ -201,15 +201,9 @@ export class AgentStoreProjection {
useDraftStore.getState().clearDraftInput({
draftKey: buildDraftStoreKey({ serverId: this.serverId, agentId }),
});
// Only entity deletion destroys the transcript. A filtered active-list
// response can arrive after a fresh history response for an archived agent.
const store = useSessionStore.getState();
const removeKey = withoutAgent(agentId);
store.setAgentTimelineCursor(this.serverId, removeKey);
store.setAgentTimelineUnsettledTurn(this.serverId, agentId, null);
store.setAgentAuthoritativeHistoryApplied(this.serverId, agentId, false);
store.setAgentStreamTail(this.serverId, removeKey);
store.clearAgentStreamHead(this.serverId, agentId);
// Leaving the active list does not release the transcript: an archived chat open in
// History stays readable. The viewed timeline owner releases it once nobody shows it.
useSessionStore.getState().releaseAgentTimeline(this.serverId, agentId);
}
archive(agentId: string, archivedAt: string): Agent | null {
+24 -144
View File
@@ -83,18 +83,8 @@ import {
} from "@/desktop/browser/automation/handler";
import { schedulesQueryBaseKey } from "@/schedules/aggregated-schedules";
import { dispatchComposerAgentMessage, sendQueuedComposerMessageNow } from "@/composer/actions";
import {
applyFailedStartupSettings,
beginStagedProviderSwitch,
discardFailedStartupSettings,
endStagedProviderSwitch,
getFailedStartupSettings,
getStagedProviderSwitch,
settleCommittedProviderSwitch,
} from "@/composer/provider-switch";
import { createMessageSubmissionWriter } from "@/composer/submission/writer";
import { resolveComposerAttachmentSubmitFormat } from "@/composer/attachments/submit";
import { normalizeAgentSnapshot } from "@/utils/agent-snapshots";
import { encodeImages } from "@/utils/encode-images";
import { DirectorySync, type RefreshAgentDirectoryResult } from "@/runtime/directory-sync";
import { ReplicaCache } from "@/runtime/replica-cache";
@@ -265,7 +255,6 @@ const PROBE_INACTIVE_WHILE_ONLINE_MAX_MS = 30 * 60_000;
const ACTIVE_RTT_WINDOW_MS = 60_000;
const ADAPTIVE_SWITCH_THRESHOLD_MS = 40;
const ADAPTIVE_SWITCH_MIN_IMPROVEMENT_RATIO = 0.35;
const MAX_STALE_TIMELINE_PAGE_ATTEMPTS = 3;
const ADAPTIVE_SWITCH_CONSECUTIVE_PROBES = 3;
const CONFIGURED_OVERRIDE_BOOTSTRAP_RETRY_MS = 1_000;
@@ -1928,7 +1917,6 @@ export class HostRuntimeStore {
private lastOnlineEpochByServer = new Map<string, number>();
private connectionStatusStartedAtByServer = new Map<string, number>();
private queuedAgentDrainInFlight = new Set<string>();
private queuedAgentDrainPending = new Set<string>();
private directorySyncByServer = new Map<string, DirectorySync>();
private nextCancellationRequestId = 0;
private timelineReplicaByServer = new Map<string, TimelineReplica>();
@@ -2893,58 +2881,9 @@ export class HostRuntimeStore {
}
}
private resumeIdleQueueIfReady(serverId: string, agentId: string): void {
const latestSession = useSessionStore.getState().sessions[serverId];
const latestAgent = latestSession?.agents.get(agentId);
const remainingQueue = latestSession?.queuedMessages.get(agentId);
if (
latestAgent?.status === "idle" &&
remainingQueue &&
remainingQueue.length > 0 &&
latestSession?.initializingAgents.get(agentId) !== true
) {
this.drainQueuedAgentMessage(serverId, agentId);
}
}
/**
* Explicitly retries or discards startup settings that failed after a provider switch,
* then resumes automatic draining if the chat is idle with queued messages.
*/
async recoverFailedStartupSettings(
serverId: string,
agentId: string,
action: "retry" | "discard",
): Promise<boolean> {
if (action === "discard") {
discardFailedStartupSettings(serverId, agentId);
useSessionStore.getState().setQueuedSendError(serverId, agentId, null);
this.resumeIdleQueueIfReady(serverId, agentId);
return true;
}
const client = useSessionStore.getState().sessions[serverId]?.client;
if (!client) {
return false;
}
const result = await applyFailedStartupSettings({ serverId, agentId, client });
if (!result.applied) {
useSessionStore.getState().setQueuedSendError(serverId, agentId, result.errorMessage);
return false;
}
useSessionStore.getState().setQueuedSendError(serverId, agentId, null);
this.resumeIdleQueueIfReady(serverId, agentId);
return true;
}
drainQueuedAgentMessage(serverId: string, agentId: string): void {
if (getFailedStartupSettings(serverId, agentId)) {
return;
}
const drainKey = `${serverId}:${agentId}`;
if (this.queuedAgentDrainInFlight.has(drainKey)) {
this.queuedAgentDrainPending.add(drainKey);
return;
}
if (this.queuedAgentDrainInFlight.has(drainKey)) return;
const store = useSessionStore.getState();
const session = store.sessions[serverId];
const queue = session?.queuedMessages.get(agentId);
@@ -2953,11 +2892,7 @@ export class HostRuntimeStore {
return;
}
this.queuedAgentDrainInFlight.add(drainKey);
this.queuedAgentDrainPending.delete(drainKey);
useSessionStore.getState().setQueuedSendError(serverId, agentId, null);
const next = queue[0];
let drainSent = false;
let drainBlockedBySettingsError: string | null = null;
void sendQueuedComposerMessageNow({
agentId,
messageId: next.id,
@@ -2967,69 +2902,28 @@ export class HostRuntimeStore {
write: (update) => useSessionStore.getState().setQueuedMessages(serverId, update),
},
submitMessage: async ({ text, attachments }) => {
const currentSession = useSessionStore.getState().sessions[serverId];
const supportsForgeAttachments = currentSession?.serverInfo?.features?.forgeSearch === true;
const supportsProviderSwitching =
currentSession?.serverInfo?.features?.providerSwitching === true;
const liveProvider = currentSession?.agents.get(agentId)?.provider;
const rawStagedSwitch = supportsProviderSwitching
? getStagedProviderSwitch(serverId, agentId)
: null;
const stagedProviderSwitch =
rawStagedSwitch && rawStagedSwitch.provider !== liveProvider ? rawStagedSwitch : null;
if (stagedProviderSwitch) {
beginStagedProviderSwitch(serverId, agentId);
}
try {
await dispatchComposerAgentMessage({
client,
agentId,
text,
attachments,
attachmentSubmitFormat: resolveComposerAttachmentSubmitFormat({
supportsForgeAttachments,
}),
encodeImages,
submission: createMessageSubmissionWriter(serverId),
stagedProviderSwitch,
onProviderSwitchCommitted: async (agent) => {
if (agent) {
this.tryAcceptAgentSnapshot(serverId, normalizeAgentSnapshot(agent, serverId));
}
if (stagedProviderSwitch) {
const settled = await settleCommittedProviderSwitch({
serverId,
agentId,
sentDraft: stagedProviderSwitch,
committedProvider: agent?.provider ?? null,
client,
});
if (!settled.applied) {
drainBlockedBySettingsError = settled.errorMessage;
}
}
},
// The queue drains when the agent goes idle, but the agent can start a turn of its own
// in that same moment (a wake-up after background work). Steering folds the message
// into that turn instead of interrupting it; with no turn running, the daemon starts
// a normal one.
activeTurnBehavior: "steer",
});
} finally {
if (stagedProviderSwitch) {
endStagedProviderSwitch(serverId, agentId);
}
}
const supportsForgeAttachments =
useSessionStore.getState().sessions[serverId]?.serverInfo?.features?.forgeSearch === true;
await dispatchComposerAgentMessage({
client,
agentId,
text,
attachments,
attachmentSubmitFormat: resolveComposerAttachmentSubmitFormat({
supportsForgeAttachments,
}),
encodeImages,
submission: createMessageSubmissionWriter(serverId),
// The queue drains when the agent goes idle, but the agent can start a turn of its own
// in that same moment (a wake-up after background work). Steering folds the message
// into that turn instead of interrupting it; with no turn running, the daemon starts
// a normal one.
activeTurnBehavior: "steer",
});
},
})
.then((result) => {
if (result.status === "submitted") {
drainSent = drainBlockedBySettingsError === null;
useSessionStore
.getState()
.setQueuedSendError(serverId, agentId, drainBlockedBySettingsError);
} else if (result.status === "failed") {
useSessionStore.getState().setQueuedSendError(serverId, agentId, result.errorMessage);
if (result.status === "failed") {
console.error("[HostRuntime] failed to drain queued agent message", {
serverId,
agentId,
@@ -3040,9 +2934,6 @@ export class HostRuntimeStore {
})
.finally(() => {
this.queuedAgentDrainInFlight.delete(drainKey);
const hadPendingDrain = this.queuedAgentDrainPending.delete(drainKey);
if (!drainSent || !hadPendingDrain) return;
this.resumeIdleQueueIfReady(serverId, agentId);
});
}
@@ -3068,10 +2959,6 @@ export class HostRuntimeStore {
return this.requireDirectory(serverId).acceptAgent(agent);
}
tryAcceptAgentSnapshot(serverId: string, agent: Agent): Agent | null {
return this.directorySyncByServer.get(serverId)?.acceptAgent(agent) ?? null;
}
archiveAgentSnapshot(serverId: string, agentId: string, archivedAt: string): void {
this.requireDirectory(serverId).archiveAgent(agentId, archivedAt);
}
@@ -3241,19 +3128,12 @@ export class HostRuntimeStore {
const directory = this.directorySyncByServer.get(serverId);
if (!directory) throw new Error(`Unknown host runtime for serverId ${serverId}`);
const owner = useSessionStore.getState().sessions[serverId]?.viewedTimelineSync;
// A page served before a rewind this client applied is asked for again. Seqs only grow within
// an epoch, so the next page includes the rewind unless another one landed meanwhile.
for (let attempt = 1; ; attempt += 1) {
const page = await directory.fetchTimeline(agentId, request);
if (!owner || useSessionStore.getState().sessions[serverId]?.viewedTimelineSync !== owner) {
return page;
}
const page = await directory.fetchTimeline(agentId, request);
if (owner && useSessionStore.getState().sessions[serverId]?.viewedTimelineSync === owner) {
owner.flushStreamAgent(agentId);
if (owner.applyTimelineResponse(page) === "applied") return page;
if (attempt === MAX_STALE_TIMELINE_PAGE_ATTEMPTS) {
throw new Error(`Timeline page for ${agentId} stayed behind a rewind`);
}
owner.applyTimelineResponse(page);
}
return page;
}
createViewedTimelineOwner(
@@ -189,7 +189,7 @@ function timelineItem(text = "Cached"): StreamItem {
id: "message-1",
text,
timestamp: new Date("2026-07-18T08:02:00.000Z"),
timelineCursor: { epoch: "epoch-1", seq: 12, anchorSeq: 12 },
timelineCursor: { epoch: "epoch-1", seq: 12 },
};
}
@@ -840,7 +840,7 @@ describe("ReplicaCache", () => {
version: 1,
data: { passed: 4, failed: 0 },
timestamp: new Date("2026-07-18T08:02:00.000Z"),
timelineCursor: { epoch: "epoch-1", seq: 12, anchorSeq: 12 },
timelineCursor: { epoch: "epoch-1", seq: 12 },
};
writer.commitTimeline(SERVER_ID, "agent-1", {
agentId: "agent-1",
@@ -885,32 +885,6 @@ describe("ReplicaCache", () => {
expect(await createCache(storage).readTimeline(SERVER_ID, "agent-1")).toBeUndefined();
});
it("keeps where each cached row started, and refetches a timeline cached without it", async () => {
const storage = new MemoryStorage();
const writer = createCache(storage);
const updatedAfterItStarted: StreamItem = {
...timelineItem(),
timelineCursor: { epoch: "epoch-1", seq: 12, anchorSeq: 9 },
};
writer.commitTimeline(SERVER_ID, "agent-1", { ...timeline(), items: [updatedAfterItStarted] });
await writer.flush();
expect((await createCache(storage).readTimeline(SERVER_ID, "agent-1"))?.items).toEqual([
updatedAfterItStarted,
]);
const row = requireTimelineRow(storage);
const payload = JSON.parse(row.payload) as {
items: Array<{ timelineCursor?: Record<string, unknown> }>;
};
delete payload.items[0]?.timelineCursor?.anchorSeq;
storage.rows.set(`${row.serverId}:${row.kind}:${row.id}`, {
...row,
payload: JSON.stringify(payload),
});
expect(await createCache(storage).readTimeline(SERVER_ID, "agent-1")).toBeUndefined();
});
it("refetches old cached Markdown fragments instead of offering them as whole messages", async () => {
const storage = new MemoryStorage();
const writer = createCache(storage);
@@ -1381,7 +1355,7 @@ it("retains semantic agent messages across disk-cache reconstruction", async ()
kind: "tool_call",
id: "delivery",
timestamp: new Date(1),
timelineCursor: { epoch: "epoch-1", seq: 12, anchorSeq: 12 },
timelineCursor: { epoch: "epoch-1", seq: 12 },
payload: {
source: "agent",
data: {
@@ -22,7 +22,6 @@ import {
isUnreconciledLocalUserMessage,
type AgentToolCallData,
type StreamItem,
type TimelinePosition,
} from "@/types/stream";
import type { UnsettledTurn } from "@/timeline/turn-liveness";
import { normalizeAgentSnapshot } from "@/utils/agent-snapshots";
@@ -83,15 +82,7 @@ const IsoDateSchema = z.iso.datetime();
const TimelinePositionSchema = z.strictObject({
epoch: z.string(),
seq: z.number().int().nonnegative(),
// COMPAT(timelineRewindOperations): absent on caches written before rows were anchored, added in
// v0.14.1, remove after 2027-05-10. Such a cache is not restored; the chat loads its tail instead.
anchorSeq: z.number().int().nonnegative().optional(),
});
type StoredTimelinePosition = z.infer<typeof TimelinePositionSchema>;
function isAnchored(position: StoredTimelinePosition | undefined): boolean {
return position === undefined || position.anchorSeq !== undefined;
}
const PluginTimelineDataSchema: z.ZodType<PluginTimelineData> = z.lazy(() =>
z.union([
z.null(),
@@ -170,23 +161,6 @@ const StoredTimelineItemSchema = z.discriminatedUnion("kind", [
trigger: z.enum(["auto", "manual"]).optional(),
preTokens: z.number().nonnegative().optional(),
}),
z.strictObject({
...TimelineItemBaseShape,
kind: z.literal("provider_switch"),
fromProvider: AgentProviderSchema,
toProvider: AgentProviderSchema,
fromModel: z.string().nullable().optional(),
toModel: z.string().nullable().optional(),
fromSessionId: z.string().nullable().optional(),
toSessionId: z.string().nullable().optional(),
context: z.strictObject({
includedItems: z.number().int().nonnegative(),
truncated: z.boolean(),
charCount: z.number().int().nonnegative(),
budgetChars: z.number().int().positive(),
omittedReasons: z.array(z.string()).optional(),
}),
}),
z.strictObject({
...TimelineItemBaseShape,
kind: z.literal("tool_call"),
@@ -388,7 +362,6 @@ const StoredTimelineSchema = z.strictObject({
epoch: z.string(),
startSeq: z.number().int().nonnegative(),
endSeq: z.number().int().nonnegative(),
activeSegmentStartSeq: z.number().int().nonnegative().optional(),
})
.nullable(),
hasOlder: z.boolean(),
@@ -450,10 +423,6 @@ function deserializeTimeline(stored: StoredTimeline | null): CachedTimeline | nu
if (!stored) {
return null;
}
// A rewind retires rows by anchor, so an unanchored row could not be retired.
if (!stored.items.every((item) => isAnchored(item.timelineCursor))) {
return null;
}
return {
agentId: stored.agentId,
items: stored.items.map(deserializeTimelineItem),
@@ -500,23 +469,6 @@ function serializeAgentToolCall(data: AgentToolCallData): StoredToolCall {
}
}
function serializeProviderSwitchItem(
base: ReturnType<typeof timelineBase>,
item: Extract<StreamItem, { kind: "provider_switch" }>,
): StoredTimelineItem {
return {
...base,
kind: item.kind,
fromProvider: item.fromProvider,
toProvider: item.toProvider,
...(item.fromModel !== undefined ? { fromModel: item.fromModel } : {}),
...(item.toModel !== undefined ? { toModel: item.toModel } : {}),
...(item.fromSessionId !== undefined ? { fromSessionId: item.fromSessionId } : {}),
...(item.toSessionId !== undefined ? { toSessionId: item.toSessionId } : {}),
context: item.context,
};
}
function serializeTimelineItem(item: StreamItem): StoredTimelineItem | null {
const base = timelineBase(item);
switch (item.kind) {
@@ -562,8 +514,6 @@ function serializeTimelineItem(item: StreamItem): StoredTimelineItem | null {
...(item.trigger ? { trigger: item.trigger } : {}),
...(item.preTokens !== undefined ? { preTokens: item.preTokens } : {}),
};
case "provider_switch":
return serializeProviderSwitchItem(base, item);
case "tool_call":
if (item.payload.source !== "agent") return null;
return {
@@ -589,20 +539,11 @@ function serializeTimelineItem(item: StreamItem): StoredTimelineItem | null {
}
}
function anchoredPosition(position: StoredTimelinePosition | undefined): {
timelineCursor?: TimelinePosition;
} {
if (!position || position.anchorSeq === undefined) return {};
return {
timelineCursor: { epoch: position.epoch, seq: position.seq, anchorSeq: position.anchorSeq },
};
}
function deserializeTimelineItem(item: StoredTimelineItem): StreamItem {
if (item.kind === "plugin") {
return {
id: item.id,
...anchoredPosition(item.timelineCursor),
...(item.timelineCursor ? { timelineCursor: item.timelineCursor } : {}),
...(item.turnId ? { turnId: item.turnId } : {}),
timestamp: new Date(item.timestamp),
kind: item.kind,
@@ -616,29 +557,12 @@ function deserializeTimelineItem(item: StoredTimelineItem): StreamItem {
return deserializeBuiltinTimelineItem(item);
}
function deserializeProviderSwitchItem(
base: { id: string; timelineCursor?: TimelinePosition; turnId?: string; timestamp: Date },
item: Extract<StoredTimelineItem, { kind: "provider_switch" }>,
): StreamItem {
return {
...base,
kind: item.kind,
fromProvider: item.fromProvider,
toProvider: item.toProvider,
...(item.fromModel !== undefined ? { fromModel: item.fromModel } : {}),
...(item.toModel !== undefined ? { toModel: item.toModel } : {}),
...(item.fromSessionId !== undefined ? { fromSessionId: item.fromSessionId } : {}),
...(item.toSessionId !== undefined ? { toSessionId: item.toSessionId } : {}),
context: item.context,
};
}
function deserializeBuiltinTimelineItem(
item: Exclude<StoredTimelineItem, { kind: "plugin" }>,
): StreamItem {
const base = {
id: item.id,
...anchoredPosition(item.timelineCursor),
...(item.timelineCursor ? { timelineCursor: item.timelineCursor } : {}),
...(item.turnId ? { turnId: item.turnId } : {}),
timestamp: new Date(item.timestamp),
};
@@ -685,8 +609,6 @@ function deserializeBuiltinTimelineItem(
...(item.trigger ? { trigger: item.trigger } : {}),
...(item.preTokens !== undefined ? { preTokens: item.preTokens } : {}),
};
case "provider_switch":
return deserializeProviderSwitchItem(base, item);
case "tool_call": {
const tool = item.item;
if (tool.type !== "tool_call") {
@@ -918,14 +840,7 @@ function serializeTimeline(timeline: CachedTimeline): StoredTimeline | null {
agentId: timeline.agentId,
items,
range: canPersistCoverage
? {
epoch: range.epoch,
startSeq: range.startSeq,
endSeq: range.endSeq,
...(range.activeSegmentStartSeq !== undefined
? { activeSegmentStartSeq: range.activeSegmentStartSeq }
: {}),
}
? { epoch: range.epoch, startSeq: range.startSeq, endSeq: range.endSeq }
: null,
hasOlder: canPersistCoverage ? timeline.hasOlder : false,
...(timeline.unsettledTurn
@@ -2188,10 +2188,11 @@ function WorkspaceScreenContent({
toast.show(t("workspace.tabs.toasts.reloadingAgent"), { durationMs: null });
try {
const refreshed = await client.refreshAgent(agentId);
// Send the existing cursor: Reload agent keeps the history, so the server
// returns only the rows it added. When the history was imported again
// under a new epoch, the cursor reads as stale and the server resets.
await client.refreshAgent(agentId);
// Send the existing cursor so the server detects the new epoch and
// returns reset:true. Without a cursor, the server returns reset:false
// and the client takes the incremental path, where new-epoch rows are
// dropped against the stale cursor.
const sessionState = useSessionStore.getState().sessions[normalizedServerId];
const currentCursor = sessionState?.agentTimelineCursor.get(agentId);
await getHostRuntimeStore().fetchAgentTimeline(normalizedServerId, agentId, {
@@ -2200,13 +2201,7 @@ function WorkspaceScreenContent({
? { cursor: { epoch: currentCursor.epoch, seq: currentCursor.endSeq } }
: {}),
});
if (refreshed.historyDiverged) {
toast.show(t("workspace.tabs.toasts.reloadedAgentHistoryDiverged"), {
variant: "warning",
});
} else {
toast.show(t("workspace.tabs.toasts.reloadedAgent"), { variant: "success" });
}
toast.show(t("workspace.tabs.toasts.reloadedAgent"), { variant: "success" });
} catch (error) {
toast.error(
error instanceof Error ? error.message : t("workspace.tabs.toasts.failedToReloadAgent"),
+31 -62
View File
@@ -317,7 +317,6 @@ export interface AgentTimelineCursorState {
epoch: string;
startSeq: number;
endSeq: number;
activeSegmentStartSeq?: number;
retainedRanges?: Array<{
startSeq: number;
endSeq: number;
@@ -325,12 +324,6 @@ export interface AgentTimelineCursorState {
}>;
}
/** The latest conversation rewind applied to an agent's history, by its sequence number. */
export interface AgentTimelineRewind {
epoch: string;
seq: number;
}
export type AgentTimelineState =
| { status: "cold" }
| { status: "painted"; items: StreamItem[] }
@@ -505,7 +498,6 @@ export interface SessionState {
agentTimelineUnsettledTurn: Map<string, UnsettledTurn>;
agentTimelineHasOlder: Map<string, boolean>;
agentTimelineHasNewer: Map<string, boolean>;
agentTimelineLatestRewind: Map<string, AgentTimelineRewind>;
agentTimelineOlderFetchInFlight: Map<string, boolean>;
historySyncGeneration: number;
agentHistorySyncGeneration: Map<string, number>;
@@ -536,7 +528,6 @@ export interface SessionState {
string,
Array<{ id: string; text: string; attachments: ComposerAttachment[] }>
>;
queuedSendErrors: Map<string, string>;
}
// Global store state
@@ -612,6 +603,8 @@ interface SessionStoreActions {
message: UserMessageItem,
) => boolean;
clearAgentStreamHead: (serverId: string, agentId: string) => void;
/** Drops every piece of one chat's resident transcript: rows, cursors, paging and sync marks. */
releaseAgentTimeline: (serverId: string, agentId: string) => void;
setAgentTimelineCursor: (
serverId: string,
state:
@@ -626,12 +619,6 @@ interface SessionStoreActions {
serverId: string,
state: Map<string, boolean> | ((prev: Map<string, boolean>) => Map<string, boolean>),
) => void;
/** Records a rewind applied to the agent's history; an older one of the same history is ignored. */
recordAgentTimelineRewind: (
serverId: string,
agentId: string,
rewind: AgentTimelineRewind,
) => void;
setAgentTimelineOlderFetchInFlight: (
serverId: string,
state: Map<string, boolean> | ((prev: Map<string, boolean>) => Map<string, boolean>),
@@ -728,7 +715,6 @@ interface SessionStoreActions {
prev: Map<string, Array<{ id: string; text: string; attachments: ComposerAttachment[] }>>,
) => Map<string, Array<{ id: string; text: string; attachments: ComposerAttachment[] }>>),
) => void;
setQueuedSendError: (serverId: string, agentId: string, error: string | null) => void;
// Hydration
setHasHydratedAgents: (serverId: string, hydrated: boolean) => void;
@@ -769,7 +755,6 @@ function createInitialSessionState(
agentTimelineUnsettledTurn: new Map(),
agentTimelineHasOlder: new Map(),
agentTimelineHasNewer: new Map(),
agentTimelineLatestRewind: new Map(),
agentTimelineOlderFetchInFlight: new Map(),
historySyncGeneration: 0,
agentHistorySyncGeneration: new Map(),
@@ -784,7 +769,6 @@ function createInitialSessionState(
pendingPermissions: new Map(),
fileExplorer: new Map(),
queuedMessages: new Map(),
queuedSendErrors: new Map(),
};
}
@@ -1360,6 +1344,35 @@ export const useSessionStore = create<SessionStore>()(
});
},
releaseAgentTimeline: (serverId, agentId) => {
set((prev) => {
const session = prev.sessions[serverId];
if (!session) return prev;
const timelineKeys = [
"agentStreamTail",
"agentStreamHead",
"agentTasks",
"agentTimelineCursor",
"agentTimelineUnsettledTurn",
"agentTimelineHasOlder",
"agentTimelineHasNewer",
"agentTimelineOlderFetchInFlight",
"agentHistorySyncGeneration",
"agentAuthoritativeHistoryApplied",
] as const satisfies readonly (keyof SessionState)[];
let next: SessionState | null = null;
for (const key of timelineKeys) {
const current: Map<string, unknown> = session[key];
if (!current.has(agentId)) continue;
const without = new Map(current);
without.delete(agentId);
next = { ...(next ?? session), [key]: without };
}
if (!next) return prev;
return { ...prev, sessions: { ...prev.sessions, [serverId]: next } };
});
},
setAgentTimelineCursor: (serverId, state) => {
set((prev) => {
const session = prev.sessions[serverId];
@@ -1419,24 +1432,6 @@ export const useSessionStore = create<SessionStore>()(
});
},
recordAgentTimelineRewind: (serverId, agentId, rewind) => {
set((prev) => {
const session = prev.sessions[serverId];
if (!session) return prev;
const current = session.agentTimelineLatestRewind.get(agentId);
if (current && current.epoch === rewind.epoch && current.seq >= rewind.seq) return prev;
const next = new Map(session.agentTimelineLatestRewind);
next.set(agentId, rewind);
return {
...prev,
sessions: {
...prev.sessions,
[serverId]: { ...session, agentTimelineLatestRewind: next },
},
};
});
},
setAgentTimelineOlderFetchInFlight: (serverId, state) => {
set((prev) => {
const session = prev.sessions[serverId];
@@ -1980,32 +1975,6 @@ export const useSessionStore = create<SessionStore>()(
});
},
setQueuedSendError: (serverId, agentId, error) => {
set((prev) => {
const session = prev.sessions[serverId];
if (!session) {
return prev;
}
const existing = session.queuedSendErrors.get(agentId) ?? null;
if (existing === error) {
return prev;
}
const next = new Map(session.queuedSendErrors);
if (error === null) {
next.delete(agentId);
} else {
next.set(agentId, error);
}
return {
...prev,
sessions: {
...prev.sessions,
[serverId]: { ...session, queuedSendErrors: next },
},
};
});
},
// Hydration
setHasHydratedAgents: (serverId, hydrated) => {
set((prev) => {
@@ -165,6 +165,7 @@ it("feeds restored layout to timeline sync as a release signal, not a subscripti
const sync = createViewedTimelineSync({
replaceDemandedAgentIds: () => undefined,
prepare: async () => undefined,
isArchived: () => false,
canCheckFreshness: () => false,
applyCurrentTimeline: () => undefined,
observe: (agentIds) => {
+372 -231
View File
@@ -7,9 +7,17 @@ import {
} from "@/runtime/replica-cache/row-store-sqlite";
import { afterEach, describe, expect, it } from "vitest";
import type { AgentTimelineItem } from "@getpaseo/protocol/agent-types";
import type { AgentStreamEventPayload } from "@getpaseo/protocol/messages";
import type {
AgentSnapshotPayload,
AgentStreamEventPayload,
WorkspaceDescriptorPayload,
} from "@getpaseo/protocol/messages";
import type { FetchAgentsEntry } from "@getpaseo/client/internal/daemon-client";
import { AgentDirectoryReplica } from "@/runtime/directory-sync/agent-replica";
import { WorkspaceDirectoryReplica } from "@/runtime/directory-sync/workspace-replica";
import type { CachedTimeline } from "@/runtime/replica-cache";
import {
normalizeWorkspaceDescriptor,
selectAgentTimelineState,
selectAgentTimelineTurnPresentation,
selectAgentTurnPresentation,
@@ -39,7 +47,7 @@ function item(id: string, text: string, seq: number): StreamItem {
id,
text,
timestamp: new Date("2026-08-26T10:00:00.000Z"),
timelineCursor: { epoch: "epoch-1", seq, anchorSeq: seq },
timelineCursor: { epoch: "epoch-1", seq },
};
}
@@ -579,235 +587,6 @@ describe("viewed timeline persistence", () => {
});
});
describe("conversation rewind through the owner", () => {
const page = {
requestId: "page-1",
agentId: AGENT_ID,
agent: null,
direction: "tail",
projection: "projected",
reset: false,
epoch: "epoch-1",
error: null,
hasNewer: false,
hasOlder: false,
staleCursor: false,
gap: false,
} as const;
function entry(seq: number, type: "user_message" | "assistant_message", text: string) {
return {
seqStart: seq,
seqEnd: seq,
sourceSeqRanges: [{ startSeq: seq, endSeq: seq }],
collapsed: [],
provider: "codex",
item: { type, text },
timestamp: `2026-08-26T10:00:0${seq}.000Z`,
};
}
function texts(items: readonly StreamItem[]): string[] {
return items.flatMap((row) =>
row.kind === "user_message" || row.kind === "assistant_message" ? [row.text] : [],
);
}
function viewed(): string[] {
const session = useSessionStore.getState().sessions[SERVER_ID];
const timeline = selectAgentTimelineState(session, AGENT_ID);
const tail = timeline.status === "cold" ? [] : timeline.items;
return texts([...tail, ...(session?.agentStreamHead.get(AGENT_ID) ?? [])]);
}
function latestRewind() {
return useSessionStore.getState().sessions[SERVER_ID]?.agentTimelineLatestRewind.get(AGENT_ID);
}
it("retires B from the viewed and persisted timeline without refetching", () => {
useSessionStore.getState().initializeSession(SERVER_ID, null);
const commits: CachedTimeline[] = [];
const owner = createOwner({
readTimeline: async () => undefined,
commitTimeline: (_serverId, _agentId, timeline) => commits.push(timeline),
});
owner.applyTimelineResponse({
...page,
window: { minSeq: 1, maxSeq: 4, nextSeq: 5 },
startCursor: { epoch: "epoch-1", seq: 1 },
endCursor: { epoch: "epoch-1", seq: 4 },
entries: [
entry(1, "user_message", "A"),
entry(2, "assistant_message", "reply A"),
entry(3, "user_message", "B"),
entry(4, "assistant_message", "reply B"),
],
});
owner.applyStreamEvent(AGENT_ID, {
event: { type: "rewind", retireFromSeq: 3 },
seq: 5,
epoch: "epoch-1",
timestamp: new Date("2026-08-26T10:00:05.000Z"),
});
owner.applyStreamEvent(AGENT_ID, {
event: {
type: "timeline",
provider: "codex",
item: { type: "user_message", text: "C", messageId: "c" },
} as AgentStreamEventPayload,
seq: 6,
epoch: "epoch-1",
timestamp: new Date("2026-08-26T10:00:06.000Z"),
});
owner.flushStreamAgent(AGENT_ID);
expect(viewed()).toEqual(["A", "reply A", "C"]);
expect(texts(commits.at(-1)?.items ?? [])).toEqual(["A", "reply A", "C"]);
expect(commits.at(-1)?.range).toMatchObject({ epoch: "epoch-1", endSeq: 6 });
expect(latestRewind()).toEqual({ epoch: "epoch-1", seq: 5 });
owner.dispose();
});
it("brings a second client that loads after the rewind to the same conversation", () => {
useSessionStore.getState().initializeSession(SERVER_ID, null);
const owner = createOwner({ readTimeline: async () => undefined, commitTimeline: () => {} });
owner.applyTimelineResponse({
...page,
window: { minSeq: 1, maxSeq: 6, nextSeq: 7 },
startCursor: { epoch: "epoch-1", seq: 1 },
endCursor: { epoch: "epoch-1", seq: 6 },
entries: [
entry(1, "user_message", "A"),
entry(2, "assistant_message", "reply A"),
entry(6, "user_message", "C"),
],
retirements: [{ seq: 5, retireFromSeq: 3 }],
});
expect(viewed()).toEqual(["A", "reply A", "C"]);
expect(latestRewind()).toEqual({ epoch: "epoch-1", seq: 5 });
owner.dispose();
});
function liveRewindOfB(owner: ViewedTimelineOwner, retirement: { seq: number }): void {
owner.applyStreamEvent(AGENT_ID, {
event: { type: "rewind", retireFromSeq: 3 },
seq: retirement.seq,
epoch: "epoch-1",
timestamp: new Date("2026-08-26T10:00:06.000Z"),
});
owner.applyStreamEvent(AGENT_ID, {
event: {
type: "timeline",
provider: "codex",
item: { type: "user_message", text: "C", messageId: "c" },
} as AgentStreamEventPayload,
seq: retirement.seq + 1,
epoch: "epoch-1",
timestamp: new Date("2026-08-26T10:00:07.000Z"),
});
owner.flushStreamAgent(AGENT_ID);
}
/** A, reply A, B, reply B as a page served before B was rewound. */
const pageServedBeforeTheRewind: Parameters<ViewedTimelineOwner["applyTimelineResponse"]>[0] = {
...page,
direction: "before",
hasOlder: false,
window: { minSeq: 1, maxSeq: 5, nextSeq: 6 },
startCursor: { epoch: "epoch-1", seq: 1 },
endCursor: { epoch: "epoch-1", seq: 4 },
entries: [
entry(1, "user_message", "A"),
entry(2, "assistant_message", "reply A"),
entry(3, "user_message", "B"),
entry(4, "assistant_message", "reply B"),
],
};
function loadTheEndOfB(owner: ViewedTimelineOwner): void {
owner.applyTimelineResponse({
...page,
hasOlder: true,
window: { minSeq: 1, maxSeq: 5, nextSeq: 6 },
startCursor: { epoch: "epoch-1", seq: 5 },
endCursor: { epoch: "epoch-1", seq: 5 },
entries: [entry(5, "assistant_message", "more of B")],
});
}
it("refuses an older page served before the rewind and takes the one served after it", () => {
useSessionStore.getState().initializeSession(SERVER_ID, null);
const owner = createOwner({ readTimeline: async () => undefined, commitTimeline: () => {} });
loadTheEndOfB(owner);
liveRewindOfB(owner, { seq: 6 });
expect(viewed()).toEqual(["C"]);
const outcome = owner.applyTimelineResponse(pageServedBeforeTheRewind);
expect(viewed()).toEqual(["C"]);
expect(outcome).toBe("stale");
owner.applyTimelineResponse({
...pageServedBeforeTheRewind,
window: { minSeq: 1, maxSeq: 7, nextSeq: 8 },
// Retired rows count as covered, so the page reaches the loaded start.
endCursor: { epoch: "epoch-1", seq: 4 },
entries: [entry(1, "user_message", "A"), entry(2, "assistant_message", "reply A")],
});
expect(viewed()).toEqual(["A", "reply A", "C"]);
owner.dispose();
});
it("refuses a prompt jump window served before the rewind", () => {
useSessionStore.getState().initializeSession(SERVER_ID, null);
const owner = createOwner({ readTimeline: async () => undefined, commitTimeline: () => {} });
loadTheEndOfB(owner);
liveRewindOfB(owner, { seq: 6 });
const outcome = owner.applyTimelineResponse({
...pageServedBeforeTheRewind,
mergeWindow: true,
});
expect(viewed()).toEqual(["C"]);
expect(outcome).toBe("stale");
owner.dispose();
});
it("refuses a first page served before a rewind that reached the chat while it loaded", () => {
useSessionStore.getState().initializeSession(SERVER_ID, null);
const owner = createOwner({ readTimeline: async () => undefined, commitTimeline: () => {} });
liveRewindOfB(owner, { seq: 5 });
const outcome = owner.applyTimelineResponse({
...pageServedBeforeTheRewind,
direction: "tail",
window: { minSeq: 1, maxSeq: 4, nextSeq: 5 },
});
expect(viewed()).toEqual(["C"]);
expect(outcome).toBe("stale");
owner.applyTimelineResponse({
...page,
window: { minSeq: 1, maxSeq: 6, nextSeq: 7 },
startCursor: { epoch: "epoch-1", seq: 1 },
endCursor: { epoch: "epoch-1", seq: 6 },
entries: [
entry(1, "user_message", "A"),
entry(2, "assistant_message", "reply A"),
{
...entry(6, "user_message", "C"),
item: { type: "user_message", text: "C", messageId: "c" },
},
],
retirements: [{ seq: 5, retireFromSeq: 3 }],
});
expect(viewed()).toEqual(["A", "reply A", "C"]);
owner.dispose();
});
});
describe("turn boundaries", () => {
it("commits a turn's final reply before the turn stops running", () => {
useSessionStore.getState().initializeSession(SERVER_ID, null);
@@ -2031,3 +1810,365 @@ describe("SQLite baseline restoration", () => {
}
});
});
describe("archived timeline lifetime", () => {
const ACTIVE = "active-agent";
const OTHER = "other-agent";
const ARCHIVED = "archived-agent";
/** An agent whose row never got its archive timestamp, in a workspace that was archived. */
const IN_ARCHIVED_WORKSPACE = "agent-in-archived-workspace";
const WORKSPACE = "workspace";
const ARCHIVED_WORKSPACE = "archived-workspace";
const openOwners: ViewedTimelineOwner[] = [];
afterEach(() => {
for (const owner of openOwners.splice(0)) owner.dispose();
});
function agentPayload(
id: string,
archivedAt?: string,
workspaceId: string = WORKSPACE,
): AgentSnapshotPayload {
return {
id,
workspaceId,
provider: "codex",
cwd: "/repo",
model: null,
createdAt: "2026-07-17T00:00:00.000Z",
updatedAt: "2026-07-17T00:01:00.000Z",
lastUserMessageAt: null,
status: "idle",
capabilities: {
supportsStreaming: true,
supportsSessionPersistence: true,
supportsDynamicModes: true,
supportsMcpServers: true,
supportsReasoningStream: true,
supportsToolInvocations: true,
},
currentModeId: null,
availableModes: [],
pendingPermissions: [],
persistence: null,
title: id,
labels: {},
...(archivedAt ? { archivedAt } : {}),
};
}
function directoryEntry(id: string): FetchAgentsEntry {
return {
agent: agentPayload(id),
project: {
projectKey: "/repo",
projectName: "repo",
checkout: {
cwd: "/repo",
isGit: false,
currentBranch: null,
remoteUrl: null,
worktreeRoot: null,
isPaseoOwnedWorktree: false,
mainRepoRoot: null,
},
},
};
}
function historyPage(agentId: string): TimelineResponsePayload {
return {
requestId: `tail-${agentId}`,
agentId,
agent: null,
direction: "tail",
projection: "projected",
reset: false,
epoch: "epoch-1",
window: { minSeq: 1, maxSeq: 1, nextSeq: 2 },
startCursor: { epoch: "epoch-1", seq: 1 },
endCursor: { epoch: "epoch-1", seq: 1 },
entries: [
{
provider: "codex",
item: { type: "assistant_message", text: `history of ${agentId}` },
timestamp: "2026-08-26T10:00:00.000Z",
seqStart: 1,
seqEnd: 1,
sourceSeqRanges: [{ startSeq: 1, endSeq: 1 }],
collapsed: [],
},
],
error: null,
hasNewer: false,
hasOlder: false,
staleCursor: false,
gap: false,
};
}
/**
* A host with an active directory and a viewed-timeline owner. Fetches reach the store the
* way the host runtime delivers them: the agent row first, then the page, whether or not
* the catch-up that asked for it is still current.
*/
function openHost(
activeAgentIds: string[],
storage: TimelineReplicaStorage = {
readTimeline: async () => undefined,
commitTimeline: () => undefined,
},
) {
useSessionStore.getState().initializeSession(SERVER_ID, null);
const directory = new AgentDirectoryReplica(
SERVER_ID,
() => undefined,
() => undefined,
);
const workspaces = new WorkspaceDirectoryReplica(SERVER_ID);
workspaces.commitSnapshot(
{
workspaces: new Map([[WORKSPACE, normalizeWorkspaceDescriptor(workspaceDescriptor())]]),
projects: new Map(),
},
[],
);
directory.commitSnapshot(activeAgentIds.map(directoryEntry), []);
const fetches: string[] = [];
const held = new Map<string, () => void>();
const holding = new Set<string>();
const replica = createTimelineReplica({
serverId: SERVER_ID,
storage,
prepareAgent: async () => undefined,
});
const owner: ViewedTimelineOwner = createViewedTimelineOwner({
serverId: SERVER_ID,
replica,
replaceDemandedAgentIds: () => undefined,
drainQueuedAgentMessage: () => undefined,
applyTurnLiveness: () => undefined,
ports: {
canCheckFreshness: () => false,
observe: () => ({ ready: Promise.resolve(), release: async () => undefined }),
readCursor: () => undefined,
fetchPage: async (agentId) => {
fetches.push(agentId);
if (holding.has(agentId)) {
await new Promise<void>((resolve) => held.set(agentId, resolve));
}
if (agentId === ARCHIVED) {
directory.submitTimelineAgent(
directory.captureTimeline(agentId),
agentPayload(agentId, "2026-09-11T00:00:00.000Z"),
);
}
if (agentId === IN_ARCHIVED_WORKSPACE) {
directory.submitTimelineAgent(
directory.captureTimeline(agentId),
agentPayload(agentId, undefined, ARCHIVED_WORKSPACE),
);
}
owner.applyTimelineResponse(historyPage(agentId));
return { hasNewer: false, endCursor: null };
},
fetchLatestTail: async () => ({ hasNewer: false, endCursor: null }),
reportError: () => undefined,
},
});
owner.setConnected(true);
openOwners.push(owner);
return {
directory,
workspaces,
owner,
fetches,
view(agentIds: string[]) {
owner.replaceVisibleAgentIds("workspace", agentIds);
},
hold(agentId: string) {
holding.add(agentId);
},
async deliverHeld(agentId: string) {
await expect.poll(() => held.has(agentId)).toBe(true);
held.get(agentId)?.();
await new Promise((resolve) => setTimeout(resolve, 0));
},
};
}
function workspaceDescriptor(): WorkspaceDescriptorPayload {
return {
id: WORKSPACE,
projectId: "project",
projectDisplayName: "project",
projectRootPath: "/repo",
workspaceDirectory: "/repo",
projectKind: "git",
workspaceKind: "worktree",
name: WORKSPACE,
title: WORKSPACE,
status: "done",
activityAt: null,
statusEnteredAt: null,
archivingAt: null,
diffStat: null,
scripts: [],
};
}
function timelineStatus(agentId: string): string {
return selectAgentTimelineState(useSessionStore.getState().sessions[SERVER_ID], agentId).status;
}
function residentAgentIds(): string[] {
const session = useSessionStore.getState().sessions[SERVER_ID];
if (!session) return [];
return [
...new Set([
...session.agentStreamTail.keys(),
...session.agentStreamHead.keys(),
...session.agentTimelineCursor.keys(),
...session.agentAuthoritativeHistoryApplied.keys(),
...session.agentTimelineHasOlder.keys(),
...session.agentTimelineHasNewer.keys(),
...session.agentHistorySyncGeneration.keys(),
]),
].sort();
}
it("keeps hidden active chats cached and switches back without a fetch", async () => {
const host = openHost([ACTIVE, OTHER]);
host.view([ACTIVE]);
await expect.poll(() => timelineStatus(ACTIVE)).toBe("synced");
host.view([OTHER]);
await expect.poll(() => timelineStatus(OTHER)).toBe("synced");
host.view([ACTIVE]);
await new Promise((resolve) => setTimeout(resolve, 0));
expect(timelineStatus(ACTIVE)).toBe("synced");
expect(timelineStatus(OTHER)).toBe("synced");
expect(host.fetches).toEqual([ACTIVE, OTHER]);
});
it("releases a hidden chat's timeline when its agent is archived", async () => {
const host = openHost([ACTIVE, OTHER]);
host.view([ACTIVE]);
await expect.poll(() => timelineStatus(ACTIVE)).toBe("synced");
host.view([OTHER]);
await expect.poll(() => timelineStatus(OTHER)).toBe("synced");
host.directory.applyDelta({ kind: "remove", agentId: ACTIVE });
expect(timelineStatus(ACTIVE)).toBe("cold");
expect(residentAgentIds()).toEqual([OTHER]);
});
it("releases an archived chat's timeline once its tab is no longer shown", async () => {
const host = openHost([ACTIVE]);
host.view([ACTIVE]);
await expect.poll(() => timelineStatus(ACTIVE)).toBe("synced");
host.directory.archive(ACTIVE, "2026-09-11T00:00:00.000Z");
expect(timelineStatus(ACTIVE)).toBe("synced");
host.view([]);
expect(timelineStatus(ACTIVE)).toBe("cold");
expect(residentAgentIds()).toEqual([]);
});
it("releases every timeline of a workspace when the active list drops its agents", async () => {
const host = openHost([ACTIVE, OTHER]);
host.view([ACTIVE]);
await expect.poll(() => timelineStatus(ACTIVE)).toBe("synced");
host.view([OTHER]);
await expect.poll(() => timelineStatus(OTHER)).toBe("synced");
host.view([]);
host.directory.commitSnapshot([], []);
expect(residentAgentIds()).toEqual([]);
});
it("releases hidden timelines of a removed workspace whose agent rows still look active", async () => {
const host = openHost([ACTIVE, OTHER]);
host.view([ACTIVE]);
await expect.poll(() => timelineStatus(ACTIVE)).toBe("synced");
host.view([OTHER]);
await expect.poll(() => timelineStatus(OTHER)).toBe("synced");
host.workspaces.removeWorkspaceSnapshot(WORKSPACE);
expect(timelineStatus(OTHER)).toBe("synced");
expect(residentAgentIds()).toEqual([OTHER]);
host.view([]);
expect(residentAgentIds()).toEqual([]);
});
it("releases a History chat whose unarchived row belongs to an archived workspace", async () => {
const host = openHost([ACTIVE]);
host.view([IN_ARCHIVED_WORKSPACE]);
await expect.poll(() => timelineStatus(IN_ARCHIVED_WORKSPACE)).toBe("synced");
host.view([]);
expect(timelineStatus(IN_ARCHIVED_WORKSPACE)).toBe("cold");
expect(residentAgentIds()).toEqual([]);
});
it("keeps an archived chat open from History through active-list syncs and releases it on leave", async () => {
const host = openHost([ACTIVE]);
host.view([ARCHIVED]);
await expect.poll(() => timelineStatus(ARCHIVED)).toBe("synced");
host.directory.commitSnapshot([directoryEntry(ACTIVE)], []);
host.directory.applyDelta({ kind: "remove", agentId: ARCHIVED });
expect(timelineStatus(ARCHIVED)).toBe("synced");
host.view([]);
expect(timelineStatus(ARCHIVED)).toBe("cold");
expect(residentAgentIds()).toEqual([]);
host.view([ARCHIVED]);
await expect.poll(() => timelineStatus(ARCHIVED)).toBe("synced");
expect(host.fetches).toEqual([ARCHIVED, ARCHIVED]);
});
it("ignores a History read that answers after the archived chat was left", async () => {
const host = openHost([ACTIVE]);
host.hold(ARCHIVED);
host.view([ARCHIVED]);
await expect.poll(() => host.fetches).toEqual([ARCHIVED]);
host.view([]);
await host.deliverHeld(ARCHIVED);
expect(timelineStatus(ARCHIVED)).toBe("cold");
expect(residentAgentIds()).toEqual([]);
});
it("does not paint a cached archived chat back after it was left", async () => {
let finishRead!: () => void;
const readStarted = new Promise<void>((resolve) => {
finishRead = resolve;
});
let reading = false;
const host = openHost([ACTIVE], {
readTimeline: async (_serverId, agentId) => {
reading = true;
await readStarted;
return { ...cachedTimeline(), agentId };
},
commitTimeline: () => undefined,
});
host.view([ARCHIVED]);
await expect.poll(() => reading).toBe(true);
host.view([]);
finishRead();
await new Promise((resolve) => setTimeout(resolve, 0));
expect(timelineStatus(ARCHIVED)).toBe("cold");
expect(residentAgentIds()).toEqual([]);
});
});
@@ -398,7 +398,7 @@ describe("processTimelineResponse", () => {
messageId: "provider-message",
text: "local prompt",
timestamp: new Date(1000),
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
timelineCursor: { epoch: "epoch-1", seq: 1 },
turnId: "turn-1",
});
const hello = createUserMessage({
@@ -406,7 +406,7 @@ describe("processTimelineResponse", () => {
clientMessageId: "hello-client",
text: "hello",
timestamp: new Date(1500),
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
timelineCursor: { epoch: "epoch-1", seq: 2 },
turnId: "turn-1",
});
const currentTail = [canonical, makeAssistantItem("existing tail", "existing-tail"), hello];
@@ -456,7 +456,7 @@ describe("processTimelineResponse", () => {
id: "stale-history",
text: "stale history",
timestamp: new Date(1040),
timelineCursor: { epoch: "epoch-1", seq: 40, anchorSeq: 40 },
timelineCursor: { epoch: "epoch-1", seq: 40 },
},
],
currentCursor: { epoch: "epoch-1", startSeq: 1, endSeq: 40 },
@@ -484,11 +484,11 @@ describe("processTimelineResponse", () => {
const unresolved = makeSubmittedUserMessage("unresolved prompt", "client-unresolved");
const coveredLive: StreamItem = {
...makeAssistantItem("covered live", "covered-live"),
timelineCursor: { epoch: "epoch-1", seq: 235, anchorSeq: 235 },
timelineCursor: { epoch: "epoch-1", seq: 235 },
};
const newerLive: StreamItem = {
...makeAssistantItem("newer live", "newer-live"),
timelineCursor: { epoch: "epoch-1", seq: 245, anchorSeq: 245 },
timelineCursor: { epoch: "epoch-1", seq: 245 },
};
const result = processTimelineResponse({
@@ -573,7 +573,7 @@ describe("processTimelineResponse", () => {
expect.objectContaining({
kind: "assistant_message",
text: "[System Error] failed",
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 40 },
timelineCursor: { epoch: "timeline-1", seq: 42 },
}),
]);
});
@@ -745,7 +745,7 @@ describe("processTimelineResponse", () => {
}).item,
} as AgentStreamEventPayload,
timestamp: new Date(2000),
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
timelineCursor: { epoch: "epoch-1", seq: 2 },
},
],
{ source: "canonical" },
@@ -775,7 +775,7 @@ describe("processTimelineResponse", () => {
expect(getAgentToolCalls([...result.tail, ...result.head])).toEqual([
expect.objectContaining({
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 1 },
timelineCursor: { epoch: "epoch-1", seq: 2 },
payload: expect.objectContaining({
data: expect.objectContaining({ callId, status: "completed" }),
}),
@@ -796,7 +796,7 @@ describe("processTimelineResponse", () => {
},
} as AgentStreamEventPayload,
timestamp: new Date(2000),
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
timelineCursor: { epoch: "epoch-1", seq: 2 },
},
],
{ source: "canonical" },
@@ -831,7 +831,7 @@ describe("processTimelineResponse", () => {
expect([...result.tail, ...result.head].filter((item) => item.kind === "todo_list")).toEqual([
expect.objectContaining({
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 1 },
timelineCursor: { epoch: "epoch-1", seq: 2 },
items: [{ text: "Verify hydration", completed: true }],
}),
]);
@@ -847,7 +847,7 @@ describe("processTimelineResponse", () => {
item: { type: "compaction", status: "completed", trigger: "auto", preTokens: 1200 },
} as AgentStreamEventPayload,
timestamp: new Date(2000),
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
timelineCursor: { epoch: "epoch-1", seq: 2 },
},
],
{ source: "canonical" },
@@ -879,7 +879,7 @@ describe("processTimelineResponse", () => {
expect([...result.tail, ...result.head].filter((item) => item.kind === "compaction")).toEqual([
expect.objectContaining({
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 1 },
timelineCursor: { epoch: "epoch-1", seq: 2 },
status: "completed",
trigger: "auto",
preTokens: 1200,
@@ -918,7 +918,7 @@ describe("processTimelineResponse", () => {
messageId: "assistant-live",
text: " continuation",
timestamp: new Date(2001),
timelineCursor: { epoch: "epoch-1", seq: 101, anchorSeq: 101 },
timelineCursor: { epoch: "epoch-1", seq: 101 },
},
],
isInitializing: true,
@@ -946,7 +946,7 @@ describe("processTimelineResponse", () => {
);
expect(assistants).toHaveLength(1);
expect(assistants[0]?.text).toBe("canonical prefix continuation");
expect(assistants[0]?.timelineCursor).toEqual({ epoch: "epoch-1", seq: 101, anchorSeq: 100 });
expect(assistants[0]?.timelineCursor).toEqual({ epoch: "epoch-1", seq: 101 });
});
it("keeps assistant segments separate when a live tool sits between them", () => {
@@ -963,12 +963,12 @@ describe("processTimelineResponse", () => {
}).item,
} as AgentStreamEventPayload,
timestamp: new Date(2101),
timelineCursor: { epoch: "epoch-1", seq: 101, anchorSeq: 101 },
timelineCursor: { epoch: "epoch-1", seq: 101 },
},
{
event: makeAssistantTimelineEvent("after tool", messageId),
timestamp: new Date(2102),
timelineCursor: { epoch: "epoch-1", seq: 102, anchorSeq: 102 },
timelineCursor: { epoch: "epoch-1", seq: 102 },
},
],
{ source: "canonical" },
@@ -1019,7 +1019,7 @@ describe("processTimelineResponse", () => {
id: "assistant-live",
text: "canonical prefix continuation",
timestamp: new Date(2001),
timelineCursor: { epoch: "epoch-1", seq: 101, anchorSeq: 101 },
timelineCursor: { epoch: "epoch-1", seq: 101 },
},
],
isInitializing: true,
@@ -1038,7 +1038,7 @@ describe("processTimelineResponse", () => {
);
expect(assistants).toHaveLength(1);
expect(assistants[0]?.text).toBe("canonical prefix continuation");
expect(assistants[0]?.timelineCursor).toEqual({ epoch: "epoch-1", seq: 101, anchorSeq: 100 });
expect(assistants[0]?.timelineCursor).toEqual({ epoch: "epoch-1", seq: 101 });
});
it("keeps a canonical live user row newer than the bootstrap page", () => {
@@ -1060,7 +1060,7 @@ describe("processTimelineResponse", () => {
});
expect(live.head[0]).toMatchObject({
kind: "user_message",
timelineCursor: { epoch: "epoch-1", seq: 101, anchorSeq: 101 },
timelineCursor: { epoch: "epoch-1", seq: 101 },
});
const result = processTimelineResponse({
@@ -1123,7 +1123,7 @@ describe("processTimelineResponse", () => {
kind: "user_message",
clientMessageId: "client-message-1",
messageId: "provider-message-1",
timelineCursor: { epoch: "epoch-1", seq: 51, anchorSeq: 51 },
timelineCursor: { epoch: "epoch-1", seq: 51 },
});
});
@@ -2808,7 +2808,7 @@ describe("processTimelineResponse", () => {
id: "newest",
text: "newest",
timestamp: new Date(1000),
timelineCursor: { epoch: "epoch-1", seq: 100, anchorSeq: 100 },
timelineCursor: { epoch: "epoch-1", seq: 100 },
},
makeSubmittedUserMessage("pending submission", "pending-submission"),
],
@@ -2886,14 +2886,14 @@ describe("processTimelineResponse", () => {
id: "oldest",
text: "oldest",
timestamp: new Date(1000),
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
timelineCursor: { epoch: "epoch-1", seq: 1 },
},
{
kind: "user_message",
id: "newest",
text: "newest",
timestamp: new Date(100_000),
timelineCursor: { epoch: "epoch-1", seq: 100, anchorSeq: 100 },
timelineCursor: { epoch: "epoch-1", seq: 100 },
},
];
@@ -2935,7 +2935,7 @@ describe("processTimelineResponse", () => {
id: "newest",
text: "newest",
timestamp: new Date(100_000),
timelineCursor: { epoch: "epoch-1", seq: 100, anchorSeq: 100 },
timelineCursor: { epoch: "epoch-1", seq: 100 },
},
...(lane === "tail" ? [pending] : []),
],
@@ -2976,13 +2976,9 @@ describe("processTimelineResponse", () => {
{
text: "local pending prompt",
messageId: "canonical-message",
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
},
{
text: "newest",
messageId: undefined,
timelineCursor: { epoch: "epoch-1", seq: 100, anchorSeq: 100 },
timelineCursor: { epoch: "epoch-1", seq: 1 },
},
{ text: "newest", messageId: undefined, timelineCursor: { epoch: "epoch-1", seq: 100 } },
],
head: [],
acknowledgedClientMessageIds: [clientMessageId],
@@ -2996,7 +2992,7 @@ describe("processTimelineResponse", () => {
{
event: makeToolCallTimelineEvent("call-1"),
timestamp: new Date(500),
timelineCursor: { epoch: "epoch-1", seq: 500, anchorSeq: 500 },
timelineCursor: { epoch: "epoch-1", seq: 500 },
},
],
{ source: "canonical" },
@@ -3042,7 +3038,7 @@ describe("processTimelineResponse", () => {
{
callId: "call-1",
status: "completed",
timelineCursor: { epoch: "epoch-1", seq: 500, anchorSeq: 1 },
timelineCursor: { epoch: "epoch-1", seq: 500 },
},
]);
});
@@ -3054,7 +3050,7 @@ describe("processTimelineResponse", () => {
...makeAssistantItem("projected response", "loaded-assistant"),
messageId: "assistant-message",
timestamp,
timelineCursor: { epoch: "epoch-1", seq: 500, anchorSeq: 500 },
timelineCursor: { epoch: "epoch-1", seq: 500 },
},
];
const result = processTimelineResponse({
@@ -3104,7 +3100,7 @@ describe("processTimelineResponse", () => {
id: "loaded-assistant",
text: "projected response",
messageId: "assistant-message",
timelineCursor: { epoch: "epoch-1", seq: 500, anchorSeq: 1 },
timelineCursor: { epoch: "epoch-1", seq: 500 },
},
]);
});
@@ -3116,7 +3112,7 @@ describe("processTimelineResponse", () => {
id: "current-200",
text: "current-200",
timestamp: new Date(3200),
timelineCursor: { epoch: "epoch-1", seq: 200, anchorSeq: 200 },
timelineCursor: { epoch: "epoch-1", seq: 200 },
},
];
const existingCursor: TimelineCursor = {
@@ -3223,7 +3219,7 @@ describe("processTimelineResponse", () => {
const currentTail = [
{
...makeAssistantItem("newer chunk", "assistant-newer"),
timelineCursor: { epoch: "epoch-1", seq: 3, anchorSeq: 3 },
timelineCursor: { epoch: "epoch-1", seq: 3 },
},
];
const existingCursor: TimelineCursor = {
@@ -3250,7 +3246,7 @@ describe("processTimelineResponse", () => {
expect(result.tail[0]).toEqual(
expect.objectContaining({
id: "assistant-newer",
timelineCursor: { epoch: "epoch-1", seq: 3, anchorSeq: 3 },
timelineCursor: { epoch: "epoch-1", seq: 3 },
}),
);
expect(result.cursor).toEqual({
@@ -3690,7 +3686,7 @@ describe("processAgentStreamEvent", () => {
expect.objectContaining({
kind: "assistant_message",
text: "[System Error] failed",
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
timelineCursor: { epoch: "timeline-1", seq: 42 },
}),
]);
});
@@ -3937,7 +3933,7 @@ describe("processAgentStreamEvent", () => {
expect(getUserTexts(result.head)).toEqual(["live before bootstrap"]);
expect(result.head[0]).toMatchObject({
kind: "user_message",
timelineCursor: { epoch: "epoch-1", seq: 51, anchorSeq: 51 },
timelineCursor: { epoch: "epoch-1", seq: 51 },
});
expect(result.cursorChanged).toBe(false);
expect(result.cursor).toBeNull();
@@ -3972,7 +3968,7 @@ describe("processAgentStreamEvent", () => {
clientMessageId: "client-message-1",
messageId: "provider-message-1",
text: "submitted before bootstrap",
timelineCursor: { epoch: "epoch-1", seq: 51, anchorSeq: 51 },
timelineCursor: { epoch: "epoch-1", seq: 51 },
}),
]);
});
@@ -4563,279 +4559,6 @@ describe("createAgentStreamReducerQueue", () => {
});
});
// ---------------------------------------------------------------------------
// Conversation rewind: A, B, rewind B, C
// ---------------------------------------------------------------------------
describe("conversation rewind", () => {
const rewindB = { seq: 5, retireFromSeq: 3 };
function loadAB(): { tail: StreamItem[]; head: StreamItem[]; cursor: TimelineCursor } {
const result = processTimelineResponse({
...baseTimelineInput,
isInitializing: true,
hasActiveInitDeferred: true,
payload: {
...baseTimelineInput.payload,
direction: "tail",
window: { minSeq: 1, maxSeq: 4, nextSeq: 5 },
startCursor: { seq: 1 },
endCursor: { seq: 4 },
entries: [
makeTimelineEntry(1, "A", "user_message"),
makeTimelineEntry(2, "reply A"),
makeTimelineEntry(3, "B", "user_message"),
makeTimelineEntry(4, "reply B"),
],
},
});
if (!result.cursor) throw new Error("expected a loaded range");
return { tail: result.tail, head: result.head, cursor: result.cursor };
}
function live(
state: { tail: StreamItem[]; head: StreamItem[]; cursor: TimelineCursor },
events: AgentStreamReducerEvent[],
) {
const result = processAgentStreamEvents({
events,
currentTail: state.tail,
currentHead: state.head,
currentCursor: state.cursor,
hasAuthoritativeBaseline: true,
});
return {
tail: result.tail,
head: result.head,
cursor: result.cursor ?? state.cursor,
sideEffects: result.sideEffects,
};
}
function rewindEvent(retirement: { seq: number; retireFromSeq: number }) {
return {
event: { type: "rewind" as const, retireFromSeq: retirement.retireFromSeq },
seq: retirement.seq,
epoch: "epoch-1",
timestamp: new Date(1000 + retirement.seq),
};
}
const promptC = [
makeStreamReducerEvent(makeTimelineEvent("C", "user_message"), 6),
makeStreamReducerEvent(makeTimelineEvent("reply C"), 7),
];
function conversation(state: { tail: StreamItem[]; head: StreamItem[] }) {
return [...state.tail, ...state.head].map((item) =>
item.kind === "user_message" || item.kind === "assistant_message" ? item.text : item.kind,
);
}
it("retires B in place, keeps A mounted, and shows C once", () => {
const loaded = loadAB();
const [promptA, replyA] = loaded.tail;
const rewound = live(loaded, [rewindEvent(rewindB), ...promptC]);
expect(conversation(rewound)).toEqual(["A", "reply A", "C", "reply C"]);
expect(rewound.tail[0]).toBe(promptA);
expect(rewound.tail[1]).toBe(replyA);
expect(rewound.cursor).toMatchObject({ epoch: "epoch-1", startSeq: 1, endSeq: 7 });
expect(rewound.sideEffects).toEqual([]);
});
it("ignores a duplicate rewind so C is not retired", () => {
const rewound = live(loadAB(), [rewindEvent(rewindB), ...promptC]);
const replayed = live(rewound, [rewindEvent(rewindB)]);
expect(conversation(replayed)).toEqual(["A", "reply A", "C", "reply C"]);
expect(replayed.cursor.endSeq).toBe(7);
});
it("does not let an old page resurrect B after the rewind applied", () => {
const rewound = live(loadAB(), [rewindEvent(rewindB), ...promptC]);
const stale = processTimelineResponse({
...baseTimelineInput,
currentTail: rewound.tail,
currentHead: rewound.head,
currentCursor: rewound.cursor,
payload: {
...baseTimelineInput.payload,
direction: "after",
window: { minSeq: 1, maxSeq: 4, nextSeq: 5 },
startCursor: { seq: 3 },
endCursor: { seq: 4 },
entries: [makeTimelineEntry(3, "B", "user_message"), makeTimelineEntry(4, "reply B")],
},
});
expect(conversation(stale)).toEqual(["A", "reply A", "C", "reply C"]);
expect(stale.cursorChanged).toBe(false);
});
it("drops a late live delivery for the retired range", () => {
const rewound = live(loadAB(), [rewindEvent(rewindB)]);
const late = live(rewound, [makeStreamReducerEvent(makeTimelineEvent("late B"), 4)]);
expect(conversation(late)).toEqual(["A", "reply A"]);
});
it("catches up through a page that only carries the retirement", () => {
const loaded = loadAB();
const caughtUp = processTimelineResponse({
...baseTimelineInput,
currentTail: loaded.tail,
currentHead: loaded.head,
currentCursor: loaded.cursor,
payload: {
...baseTimelineInput.payload,
direction: "after",
window: { minSeq: 1, maxSeq: 5, nextSeq: 6 },
startCursor: { seq: 5 },
endCursor: { seq: 5 },
entries: [],
retirements: [rewindB],
},
});
if (!caughtUp.cursor) throw new Error("expected a loaded range");
expect(conversation(caughtUp)).toEqual(["A", "reply A"]);
expect(caughtUp.cursor.endSeq).toBe(5);
expect(caughtUp.sideEffects).not.toContainEqual(expect.objectContaining({ type: "catch_up" }));
const continued = live({ ...caughtUp, cursor: caughtUp.cursor }, promptC);
expect(conversation(continued)).toEqual(["A", "reply A", "C", "reply C"]);
});
it("converges after reconnect from a resume page that crosses the rewind", () => {
const loaded = loadAB();
const resumed = processTimelineResponse({
...baseTimelineInput,
currentTail: loaded.tail,
currentHead: loaded.head,
currentCursor: loaded.cursor,
payload: {
...baseTimelineInput.payload,
direction: "tail",
window: { minSeq: 1, maxSeq: 7, nextSeq: 8 },
startCursor: { seq: 1 },
endCursor: { seq: 7 },
entries: [
makeTimelineEntry(1, "A", "user_message"),
makeTimelineEntry(2, "reply A"),
makeTimelineEntry(6, "C", "user_message"),
makeTimelineEntry(7, "reply C"),
],
retirements: [rewindB],
},
});
expect(conversation(resumed)).toEqual(["A", "reply A", "C", "reply C"]);
expect(resumed.tail[0]).toBe(loaded.tail[0]);
expect(resumed.cursor).toMatchObject({ endSeq: 7 });
});
it("recovers a rewind that skips past the loaded end", () => {
const loaded = loadAB();
const gapped = live(loaded, [rewindEvent({ seq: 9, retireFromSeq: 3 })]);
expect(conversation(gapped)).toEqual(["A", "reply A", "B", "reply B"]);
expect(gapped.sideEffects).toEqual([
{ type: "catch_up", cursor: { epoch: "epoch-1", endSeq: 4 } },
]);
});
it("keeps an A row whose late update carries a seq inside B's range", () => {
const loaded = loadAB();
const [promptA, replyA, ...rest] = loaded.tail;
const lateTool = hydrateStreamState(
[
{
event: makeToolCallTimelineEvent("call-a"),
timestamp: new Date(1002),
timelineCursor: { epoch: "epoch-1", seq: 4, anchorSeq: 2 },
},
],
{ source: "canonical" },
);
const state = { ...loaded, tail: [promptA, replyA, ...lateTool, ...rest] };
const rewound = live(state, [rewindEvent(rewindB)]);
expect(conversation(rewound)).toEqual(["A", "reply A", "tool_call"]);
});
it("keeps a tool that started before B when B's prompt is not loaded and the tool updated after B", () => {
const toolA = {
...makeToolCallTimelineEntry(2, "call-a", "completed", {
type: "read",
filePath: "/tmp/a.ts",
}),
seqEnd: 6,
sourceSeqRanges: [
{ startSeq: 2, endSeq: 2 },
{ startSeq: 6, endSeq: 6 },
],
};
const loaded = processTimelineResponse({
...baseTimelineInput,
isInitializing: true,
hasActiveInitDeferred: true,
payload: {
...baseTimelineInput.payload,
direction: "tail",
window: { minSeq: 1, maxSeq: 6, nextSeq: 7 },
startCursor: { seq: 1 },
endCursor: { seq: 6 },
entries: [makeTimelineEntry(1, "A", "user_message"), toolA],
},
});
if (!loaded.cursor) throw new Error("expected a loaded range");
const rewound = live({ tail: loaded.tail, head: loaded.head, cursor: loaded.cursor }, [
rewindEvent({ seq: 7, retireFromSeq: 3 }),
]);
expect(conversation(rewound)).toEqual(["A", "tool_call"]);
});
it("keeps C from the live overlay when the first page brings the retirement C followed", () => {
const overlay = processAgentStreamEvents({
events: [rewindEvent(rewindB), ...promptC],
currentTail: [],
currentHead: [],
currentCursor: undefined,
hasAuthoritativeBaseline: false,
});
const initialized = processTimelineResponse({
...baseTimelineInput,
isInitializing: true,
hasActiveInitDeferred: true,
currentTail: overlay.tail,
currentHead: overlay.head,
payload: {
...baseTimelineInput.payload,
direction: "tail",
window: { minSeq: 1, maxSeq: 5, nextSeq: 6 },
startCursor: { seq: 1 },
endCursor: { seq: 5 },
entries: [makeTimelineEntry(1, "A", "user_message"), makeTimelineEntry(2, "reply A")],
retirements: [rewindB],
},
});
expect(conversation(initialized)).toEqual(["A", "reply A", "C", "reply C"]);
});
});
describe("turn metrics", () => {
const metrics = [
{ label: "Model", value: "opus" },
@@ -5093,30 +4816,4 @@ describe("turn metrics", () => {
expect(repeated.tail).toBe(first.tail);
});
it("stamps turn metrics carried on a live timeline event appended by reload", () => {
const result = processAgentStreamEvents({
events: [
makeStreamReducerEvent(makeTimelineEvent("question", "user_message"), 1),
makeStreamReducerEvent(
{
type: "timeline",
provider: "claude",
item: { type: "assistant_message", text: "Appended reply." },
turnMetrics: metrics,
},
2,
),
],
currentTail: [],
currentHead: [],
currentCursor: { epoch: "epoch-1", startSeq: 0, endSeq: 0 },
hasAuthoritativeBaseline: true,
});
expect(metricsByKind([...result.tail, ...result.head])).toEqual([
{ kind: "user_message", turnMetrics: undefined },
{ kind: "assistant_message", turnMetrics: metrics },
]);
});
});
@@ -1,13 +1,7 @@
import type { AgentMetric, AgentTimelineItem } from "@getpaseo/protocol/agent-types";
import type { AgentStreamEventPayload } from "@getpaseo/protocol/messages";
import { selectAgentTimelineState, useSessionStore } from "@/stores/session-store";
import {
advanceTimelinePosition,
type AssistantMessageItem,
type StreamItem,
type TimelinePosition,
type TodoEntry,
} from "@/types/stream";
import type { AssistantMessageItem, StreamItem, TodoEntry } from "@/types/stream";
import type { TurnLivenessTransition } from "@/timeline/turn-liveness";
import { stampTimelineTurnMetrics } from "@/timeline/turn-metrics";
import {
@@ -40,7 +34,6 @@ export interface TimelineCursor {
epoch: string;
startSeq: number;
endSeq: number;
activeSegmentStartSeq?: number;
retainedRanges?: TimelineLoadedRange[];
}
@@ -79,64 +72,6 @@ interface TimelineSeqRange {
endSeq: number;
}
/** A conversation rewind took the rows anchored in `[retireFromSeq, seq)` out of the conversation. */
export interface TimelineRetirement {
seq: number;
retireFromSeq: number;
}
/** The live form of a retirement; it is sequenced with the stream events around it. */
export interface TimelineRewindEvent {
type: "rewind";
retireFromSeq: number;
}
/**
* Drops the rows a retirement took out of the conversation: those anchored in
* `[retireFromSeq, seq)`. Anchors do not move on update, so an earlier row updated after the
* rewound prompt stays, and a row that started after the retirement stays. Items without a
* timeline position are local sends the daemon has not echoed and stay.
*/
function retireRewoundStreamItems(input: {
tail: StreamItem[];
head: StreamItem[];
epoch: string;
retirement: TimelineRetirement;
}): { tail: StreamItem[]; head: StreamItem[] } {
const { tail, head, epoch, retirement } = input;
const isRetired = (item: StreamItem) => {
const position = item.timelineCursor;
return (
position?.epoch === epoch &&
position.anchorSeq >= retirement.retireFromSeq &&
position.anchorSeq < retirement.seq
);
};
const nextTail = tail.filter((item) => !isRetired(item));
const nextHead = head.filter((item) => !isRetired(item));
return {
tail: nextTail.length === tail.length ? tail : nextTail,
head: nextHead.length === head.length ? head : nextHead,
};
}
/**
* Applies a page's retirements to what this client holds. The page's own entries are already
* active. Applying a retirement twice changes nothing, since its range is bounded.
*/
function retireForPage(input: {
payload: ProcessTimelineResponseInput["payload"];
tail: StreamItem[];
head: StreamItem[];
}): { tail: StreamItem[]; head: StreamItem[] } {
const { payload } = input;
let held = { tail: input.tail, head: input.head };
for (const retirement of payload.retirements ?? []) {
held = retireRewoundStreamItems({ ...held, epoch: payload.epoch, retirement });
}
return held;
}
function mergeTimelineCoverage(
current: TimelineCursor,
added: TimelineLoadedRange,
@@ -165,9 +100,6 @@ function mergeTimelineCoverage(
epoch: current.epoch,
startSeq: contiguous.startSeq,
endSeq: contiguous.endSeq,
...(current.activeSegmentStartSeq !== undefined
? { activeSegmentStartSeq: current.activeSegmentStartSeq }
: {}),
...(retainedRanges.length > 0 ? { retainedRanges } : {}),
};
}
@@ -176,8 +108,7 @@ function timelineCursorEquals(left: TimelineCursor, right: TimelineCursor): bool
if (
left.epoch !== right.epoch ||
left.startSeq !== right.startSeq ||
left.endSeq !== right.endSeq ||
(left.activeSegmentStartSeq ?? 0) !== (right.activeSegmentStartSeq ?? 0)
left.endSeq !== right.endSeq
) {
return false;
}
@@ -221,8 +152,6 @@ export interface ProcessTimelineResponseInput {
hasNewer: boolean;
hasOlder: boolean;
mergeWindow?: boolean;
retirements?: TimelineRetirement[];
activeSegmentStartSeq?: number;
};
currentTail: StreamItem[];
currentHead: StreamItem[];
@@ -467,7 +396,7 @@ function mergeTimelineWindow(args: {
toHydratedEvents: (units: TimelineUnit[]) => Array<{
event: AgentStreamEventPayload;
timestamp: Date;
timelineCursor: TimelinePosition;
timelineCursor: { epoch: string; seq: number };
}>;
}): TimelinePathResult {
const { timelineUnits, payload, currentTail, currentHead, currentCursor, toHydratedEvents } =
@@ -831,7 +760,7 @@ function replaceLiveAssistantWithProjectedText(params: {
head: StreamItem[];
event: AgentStreamEventPayload;
timestamp: Date;
timelineCursor: TimelinePosition;
timelineCursor: { epoch: string; seq: number };
}): StreamItem[] | null {
const { head, event, timestamp, timelineCursor } = params;
if (event.type !== "timeline" || event.item.type !== "assistant_message") {
@@ -850,7 +779,7 @@ function replaceLiveAssistantWithProjectedText(params: {
...current,
text: event.item.text,
timestamp,
...advanceTimelinePosition(current.timelineCursor, timelineCursor),
timelineCursor,
};
return next;
}
@@ -900,7 +829,7 @@ function reconcileOverlappingProjectedAssistant(params: {
...(messageId !== undefined ? { messageId } : {}),
text: projectedText,
timestamp: unit.timestamp,
timelineCursor: { epoch: params.epoch, seq: unit.seqEnd, anchorSeq: unit.seq },
timelineCursor: { epoch: params.epoch, seq: unit.seqEnd },
};
const replaceMatch = (items: StreamItem[], index: number) => {
const next = [...items];
@@ -1017,8 +946,8 @@ function applyCanonicalForwardUnit(params: {
unit: TimelineUnit;
epoch: string;
}): { tail: StreamItem[]; head: StreamItem[]; acknowledgedClientMessageIds: string[] } {
const { event, timestamp, seq, seqEnd } = params.unit;
const timelineCursor: TimelinePosition = { epoch: params.epoch, seq: seqEnd, anchorSeq: seq };
const { event, timestamp, seqEnd } = params.unit;
const timelineCursor = { epoch: params.epoch, seq: seqEnd };
if (event.type === "timeline" && event.item.type === "user_message") {
const applied = applyStreamEvent({
tail: params.tail,
@@ -1217,10 +1146,10 @@ function applyAcceptedTimelinePage(input: {
});
}
const olderTail = hydrateStreamState(
acceptedUnits.map(({ event, timestamp, seq, seqEnd }) => ({
acceptedUnits.map(({ event, timestamp, seqEnd }) => ({
event,
timestamp,
timelineCursor: { epoch: payload.epoch, seq: seqEnd, anchorSeq: seq },
timelineCursor: { epoch: payload.epoch, seq: seqEnd },
})),
{
source: "canonical",
@@ -1252,12 +1181,7 @@ function applyTimelineIncrementalPath(args: {
let cursorChanged = false;
const sideEffects: TimelineReducerSideEffect[] = [];
// A forward page of retirements alone still advances the loaded end.
if (
timelineUnits.length === 0 &&
payload.direction !== "before" &&
(payload.retirements?.length ?? 0) === 0
) {
if (timelineUnits.length === 0 && payload.direction !== "before") {
return {
tail: currentTail,
head: currentHead,
@@ -1310,62 +1234,13 @@ function applyTimelineIncrementalPath(args: {
};
}
function mergeResponseActiveSegmentCursor(
cursor: TimelineCursor | null | undefined,
cursorChanged: boolean,
currentCursor: TimelineCursor | undefined,
incomingActiveSegmentStartSeq: number | undefined,
): { cursor: TimelineCursor | null | undefined; cursorChanged: boolean } {
if (!cursor) {
return { cursor, cursorChanged };
}
const prevSegment =
currentCursor?.epoch === cursor.epoch ? (currentCursor.activeSegmentStartSeq ?? 0) : 0;
const incomingSegment = incomingActiveSegmentStartSeq ?? cursor.activeSegmentStartSeq ?? 0;
const mergedSegment = Math.max(prevSegment, incomingSegment);
if (mergedSegment > 0 && cursor.activeSegmentStartSeq !== mergedSegment) {
return { cursor: { ...cursor, activeSegmentStartSeq: mergedSegment }, cursorChanged: true };
}
return { cursor, cursorChanged };
}
function advanceLiveActiveSegmentCursor(input: {
shouldApply: boolean;
event: AgentStreamEventPayload;
seq: number | undefined;
epoch: string | undefined;
nextCursor: TimelineCursor | null;
cursorChanged: boolean;
currentCursor: TimelineCursor | undefined;
}): { cursor: TimelineCursor | null; cursorChanged: boolean } {
const { shouldApply, event, seq, epoch, nextCursor, cursorChanged, currentCursor } = input;
if (
!shouldApply ||
event.type !== "timeline" ||
event.item.type !== "provider_switch" ||
typeof seq !== "number" ||
typeof epoch !== "string"
) {
return { cursor: nextCursor, cursorChanged };
}
const baseCursor =
nextCursor ??
(currentCursor?.epoch === epoch ? currentCursor : { epoch, startSeq: seq, endSeq: seq });
const nextActiveSegment = Math.max(baseCursor.activeSegmentStartSeq ?? 0, seq);
if (baseCursor.activeSegmentStartSeq !== nextActiveSegment || nextCursor === null) {
return {
cursor: { ...baseCursor, activeSegmentStartSeq: nextActiveSegment },
cursorChanged: true,
};
}
return { cursor: nextCursor, cursorChanged };
}
export function processTimelineResponse(
input: ProcessTimelineResponseInput,
): ProcessTimelineResponseOutput {
const {
payload,
currentTail,
currentHead,
currentCursor,
isInitializing,
hasActiveInitDeferred,
@@ -1379,8 +1254,8 @@ export function processTimelineResponse(
if (payload.error) {
return {
commit: "apply",
tail: input.currentTail,
head: input.currentHead,
tail: currentTail,
head: currentHead,
cursor: currentCursor,
cursorChanged: false,
older: "unchanged",
@@ -1392,13 +1267,6 @@ export function processTimelineResponse(
};
}
// Entries are already free of retired rows; the retirements apply to what this client holds.
const { tail: currentTail, head: currentHead } = retireForPage({
payload,
tail: input.currentTail,
head: input.currentHead,
});
// ------------------------------------------------------------------
// Convert entries to timeline units
// ------------------------------------------------------------------
@@ -1424,12 +1292,12 @@ export function processTimelineResponse(
): Array<{
event: AgentStreamEventPayload;
timestamp: Date;
timelineCursor: TimelinePosition;
timelineCursor: { epoch: string; seq: number };
}> =>
units.map(({ event, timestamp, seq, seqEnd }) => ({
units.map(({ event, timestamp, seqEnd }) => ({
event,
timestamp,
timelineCursor: { epoch: payload.epoch, seq: seqEnd, anchorSeq: seq },
timelineCursor: { epoch: payload.epoch, seq: seqEnd },
}));
// ------------------------------------------------------------------
@@ -1516,12 +1384,8 @@ export function processTimelineResponse(
const nextTail = stampTimelineTurnMetrics(timelineResult.tail, payload.epoch, pageEntries);
const nextHead = stampTimelineTurnMetrics(timelineResult.head, payload.epoch, pageEntries);
const { cursor: nextCursor, cursorChanged } = mergeResponseActiveSegmentCursor(
timelineResult.cursor,
timelineResult.cursorChanged,
currentCursor,
payload.activeSegmentStartSeq,
);
const nextCursor = timelineResult.cursor;
const cursorChanged = timelineResult.cursorChanged;
sideEffects.push(...timelineResult.sideEffects);
// ------------------------------------------------------------------
@@ -1568,7 +1432,7 @@ export function processTimelineResponse(
// ---------------------------------------------------------------------------
export interface ProcessAgentStreamEventInput {
event: AgentStreamEventPayload | TimelineRewindEvent;
event: AgentStreamEventPayload;
seq: number | undefined;
epoch: string | undefined;
currentTail: StreamItem[];
@@ -1591,7 +1455,7 @@ export interface ProcessAgentStreamEventOutput {
}
export interface AgentStreamReducerEvent {
event: AgentStreamEventPayload | TimelineRewindEvent;
event: AgentStreamEventPayload;
seq: number | undefined;
epoch: string | undefined;
timestamp: Date;
@@ -1709,70 +1573,11 @@ function processTimelineSequencingGate(input: {
};
}
/**
* Applies a live rewind in sequence with the stream. One that does not follow the loaded end is
* stale (already applied, or older than a page this client took) or leaves a gap to catch up.
*/
function processTimelineRewind(
input: ProcessAgentStreamEventInput & { event: TimelineRewindEvent },
): ProcessAgentStreamEventOutput {
const { event, seq, epoch, currentTail, currentHead, currentCursor } = input;
const unchanged: ProcessAgentStreamEventOutput = {
tail: currentTail,
head: currentHead,
changedTail: false,
changedHead: false,
cursor: null,
cursorChanged: false,
acknowledgedClientMessageIds: [],
sideEffects: [],
};
if (seq === undefined || epoch === undefined) return unchanged;
const decision =
input.hasAuthoritativeBaseline === false
? "overlay"
: classifySessionTimelineSeq({
cursor: currentCursor
? { epoch: currentCursor.epoch, endSeq: currentCursor.endSeq }
: null,
epoch,
seq,
});
if (decision === "gap" && currentCursor) {
return {
...unchanged,
sideEffects: [
{ type: "catch_up", cursor: { epoch: currentCursor.epoch, endSeq: currentCursor.endSeq } },
],
};
}
if (decision !== "accept" && decision !== "init" && decision !== "overlay") return unchanged;
const retired = retireRewoundStreamItems({
tail: currentTail,
head: currentHead,
epoch,
retirement: { seq, retireFromSeq: event.retireFromSeq },
});
let cursor: TimelineCursor | null = null;
if (decision === "accept" && currentCursor) cursor = { ...currentCursor, endSeq: seq };
if (decision === "init") cursor = { epoch, startSeq: seq, endSeq: seq };
return {
...unchanged,
tail: retired.tail,
head: retired.head,
changedTail: retired.tail !== currentTail,
changedHead: retired.head !== currentHead,
cursor,
cursorChanged: cursor !== null,
};
}
export function processAgentStreamEvent(
input: ProcessAgentStreamEventInput,
): ProcessAgentStreamEventOutput {
const event = input.event;
if (event.type === "rewind") return processTimelineRewind({ ...input, event });
const {
event,
seq,
epoch,
currentTail,
@@ -1791,7 +1596,7 @@ export function processAgentStreamEvent(
});
const timelineCursor =
event.type === "timeline" && seq !== undefined && epoch !== undefined
? { epoch, seq, anchorSeq: seq }
? { epoch, seq }
: undefined;
// ------------------------------------------------------------------
// Apply stream event to tail/head
@@ -1840,23 +1645,14 @@ export function processAgentStreamEvent(
});
}
const { tail, head, changedTail, changedHead } = streamResult;
const { cursor: nextTimelineCursor, cursorChanged } = advanceLiveActiveSegmentCursor({
shouldApply: sequencing.shouldApplyStreamEvent,
event,
seq,
epoch,
nextCursor: sequencing.nextTimelineCursor,
cursorChanged: sequencing.cursorChanged,
currentCursor,
});
return {
tail,
head,
changedTail,
changedHead,
cursor: nextTimelineCursor,
cursorChanged,
cursor: sequencing.nextTimelineCursor,
cursorChanged: sequencing.cursorChanged,
acknowledgedClientMessageIds: streamResult.acknowledgedClientMessageIds ?? [],
...(sequencing.shouldApplyStreamEvent && event.type === "timeline" && event.item.type === "todo"
? { taskSnapshot: event.item.items }
@@ -2114,10 +1910,6 @@ export function createSessionAgentStreamReducerQueue(
};
},
commit: (agentId, result, events) => {
for (const { event, seq, epoch } of events) {
if (event.type !== "rewind" || seq === undefined || epoch === undefined) continue;
useSessionStore.getState().recordAgentTimelineRewind(serverId, agentId, { epoch, seq });
}
if (
result.changedTail ||
result.changedHead ||
@@ -208,6 +208,7 @@ class TimelineWorld {
},
onCatchUpOwed: () => undefined,
onCatchUpSettled: () => undefined,
isArchived: () => false,
prepare: async (agentId) => {
this.cacheRequests.push(agentId);
this.cacheRequestWaiters.shift()?.(agentId);
+114 -56
View File
@@ -11,6 +11,7 @@ import {
useSessionStore,
type AgentTimelineCursorState,
type AgentTimelineState,
type SessionState,
} from "@/stores/session-store";
import { useCreateFlowStore } from "@/stores/create-flow-store";
import type { AgentSnapshotPayload, SessionOutboundMessage } from "@getpaseo/protocol/messages";
@@ -102,6 +103,8 @@ export interface TimelineReplica {
timelineUpdated(agentId: string): void;
catchUpOwed(agentId: string): void;
catchUpSettled(agentId: string): void;
/** Forgets a released chat's cached range, so showing it again reads the cache afresh. */
release(agentId: string): void;
}
class TimelineReplicaOwner implements TimelineReplica {
@@ -187,6 +190,10 @@ class TimelineReplicaOwner implements TimelineReplica {
if (this.preparations.has(agentId)) this.settledDuringPreparation.add(agentId);
useSessionStore.getState().setAgentTimelineUnsettledTurn(this.serverId, agentId, null);
}
release(agentId: string): void {
this.cachedRanges.delete(agentId);
}
}
export function createTimelineReplica(input: {
@@ -237,13 +244,6 @@ function commitProcessedTimeline(input: {
const agentId = payload.agentId;
const store = useSessionStore.getState();
if (result.commit !== "discard") {
const latestRewindSeq = Math.max(...(payload.retirements ?? []).map(({ seq }) => seq));
if (Number.isFinite(latestRewindSeq)) {
store.recordAgentTimelineRewind(serverId, agentId, {
epoch: payload.epoch,
seq: latestRewindSeq,
});
}
store.applyAgentTimelineResponseState(serverId, agentId, {
items: result.tail,
head: result.head,
@@ -382,6 +382,11 @@ function buildCurrentTimelinePage(
export interface ViewedTimelineSyncPorts {
prepare(agentId: string): Promise<void>;
/**
* Whether the agent left the active list: it, or its workspace, is archived. A hidden chat
* of an archived agent leaves the opened chats, so showing it again reads it afresh.
*/
isArchived(agentId: string): boolean;
replaceDemandedAgentIds(agentIds: string[]): void;
/** Whether the daemon answers with each cursor's freshness in the subscribe response. */
canCheckFreshness(): boolean;
@@ -454,9 +459,17 @@ export interface ViewedTimelineSync extends ViewedTimelineUiBridge {
dispose(): void;
}
/** What the timeline owner needs from membership beyond the UI-facing surface. */
export interface ViewedTimelineMembership extends ViewedTimelineSync {
isVisible(agentId: string): boolean;
/** Re-reads `isArchived` for the opened chats, after the active list changed. */
archiveChanged(): void;
}
export type ViewedTimelineOwnerPorts = Omit<
ViewedTimelineSyncPorts,
| "prepare"
| "isArchived"
| "replaceDemandedAgentIds"
| "onCatchUpEnded"
| "onCatchUpOwed"
@@ -464,14 +477,8 @@ export type ViewedTimelineOwnerPorts = Omit<
| "applyCurrentTimeline"
>;
/**
* `stale`: the page was served before a rewind this client already applied, so it can hold rows
* that rewind retired. Nothing was applied; request the page again.
*/
export type TimelineResponseOutcome = "applied" | "stale";
export interface ViewedTimelineOwner extends ViewedTimelineSync {
applyTimelineResponse(payload: TimelineResponsePayload): TimelineResponseOutcome;
applyTimelineResponse(payload: TimelineResponsePayload): void;
/**
* Accepts one live stream event. Content is coalesced to the next frame; a turn boundary
* commits the turn's queued content before its liveness changes, so the view never shows
@@ -481,37 +488,6 @@ export interface ViewedTimelineOwner extends ViewedTimelineSync {
flushStreamAgent(agentId: string): void;
}
/**
* The latest retirement each chat has seen, live or on a page. Tail, older and prompt-jump pages
* are served from active rows at one moment; one served before that retirement can still hold the
* rows it retired, and has no retirement to drop them with. Forward pages are sequenced against
* the loaded end instead, so they are never stale here.
*/
function createRetirementHighWater() {
const latest = new Map<string, { epoch: string; seq: number }>();
function note(agentId: string, retirement: { epoch: string; seq: number }): void {
const current = latest.get(agentId);
if (current?.epoch === retirement.epoch && current.seq >= retirement.seq) return;
latest.set(agentId, retirement);
}
return {
note,
notePage(payload: TimelineResponsePayload): void {
for (const retirement of payload.retirements ?? []) {
note(payload.agentId, { epoch: payload.epoch, seq: retirement.seq });
}
},
servedBefore(payload: TimelineResponsePayload): boolean {
const known = latest.get(payload.agentId);
return (
payload.direction !== "after" &&
known?.epoch === payload.epoch &&
payload.window.maxSeq < known.seq
);
},
};
}
export function createViewedTimelineOwner(input: {
serverId: string;
replica: TimelineReplica;
@@ -521,9 +497,14 @@ export function createViewedTimelineOwner(input: {
ports: ViewedTimelineOwnerPorts;
}): ViewedTimelineOwner {
const forcedTailReplacements = new Set<string>();
const retirements = createRetirementHighWater();
const isArchived = (agentId: string) =>
isAgentArchived(useSessionStore.getState().sessions[input.serverId], agentId);
// Active chats stay resident while hidden so switching back needs no fetch. An archived
// chat is resident only while it is shown, as when it is open from History.
const isResident = (agentId: string) => sync.isVisible(agentId) || !isArchived(agentId);
const sync = createViewedTimelineSync({
...input.ports,
isArchived,
fetchLatestTail: async (agentId) => {
forcedTailReplacements.add(agentId);
try {
@@ -532,7 +513,11 @@ export function createViewedTimelineOwner(input: {
forcedTailReplacements.delete(agentId);
}
},
prepare: (agentId) => input.replica.prepare(agentId),
prepare: async (agentId) => {
await input.replica.prepare(agentId);
// A cache read that lands after its archived chat was left paints a chat nobody shows.
releaseHiddenArchivedTimelines();
},
readCursor: (agentId) => input.replica.readCursor(agentId) ?? input.ports.readCursor(agentId),
replaceDemandedAgentIds: input.replaceDemandedAgentIds,
applyCurrentTimeline: (agentId) => {
@@ -559,11 +544,40 @@ export function createViewedTimelineOwner(input: {
recoverTimelineGap: (agentId, cursor) => sync.recoverGap(agentId, cursor),
onCommitted: (agentId) => input.replica.timelineUpdated(agentId),
});
const releaseHiddenArchivedTimelines = () => {
const session = useSessionStore.getState().sessions[input.serverId];
if (!session) return;
for (const agentId of selectResidentTimelineAgentIds(session)) {
if (isResident(agentId)) continue;
streamQueue.flushAgent(agentId);
input.replica.release(agentId);
useSessionStore.getState().releaseAgentTimeline(input.serverId, agentId);
}
};
// Archiving an agent or its workspace reaches this host as the agent leaving the active list.
let observedSession = useSessionStore.getState().sessions[input.serverId];
const stopObservingArchive = useSessionStore.subscribe((state) => {
const session = state.sessions[input.serverId];
const changed =
session?.agents !== observedSession?.agents ||
session?.agentDetails !== observedSession?.agentDetails ||
session?.hasHydratedAgents !== observedSession?.hasHydratedAgents ||
session?.workspaces !== observedSession?.workspaces ||
session?.hasHydratedWorkspaces !== observedSession?.hasHydratedWorkspaces;
observedSession = session;
if (!changed) return;
sync.archiveChanged();
releaseHiddenArchivedTimelines();
});
return {
...sync,
replaceVisibleAgentIds(sourceId, agentIds) {
sync.replaceVisibleAgentIds(sourceId, agentIds);
releaseHiddenArchivedTimelines();
},
applyTimelineResponse(receivedPayload) {
if (retirements.servedBefore(receivedPayload)) return "stale";
retirements.notePage(receivedPayload);
// A read that answers after its archived chat was released must not bring it back.
if (!isResident(receivedPayload.agentId)) return;
const payload = consumeForcedTimelineTailReplacement(receivedPayload, forcedTailReplacements);
const accepted = applyAuthoritativeTimelineResponse({
serverId: input.serverId,
@@ -573,12 +587,9 @@ export function createViewedTimelineOwner(input: {
drainQueuedAgentMessage: input.drainQueuedAgentMessage,
});
if (accepted) input.replica.timelineUpdated(payload.agentId);
return "applied";
},
applyStreamEvent(agentId, event) {
if (event.event.type === "rewind" && event.epoch !== undefined && event.seq !== undefined) {
retirements.note(agentId, { epoch: event.epoch, seq: event.seq });
}
if (!isResident(agentId)) return;
streamQueue.enqueue(agentId, event);
const turnLiveness = deriveAgentStreamTurnLiveness([event]);
if (turnLiveness.length === 0) return;
@@ -590,12 +601,38 @@ export function createViewedTimelineOwner(input: {
streamQueue.flushAgent(agentId);
},
dispose() {
stopObservingArchive();
streamQueue.dispose({ flush: true });
sync.dispose();
},
};
}
/**
* An agent is archived once the hydrated active list lacks it, its row carries an archive
* timestamp, or the hydrated workspace list lacks its workspace. Workspace archive can leave
* an agent row without a timestamp. Until a list hydrates, it rules nothing out.
*/
function isAgentArchived(session: SessionState | undefined, agentId: string): boolean {
if (!session?.hasHydratedAgents) return false;
const agent = session.agents.get(agentId) ?? session.agentDetails.get(agentId);
if (!agent || agent.archivedAt != null) return true;
return (
session.hasHydratedWorkspaces &&
agent.workspaceId !== undefined &&
!session.workspaces.has(agent.workspaceId)
);
}
function selectResidentTimelineAgentIds(session: SessionState): Set<string> {
return new Set([
...session.agentStreamTail.keys(),
...session.agentStreamHead.keys(),
...session.agentTimelineCursor.keys(),
...session.agentAuthoritativeHistoryApplied.keys(),
]);
}
const MAX_HIDDEN_CATCH_UPS = 2;
type CatchUpStatus = "running" | "complete" | "error";
@@ -659,7 +696,7 @@ function sameAgentIds(left: string[], right: string[]): boolean {
return left.length === right.length && left.every((agentId, index) => agentId === right[index]);
}
export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): ViewedTimelineSync {
export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): ViewedTimelineMembership {
const sources = new Map<string, string[]>();
const catchUps = new Map<string, CatchUpState>();
const catchUpGenerations = new Map<string, number>();
@@ -839,10 +876,12 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
const ensureCacheLoaded = (agentId: string): void => {
if (loadedCache.has(agentId) || cacheLoads.has(agentId)) return;
const load = ports
const load: Promise<void> = ports
.prepare(agentId)
.catch((error) => ports.reportError(error))
.finally(() => {
// A released chat forgot this load; showing it again starts its own.
if (cacheLoads.get(agentId) !== load) return;
cacheLoads.delete(agentId);
loadedCache.add(agentId);
const pending = pendingCatchUps.get(agentId);
@@ -1130,10 +1169,29 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
};
const publishVisibleMembership = () => {
commitDesiredMembership(normalizeAgentIds([...openedAgentIds, ...visibleAgentIds()]));
const visible = visibleAgentIds();
const kept = openedAgentIds.filter(
(agentId) => visible.includes(agentId) || !ports.isArchived(agentId),
);
if (kept.length !== openedAgentIds.length) {
for (const agentId of openedAgentIds) {
if (kept.includes(agentId)) continue;
loadedCache.delete(agentId);
cacheLoads.delete(agentId);
}
openedAgentIds = kept;
}
commitDesiredMembership(normalizeAgentIds([...openedAgentIds, ...visible]));
};
return {
isVisible(agentId) {
for (const agentIds of sources.values()) if (agentIds.includes(agentId)) return true;
return false;
},
archiveChanged() {
publishVisibleMembership();
},
subscribe(listener) {
listeners.add(listener);
return () => listeners.delete(listener);
+3 -7
View File
@@ -1009,7 +1009,7 @@ describe("stream reducer canonical tool calls", () => {
});
it("keeps the timeline position on the whole assistant message", () => {
const timelineCursor = { epoch: "epoch-1", seq: 42, anchorSeq: 42 };
const timelineCursor = { epoch: "epoch-1", seq: 42 };
const result = applyStreamEvent({
tail: [],
head: [],
@@ -1890,7 +1890,7 @@ describe("turn lifecycle events", () => {
new Date("2025-01-01T15:03:11Z"),
{
source: "canonical",
timelineCursor: { epoch: "epoch-1", seq: 42, anchorSeq: 42 },
timelineCursor: { epoch: "epoch-1", seq: 42 },
},
);
@@ -1902,11 +1902,7 @@ describe("turn lifecycle events", () => {
assert.strictEqual(userMessage.messageId, "provider-owned-canonical");
assert.strictEqual(userMessage.text, "Analyze this");
assert.strictEqual(userMessage.timestamp.getTime(), submittedTimestamp.getTime());
assert.deepStrictEqual(userMessage.timelineCursor, {
epoch: "epoch-1",
seq: 42,
anchorSeq: 42,
});
assert.deepStrictEqual(userMessage.timelineCursor, { epoch: "epoch-1", seq: 42 });
assert.deepStrictEqual(userMessage.images, [image]);
assert.deepStrictEqual(userMessage.attachments, [attachment]);
});
+15 -108
View File
@@ -4,7 +4,6 @@ import type {
AgentProvider,
AgentTimelineItem,
JsonValue,
ProviderSwitchContextSummary,
ToolCallDetail,
} from "@getpaseo/protocol/agent-types";
import { timelineItemIdentity } from "@getpaseo/protocol/timeline-identity";
@@ -90,25 +89,9 @@ export type StreamItem =
| TodoListItem
| NotificationItem
| CompactionItem
| ProviderSwitchItem
| PluginTimelineStreamItem
| TurnSummaryItem;
export interface ProviderSwitchItem {
kind: "provider_switch";
id: string;
timelineCursor?: TimelinePosition;
turnId?: string;
timestamp: Date;
fromProvider: AgentProvider;
toProvider: AgentProvider;
fromModel?: string | null;
toModel?: string | null;
fromSessionId?: string | null;
toSessionId?: string | null;
context: ProviderSwitchContextSummary;
}
export type UserMessageImageAttachment = AttachmentMetadata;
export interface UserMessageItem {
@@ -283,7 +266,7 @@ function produceUserMessage(
...presentation,
clientMessageId: incoming.clientMessageId ?? existing.clientMessageId,
messageId: incoming.messageId ?? existing.messageId,
...advanceTimelinePosition(existing.timelineCursor, incoming.timelineCursor),
timelineCursor: incoming.timelineCursor ?? existing.timelineCursor,
});
if (
existing.id === merged.id &&
@@ -499,7 +482,7 @@ function mergeRetainedLifecycleItem(tail: StreamItem[], retained: StreamItem): S
const next = [...tail];
next[tailIndex] = {
...existing,
...advanceTimelinePosition(existing.timelineCursor, retained.timelineCursor),
timelineCursor: retained.timelineCursor,
timestamp: retained.timestamp,
items: retained.items,
};
@@ -516,7 +499,7 @@ function mergeRetainedLifecycleItem(tail: StreamItem[], retained: StreamItem): S
const next = [...tail];
next[tailIndex] = {
...existing,
...advanceTimelinePosition(existing.timelineCursor, retained.timelineCursor),
timelineCursor: retained.timelineCursor,
status: "completed",
trigger: retained.trigger ?? existing.trigger,
preTokens: retained.preTokens ?? existing.preTokens,
@@ -536,10 +519,7 @@ function replaceTimelineIdentityItem(
const existing = items[index];
if (index < 0 || !existing || existing.kind !== "plugin") return null;
const next = [...items];
next[index] = {
...retained,
...advanceTimelinePosition(existing.timelineCursor, retained.timelineCursor),
};
next[index] = retained;
return next;
}
@@ -630,11 +610,7 @@ function preserveReplacementHead(
: `${tailAssistant.text}${liveAssistant.text}`;
const head = [
...unreconciledHead.slice(0, liveAssistantIndex),
{
...liveAssistant,
text,
...advanceTimelinePosition(tailAssistant.timelineCursor, liveAssistant.timelineCursor),
},
{ ...liveAssistant, text },
...unreconciledHead.slice(liveAssistantIndex + 1),
];
return {
@@ -649,13 +625,7 @@ function preserveReplacementHead(
const head = [
...unreconciledHead.slice(0, liveAssistantIndex),
{
...liveAssistant,
text: tailAssistant.text,
...(liveAssistant.timelineCursor
? advanceTimelinePosition(tailAssistant.timelineCursor, liveAssistant.timelineCursor)
: {}),
},
{ ...liveAssistant, text: tailAssistant.text },
...unreconciledHead.slice(liveAssistantIndex + 1),
];
return {
@@ -754,27 +724,7 @@ export interface AssistantMessageItem {
export interface TimelinePosition {
epoch: string;
/** The latest seq that changed this row. */
seq: number;
/** The seq the row started at. Updates never move it; rewinds retire rows by it. */
anchorSeq: number;
}
/**
* The position of a row after an update: it moves to the update's seq and stays anchored where it
* started. Without an incoming position the row keeps the one it has.
*/
export function advanceTimelinePosition(
existing: TimelinePosition | undefined,
incoming: TimelinePosition | undefined,
): { timelineCursor?: TimelinePosition } {
if (!incoming) return existing ? { timelineCursor: existing } : {};
if (!existing || existing.epoch !== incoming.epoch) return { timelineCursor: incoming };
const anchorSeq = Math.min(existing.anchorSeq, incoming.anchorSeq);
if (existing.seq === incoming.seq && existing.anchorSeq === anchorSeq) {
return { timelineCursor: existing };
}
return { timelineCursor: { ...incoming, anchorSeq } };
}
export type ThoughtStatus = "loading" | "ready";
@@ -1033,7 +983,7 @@ function appendAssistantMessage(
...last,
text: `${last.text}${chunk}`,
timestamp,
...advanceTimelinePosition(last.timelineCursor, timelineCursor),
...(timelineCursor ? { timelineCursor } : {}),
};
return [...state.slice(0, -1), updated];
}
@@ -1051,7 +1001,7 @@ function appendAssistantMessage(
...secondLast,
text: `${secondLast.text}${chunk}`,
timestamp,
...advanceTimelinePosition(secondLast.timelineCursor, timelineCursor),
...(timelineCursor ? { timelineCursor } : {}),
};
return [...state.slice(0, -2), updated, last];
}
@@ -1089,7 +1039,7 @@ function appendThought(
if (last && last.kind === "thought" && last.turnId === turnId) {
const updated: ThoughtItem = {
...last,
...advanceTimelinePosition(last.timelineCursor, timelineCursor),
...(timelineCursor ? { timelineCursor } : {}),
text: `${last.text}${chunk}`,
timestamp,
status: "loading",
@@ -1269,7 +1219,7 @@ export function mergeAgentToolCallItem(
return {
...existing,
...advanceTimelinePosition(existing.timelineCursor, timelineCursor),
...(timelineCursor ? { timelineCursor } : {}),
timestamp,
payload: {
source: "agent",
@@ -1375,11 +1325,7 @@ function appendPluginTimelineItem(
const existing = state[existingIndex];
if (!existing || existing.kind !== "plugin") return state;
const next = [...state];
next[existingIndex] = {
...nextItem,
id: existing.id,
...advanceTimelinePosition(existing.timelineCursor, timelineCursor),
};
next[existingIndex] = { ...nextItem, id: existing.id };
return next;
}
@@ -1410,7 +1356,7 @@ function appendTodoList(
const next = [...state];
next[previousIndex] = {
...previous,
...advanceTimelinePosition(previous.timelineCursor, timelineCursor),
...(timelineCursor ? { timelineCursor } : {}),
items: normalizedItems,
timestamp,
};
@@ -1429,7 +1375,7 @@ function appendTodoList(
const next = [...state];
next[next.length - 1] = {
...lastItem,
...advanceTimelinePosition(lastItem.timelineCursor, timelineCursor),
...(timelineCursor ? { timelineCursor } : {}),
items: normalizedItems,
activity: { type: "created", count: normalizedItems.length },
timestamp,
@@ -1574,7 +1520,7 @@ function reduceTimelineCompaction(
if (loadingIdx >= 0 && existing && existing.kind === "compaction") {
const updated: CompactionItem = {
...existing,
...advanceTimelinePosition(existing.timelineCursor, timelineCursor),
...(timelineCursor ? { timelineCursor } : {}),
status: "completed",
trigger: item.trigger ?? existing.trigger,
preTokens: item.preTokens ?? existing.preTokens,
@@ -1597,40 +1543,6 @@ function reduceTimelineCompaction(
return [...state, compaction];
}
function reduceTimelineProviderSwitch(
state: StreamItem[],
item: Extract<AgentTimelineItem, { type: "provider_switch" }>,
timestamp: Date,
timelineCursor?: TimelinePosition,
): StreamItem[] {
const switchId =
timelineCursor !== undefined
? `provider_switch:${timelineCursor.epoch}:${timelineCursor.anchorSeq}`
: createUniqueTimelineId(
state,
"provider_switch",
`${item.fromProvider}->${item.toProvider}`,
timestamp,
);
if (state.some((existing) => existing.kind === "provider_switch" && existing.id === switchId)) {
return state;
}
const marker: ProviderSwitchItem = {
kind: "provider_switch",
id: switchId,
...(timelineCursor ? { timelineCursor } : {}),
timestamp,
fromProvider: item.fromProvider,
toProvider: item.toProvider,
...(item.fromModel !== undefined ? { fromModel: item.fromModel } : {}),
...(item.toModel !== undefined ? { toModel: item.toModel } : {}),
...(item.fromSessionId !== undefined ? { fromSessionId: item.fromSessionId } : {}),
...(item.toSessionId !== undefined ? { toSessionId: item.toSessionId } : {}),
context: item.context,
};
return [...state, marker];
}
function reduceTimelineEvent(
state: StreamItem[],
event: Extract<AgentStreamEventPayload, { type: "timeline" }>,
@@ -1702,8 +1614,6 @@ function reduceTimelineEvent(
}
case "compaction":
return reduceTimelineCompaction(state, item, timestamp, timelineCursor);
case "provider_switch":
return reduceTimelineProviderSwitch(state, item, timestamp, timelineCursor);
case "plugin":
return appendPluginTimelineItem(state, item, timestamp, timelineCursor);
default:
@@ -1735,10 +1645,7 @@ export function reduceStreamUpdate(
),
event,
);
const stamped = event.turnMetrics?.length
? stampCompletedTurnMetrics(updated, event.turnMetrics, event.turnId)
: updated;
return event.item.type === "reasoning" ? stamped : finalizeActiveThoughts(stamped);
return event.item.type === "reasoning" ? updated : finalizeActiveThoughts(updated);
}
case "turn_completed":
return stampCompletedTurnMetrics(finalizeActiveThoughts(state), event.metrics, event.turnId);
@@ -16,7 +16,6 @@ export const ArrowDownUp = StubIcon;
export const ArrowLeft = StubIcon;
export const ArrowLeftToLine = StubIcon;
export const ArrowRight = StubIcon;
export const ArrowRightLeft = StubIcon;
export const ArrowUp = StubIcon;
export const ArrowUpRight = StubIcon;
export const AudioLines = StubIcon;
-3
View File
@@ -47,8 +47,5 @@
"typescript": "^5.2.2",
"vitest": "^4.1.6",
"zx": "^8.8.5"
},
"engines": {
"node": ">=22.16.0"
}
}
@@ -146,10 +146,6 @@ export async function runAttachCommand(
const unsubscribe = client.subscribeAgentTimeline(resolvedId, (message) => {
if (message.type === "agent.timeline.replacement") {
console.log("\n[Timeline replaced; earlier output is no longer current]");
} else if (message.type === "agent.timeline.rewind") {
console.log(
"\n[Conversation rewound; output since the rewound message is no longer current]",
);
} else if (message.type === "agent.timeline.subscription_restored") {
console.log("\n[Reconnected; live output resumed. Events may have been missed.]");
} else if (message.type === "agent.timeline.error") {
+1 -5
View File
@@ -408,6 +408,7 @@ async function runFollowMode({
} catch (error) {
console.warn("Warning: failed to fetch existing timeline", error);
}
// Apply filter to existing items
if (options.filter) {
existingItems = existingItems.filter((item) => matchesFilter(item, options.filter));
@@ -438,11 +439,6 @@ async function runFollowMode({
notice("\n[Timeline replaced; earlier output is no longer current]");
return;
}
if (message.type === "agent.timeline.rewind") {
writer.end();
notice("\n[Conversation rewound; output since the rewound message is no longer current]");
return;
}
if (message.type === "agent.timeline.error") {
writer.end();
@@ -210,12 +210,7 @@ try {
console.log("Foreground SIGINT reached the supervisor. The worker and ACP processes exited.");
daemon = await startSupervisor();
// The stored timeline is served without reopening the agent.
const storedIdle = (await daemon.client.fetchAgentTimeline(idle.id)).agent;
assert.equal(storedIdle?.status, "closed");
assert.equal(storedIdle?.requiresAttention, false);
await daemon.client.refreshAgent(idle.id);
const restoredIdle = (await daemon.client.fetchAgent(idle.id))?.agent;
const restoredIdle = (await daemon.client.fetchAgentTimeline(idle.id)).agent;
assert.equal(restoredIdle?.status, "idle");
assert.equal(restoredIdle?.requiresAttention, false);
await waitFor(async () => {
-31
View File
@@ -211,37 +211,6 @@ test("SDK subscribers receive timeline replacement instead of silently losing hi
}
});
test("SDK subscribers receive a conversation rewind as a retired range", async () => {
const { createPaseoApi } = await import("./index");
const h = connection();
const received: unknown[] = [];
try {
const ready = h.client.connect();
h.open();
await ready;
const off = createPaseoApi(h.client)
.agents.ref("agent")
.timeline.subscribe((event) => received.push(event));
await off.ready;
h.receive({
type: "agent.timeline.rewind",
payload: {
agentId: "agent",
epoch: "epoch-1",
seq: 12,
retireFromSeq: 7,
subscriptionId: off.subscriptionId,
},
});
expect(received).toEqual([
{ agentId: "agent", event: { type: "rewind", epoch: "epoch-1", seq: 12, retireFromSeq: 7 } },
]);
off();
} finally {
await h.client.close();
}
});
test("local listeners create no demand before or after reconnect", async () => {
const h = connection();
try {
-2
View File
@@ -141,10 +141,8 @@ export const DEFAULT_CLIENT_CAPABILITIES = {
[CLIENT_CAPS.compactProviderSnapshots]: true,
[CLIENT_CAPS.providerSnapshotReferences]: true,
[CLIENT_CAPS.timelineReplacementInvalidation]: true,
[CLIENT_CAPS.timelineRewindOperations]: true,
[CLIENT_CAPS.timelineNotifications]: true,
[CLIENT_CAPS.pluginTimelineItems]: true,
[CLIENT_CAPS.timelineProviderSwitches]: true,
[CLIENT_CAPS.workspaceSetupBlocked]: true,
[CLIENT_CAPS.workspaceSetupObservation]: true,
[CLIENT_CAPS.pluginBinaryPayloads]: true,
+1 -3
View File
@@ -246,9 +246,7 @@ export class LegacySubscriptions {
);
case "agent.timeline.set_subscription.request":
return (
(message.type === "agent_stream" ||
message.type === "agent.timeline.replacement" ||
message.type === "agent.timeline.rewind") &&
(message.type === "agent_stream" || message.type === "agent.timeline.replacement") &&
(query.agentIds as string[]).includes(message.payload.agentId)
);
case "session.events.set_subscription.request":
@@ -1132,7 +1132,6 @@ test("advertises client capabilities in hello", async () => {
all_providers: true,
selective_agent_timeline: true,
timeline_replacement_invalidation: true,
timeline_rewind_operations: true,
provider_snapshot_references: true,
explicit_event_subscriptions: true,
owned_subscriptions: true,
@@ -1146,7 +1145,6 @@ test("advertises client capabilities in hello", async () => {
terminal_reflowable_snapshot: true,
terminal_chunked_replay: true,
timeline_notifications: true,
timeline_provider_switches: true,
plugin_timeline_items: true,
plugin_binary_payloads: true,
workspace_setup_blocked: true,
+5 -112
View File
@@ -127,8 +127,6 @@ import type {
DaemonConfigReloadResponse,
DiagnosticsResponse,
AgentRewindResponseMessage,
AgentProviderSwitchRequest,
AgentProviderSwitchResponseMessage,
ListTerminalsResponse,
CreateTerminalResponse,
SubscribeTerminalResponse,
@@ -511,28 +509,6 @@ export interface SendMessageOptions {
attachments?: SendAgentMessageRequest["attachments"];
}
export interface SwitchAgentProviderOptions {
provider: AgentProvider;
model?: string | null;
modeId?: string | null;
thinkingOptionId?: string | null;
providerOptions?: Record<string, unknown>;
text: string;
messageId?: string;
images?: Array<{ data: string; mimeType: string }>;
attachments?: AgentProviderSwitchRequest["attachments"];
}
export class AgentProviderSwitchError extends Error {
constructor(
message: string,
readonly agent?: AgentSnapshotPayload,
) {
super(message);
this.name = "AgentProviderSwitchError";
}
}
export interface AgentAttentionRequiredNotification {
agentId: string;
reason: "finished" | "error" | "permission";
@@ -4363,56 +4339,6 @@ export class DaemonClient {
};
}
async switchAgentProvider(
agentId: string,
options: SwitchAgentProviderOptions,
): Promise<{ agent?: AgentSnapshotPayload }> {
if (this.lastServerInfoMessage?.features?.providerSwitching !== true) {
throw new Error("Update the Paseo host to switch providers in an existing chat.");
}
const requestId = this.createRequestId();
const messageId = options.messageId ?? crypto.randomUUID();
const message = SessionInboundMessageSchema.parse({
type: "agent.provider.switch.request",
requestId,
agentId,
provider: options.provider,
...(options.model !== undefined ? { model: options.model } : {}),
...(options.modeId !== undefined ? { modeId: options.modeId } : {}),
...(options.thinkingOptionId !== undefined
? { thinkingOptionId: options.thinkingOptionId }
: {}),
...(options.providerOptions !== undefined
? { providerOptions: options.providerOptions }
: {}),
text: options.text,
messageId,
images: options.images,
attachments: options.attachments,
});
const payload: AgentProviderSwitchResponseMessage["payload"] = await this.sendRequest({
requestId,
message,
options: { skipQueue: true },
select: (msg) => {
if (msg.type !== "agent.provider.switch.response") {
return null;
}
if (msg.payload.requestId !== requestId) {
return null;
}
return msg.payload;
},
});
if (!payload.accepted) {
throw new AgentProviderSwitchError(
payload.error ?? "switchAgentProvider rejected",
payload.agent,
);
}
return payload.agent ? { agent: payload.agent } : {};
}
/** The behavior to put on the wire for this host. */
private activeTurnBehaviorForHost(
options: SendMessageOptions,
@@ -4501,29 +4427,12 @@ export class DaemonClient {
}
}
private expectedProviderWireField(options?: {
expectedProvider?: AgentProvider;
}): { expectedProvider: AgentProvider } | Record<string, never> {
if (
options?.expectedProvider &&
this.lastServerInfoMessage?.features?.providerSwitching === true
) {
return { expectedProvider: options.expectedProvider };
}
return {};
}
async setAgentMode(
agentId: string,
modeId: string,
options?: { expectedProvider?: AgentProvider },
): Promise<AgentProviderNotice | null> {
async setAgentMode(agentId: string, modeId: string): Promise<AgentProviderNotice | null> {
const requestId = this.createRequestId();
const message = SessionInboundMessageSchema.parse({
type: "set_agent_mode_request",
agentId,
modeId,
...this.expectedProviderWireField(options),
requestId,
});
const payload = await this.sendRequest({
@@ -4546,17 +4455,12 @@ export class DaemonClient {
return payload.notice ?? null;
}
async setAgentModel(
agentId: string,
modelId: string | null,
options?: { expectedProvider?: AgentProvider },
): Promise<void> {
async setAgentModel(agentId: string, modelId: string | null): Promise<void> {
const requestId = this.createRequestId();
const message = SessionInboundMessageSchema.parse({
type: "set_agent_model_request",
agentId,
modelId,
...this.expectedProviderWireField(options),
requestId,
});
const payload = await this.sendRequest({
@@ -4578,19 +4482,13 @@ export class DaemonClient {
}
}
async setAgentFeature(
agentId: string,
featureId: string,
value: unknown,
options?: { expectedProvider?: AgentProvider },
): Promise<void> {
async setAgentFeature(agentId: string, featureId: string, value: unknown): Promise<void> {
const requestId = this.createRequestId();
const message = SessionInboundMessageSchema.parse({
type: "set_agent_feature_request",
agentId,
featureId,
value,
...this.expectedProviderWireField(options),
requestId,
});
const payload = await this.sendRequest({
@@ -4619,7 +4517,6 @@ export class DaemonClient {
async setAgentOptions(
agentId: string,
patch: Record<string, unknown>,
options?: { expectedProvider?: AgentProvider },
): Promise<AgentProviderNotice | null> {
const legacy = this.legacyProviderOptions();
if (legacy) {
@@ -4627,11 +4524,11 @@ export class DaemonClient {
const pending = this.legacyResetControls(agentId, patch);
const controls = pending ? await pending : [];
for (const [featureId, value] of legacy.featureWrites(patch, controls)) {
await this.setAgentFeature(agentId, featureId, value, options);
await this.setAgentFeature(agentId, featureId, value);
}
return null;
}
return this.applyAgentConfig(agentId, { options: patch }, options);
return this.applyAgentConfig(agentId, { options: patch });
}
/**
@@ -4651,14 +4548,12 @@ export class DaemonClient {
async setAgentThinkingOption(
agentId: string,
thinkingOptionId: string | null,
options?: { expectedProvider?: AgentProvider },
): Promise<AgentProviderNotice | null> {
const requestId = this.createRequestId();
const message = SessionInboundMessageSchema.parse({
type: "set_agent_thinking_request",
agentId,
thinkingOptionId,
...this.expectedProviderWireField(options),
requestId,
});
const payload = await this.sendRequest({
@@ -4691,7 +4586,6 @@ export class DaemonClient {
async applyAgentConfig(
agentId: string,
config: AgentConfigApply,
options?: { expectedProvider?: AgentProvider },
): Promise<AgentProviderNotice | null> {
let wireConfig = config;
const legacy = this.legacyProviderOptions();
@@ -4705,7 +4599,6 @@ export class DaemonClient {
type: "agent.config.apply.request",
agentId,
config: wireConfig,
...this.expectedProviderWireField(options),
requestId,
});
const payload = await this.sendRequest({
+1 -21
View File
@@ -346,14 +346,6 @@ export type PaseoAgentTimelineEvent =
agentId: string;
event: { type: "replacement"; epoch: string };
}
| {
/**
* A conversation rewind removed the rows anchored in `[retireFromSeq, seq)` from the active
* history. Rows after `seq` belong to the rewound conversation.
*/
agentId: string;
event: { type: "rewind"; epoch: string; seq: number; retireFromSeq: number };
}
| {
agentId: string;
subscriptionId: string;
@@ -375,9 +367,7 @@ export interface PaseoAgentTimelineHandle {
* Delivers live events only. After reconnect, subscription_restored precedes
* subsequent updates. History may have been missed; use refetch() to request
* the range you need. No history is fetched automatically. A replacement event
* invalidates the previous epoch. A rewind event removes `[retireFromSeq, seq)`
* from the active history without changing the epoch. Subscription errors
* release this observation.
* invalidates the previous epoch. Subscription errors release this observation.
* Await the returned unsubscribe function's `ready` promise before starting
* work that must be observed. It rejects if establishment fails.
*/
@@ -1057,16 +1047,6 @@ function createAgentHandleFactory(
agentId: id,
event: { type: "replacement", epoch: message.payload.epoch },
});
case "agent.timeline.rewind":
return handler({
agentId: id,
event: {
type: "rewind",
epoch: message.payload.epoch,
seq: message.payload.seq,
retireFromSeq: message.payload.retireFromSeq,
},
});
}
}),
},
@@ -3,7 +3,7 @@ import type { OwnedSubscription, TimelineSubscription } from "../connection/inde
type TimelineUpdate = Extract<
SessionOutboundMessage,
{ type: "agent_stream" | "agent.timeline.replacement" | "agent.timeline.rewind" }
{ type: "agent_stream" | "agent.timeline.replacement" }
>;
/** Local SDK lifecycle messages; these are not additional wire RPCs. */
@@ -59,11 +59,7 @@ export function subscribeTimeline(
});
},
update: (message) => {
if (
message.type === "agent_stream" ||
message.type === "agent.timeline.replacement" ||
message.type === "agent.timeline.rewind"
)
if (message.type === "agent_stream" || message.type === "agent.timeline.replacement")
notify(message);
},
error: fail,
-5
View File
@@ -377,11 +377,6 @@ export type ProviderInput =
sessionId: string;
changes: ProviderConfigChanges;
}
/**
* Rewind to the supplied `token`. Completing the request (`request.completed`) guarantees the
* plugin rewound to that exact point (removing that prompt and everything after it for
* `"conversation"` and `"both"`).
*/
| {
type: "session.revert";
requestId: string;
+1 -21
View File
@@ -401,25 +401,6 @@ export interface PluginTimelineItem {
data: JsonValue;
}
export interface ProviderSwitchContextSummary {
includedItems: number;
truncated: boolean;
charCount: number;
budgetChars: number;
omittedReasons?: string[];
}
export interface ProviderSwitchTimelineItem {
type: "provider_switch";
fromProvider: AgentProvider;
toProvider: AgentProvider;
fromModel?: string | null;
toModel?: string | null;
fromSessionId?: string | null;
toSessionId?: string | null;
context: ProviderSwitchContextSummary;
}
export interface AgentTaskItem {
text: string;
completed: boolean;
@@ -441,8 +422,7 @@ export type AgentTimelineItem =
message: string;
}
| CompactionTimelineItem
| PluginTimelineItem
| ProviderSwitchTimelineItem;
| PluginTimelineItem;
export type AgentStreamEvent =
| { type: "thread_started"; sessionId: string; provider: AgentProvider }
@@ -39,18 +39,12 @@ export const CLIENT_CAPS = {
// COMPAT(timelineReplacementInvalidation): added in v0.5.0, remove legacy
// reconstructed timeline replay after 2027-02-21 once the client floor supports invalidation.
timelineReplacementInvalidation: "timeline_replacement_invalidation",
// COMPAT(timelineRewindOperations): added in v0.14.1, remove after 2027-05-10 once the client
// floor applies rewinds. Clients without it see a rewound history under a derived epoch.
timelineRewindOperations: "timeline_rewind_operations",
// COMPAT(timelineNotifications): added in v0.7.2. The daemon omits notification
// timeline items for older clients whose strict timeline union rejects them.
// Remove after 2027-03-03 once the supported client floor is >= v0.7.2.
timelineNotifications: "timeline_notifications",
// COMPAT(pluginTimelineItems): added in v0.8.0, remove after 2027-03-07 once client floor >= v0.8.0.
pluginTimelineItems: "plugin_timeline_items",
// COMPAT(timelineProviderSwitches): added in v0.18.0, remove after 2027-05-25 once client floor >= v0.18.0.
// The daemon omits provider_switch timeline items for older clients whose strict union rejects them.
timelineProviderSwitches: "timeline_provider_switches",
workspaceSetupObservation: "workspace_setup_observation",
// COMPAT(pluginBinaryPayloads): added in v0.15.0, remove after 2027-05-02 once client floor >= v0.15.0.
// The daemon sends plugin RPC outputs as binary opcode 0x21 only to clients that decode it.
@@ -1,168 +0,0 @@
import { describe, expect, it } from "vitest";
import { CLIENT_CAPS } from "./client-capabilities.js";
import {
AgentProviderSwitchRequestSchema,
AgentProviderSwitchResponseMessageSchema,
AgentTimelineItemPayloadSchema,
FetchAgentTimelineResponseMessageSchema,
ServerInfoStatusPayloadSchema,
SessionInboundMessageSchema,
SessionOutboundMessageSchema,
WSHelloMessageSchema,
} from "./messages.js";
import { isTimelineTurnTrigger } from "./timeline-turn.js";
describe("provider switching protocol", () => {
it("parses agent.provider.switch.request and response including agent snapshot on rejection", () => {
const request = SessionInboundMessageSchema.parse({
type: "agent.provider.switch.request",
requestId: "req-switch-1",
agentId: "agent-1",
provider: "codex",
model: "gpt-5.4",
modeId: "auto",
thinkingOptionId: "high",
providerOptions: { fast_mode: true },
text: "Continue in Codex",
messageId: "msg-switch-1",
attachments: [
{
type: "text",
mimeType: "text/plain",
text: "extra context",
},
],
});
expect(request).toEqual(AgentProviderSwitchRequestSchema.parse(request));
const acceptedResponse = SessionOutboundMessageSchema.parse({
type: "agent.provider.switch.response",
payload: {
requestId: "req-switch-1",
agentId: "agent-1",
accepted: true,
error: null,
},
});
expect(acceptedResponse).toEqual(
AgentProviderSwitchResponseMessageSchema.parse(acceptedResponse),
);
const postCommitError = AgentProviderSwitchResponseMessageSchema.parse({
type: "agent.provider.switch.response",
payload: {
requestId: "req-switch-1",
agentId: "agent-1",
accepted: false,
agent: {
id: "agent-1",
provider: "codex",
cwd: "/repo",
model: "gpt-5.4",
createdAt: "2026-11-25T10:00:00.000Z",
updatedAt: "2026-11-25T10:01:00.000Z",
lastUserMessageAt: null,
status: "error",
capabilities: {
supportsStreaming: true,
supportsSessionPersistence: true,
supportsDynamicModes: true,
supportsMcpServers: true,
supportsReasoningStream: true,
supportsToolInvocations: true,
},
currentModeId: "auto",
availableModes: [],
pendingPermissions: [],
persistence: null,
title: "Chat",
labels: {},
},
error: "Rate limit exceeded",
},
});
expect(postCommitError.payload.accepted).toBe(false);
expect(postCommitError.payload.agent?.provider).toBe("codex");
});
it("parses provider_switch timeline items including null toSessionId and marks them turn triggers", () => {
const item = AgentTimelineItemPayloadSchema.parse({
type: "provider_switch",
fromProvider: "claude",
toProvider: "codex",
fromModel: "claude-sonnet-4-6",
toModel: "gpt-5.4",
fromSessionId: "claude-sess-1",
toSessionId: null,
context: {
includedItems: 12,
truncated: true,
omittedOlderItems: true,
truncatedText: false,
charCount: 14_200,
budgetChars: 100_000,
},
});
expect(item.type).toBe("provider_switch");
expect(isTimelineTurnTrigger(item)).toBe(true);
});
it("supports optional activeSegmentStartSeq on fetch_agent_timeline_response", () => {
const base = {
type: "fetch_agent_timeline_response" as const,
payload: {
requestId: "req-1",
agentId: "agent-1",
agent: null,
direction: "tail" as const,
projection: "projected" as const,
epoch: "ep-1",
reset: false,
staleCursor: false,
gap: false,
window: { minSeq: 1, maxSeq: 12, nextSeq: 13 },
startCursor: { epoch: "ep-1", seq: 1 },
endCursor: { epoch: "ep-1", seq: 12 },
hasOlder: false,
hasNewer: false,
entries: [],
error: null,
},
};
const withoutBoundary = FetchAgentTimelineResponseMessageSchema.parse(base);
expect(withoutBoundary.payload.activeSegmentStartSeq).toBeUndefined();
const withBoundary = FetchAgentTimelineResponseMessageSchema.parse({
...base,
payload: { ...base.payload, activeSegmentStartSeq: 9 },
});
expect(withBoundary.payload.activeSegmentStartSeq).toBe(9);
});
it("supports features.providerSwitching and CLIENT_CAPS.timelineProviderSwitches", () => {
const info = ServerInfoStatusPayloadSchema.parse({
status: "server_info",
serverId: "srv-1",
features: { providerSwitching: true },
});
expect(info.features?.providerSwitching).toBe(true);
const legacyInfo = ServerInfoStatusPayloadSchema.parse({
status: "server_info",
serverId: "srv-1",
features: {},
});
expect(legacyInfo.features?.providerSwitching).toBeUndefined();
const hello = WSHelloMessageSchema.parse({
type: "hello",
clientId: "client-1",
clientType: "browser",
protocolVersion: 1,
capabilities: {
[CLIENT_CAPS.timelineProviderSwitches]: true,
},
});
expect(hello.capabilities?.[CLIENT_CAPS.timelineProviderSwitches]).toBe(true);
});
});
-88
View File
@@ -818,22 +818,6 @@ export const AgentTimelineItemPayloadSchema: z.ZodType<AgentTimelineItem, unknow
version: z.number(),
data: JsonWireValueSchema,
}),
z.object({
type: z.literal("provider_switch"),
fromProvider: AgentProviderSchema,
toProvider: AgentProviderSchema,
fromModel: z.string().nullable().optional(),
toModel: z.string().nullable().optional(),
fromSessionId: z.string().nullable().optional(),
toSessionId: z.string().nullable().optional(),
context: z.object({
includedItems: z.number().int().nonnegative(),
truncated: z.boolean(),
charCount: z.number().int().nonnegative(),
budgetChars: z.number().int().nonnegative(),
omittedReasons: z.array(z.string()).optional(),
}),
}),
]);
export const AgentStreamEventPayloadSchema = z.discriminatedUnion("type", [
@@ -873,7 +857,6 @@ export const AgentStreamEventPayloadSchema = z.discriminatedUnion("type", [
provider: AgentProviderSchema,
item: AgentTimelineItemPayloadSchema,
turnId: z.string().optional(),
turnMetrics: z.array(AgentMetricSchema).optional(),
}),
z.object({
type: z.literal("permission_requested"),
@@ -2197,7 +2180,6 @@ export const SetAgentModeRequestMessageSchema = z.object({
type: z.literal("set_agent_mode_request"),
agentId: z.string(),
modeId: z.string(),
expectedProvider: AgentProviderSchema.optional(),
requestId: z.string(),
});
@@ -2218,7 +2200,6 @@ export const SetAgentModelRequestMessageSchema = z.object({
type: z.literal("set_agent_model_request"),
agentId: z.string(),
modelId: z.string().nullable(),
expectedProvider: AgentProviderSchema.optional(),
requestId: z.string(),
});
@@ -2231,7 +2212,6 @@ export const SetAgentThinkingRequestMessageSchema = z.object({
type: z.literal("set_agent_thinking_request"),
agentId: z.string(),
thinkingOptionId: z.string().nullable(),
expectedProvider: AgentProviderSchema.optional(),
requestId: z.string(),
});
@@ -2245,7 +2225,6 @@ export const SetAgentFeatureRequestMessageSchema = z.object({
agentId: z.string(),
featureId: z.string(),
value: z.unknown(),
expectedProvider: AgentProviderSchema.optional(),
requestId: z.string(),
});
@@ -2281,7 +2260,6 @@ export const AgentConfigApplyRequestMessageSchema = z.object({
type: z.literal("agent.config.apply.request"),
agentId: z.string(),
config: AgentConfigApplySchema,
expectedProvider: AgentProviderSchema.optional(),
requestId: z.string(),
});
@@ -2321,21 +2299,6 @@ export const AgentRewindResponseMessageSchema = z.object({
}),
});
export const AgentProviderSwitchRequestSchema = z.object({
type: z.literal("agent.provider.switch.request"),
requestId: z.string(),
agentId: z.string(),
provider: AgentProviderSchema,
model: z.string().nullable().optional(),
modeId: z.string().nullable().optional(),
thinkingOptionId: z.string().nullable().optional(),
providerOptions: z.record(z.string(), z.unknown()).optional(),
text: z.string(),
messageId: z.string().min(1),
images: z.array(ImageAttachmentSchema).optional(),
attachments: AgentAttachmentsSchema,
});
export const UpdateAgentResponseMessageSchema = z.object({
type: z.literal("update_agent_response"),
payload: AgentActionResponsePayloadSchema,
@@ -3657,7 +3620,6 @@ export const SessionInboundMessageSchema = z.discriminatedUnion("type", [
WorkspaceArchiveUndoRequestSchema,
SetVoiceModeMessageSchema,
SendAgentMessageRequestSchema,
AgentProviderSwitchRequestSchema,
WaitForFinishRequestSchema,
DaemonGetStatusRequestSchema,
DaemonGetPairingOfferRequestSchema,
@@ -4130,11 +4092,6 @@ export const ServerInfoStatusPayloadSchema = z
"terminal-grapheme-widths": z.boolean().optional(),
// COMPAT(rewind): added in v0.1.X, drop the gate when floor >= v0.1.X.
rewind: z.boolean().optional(),
// COMPAT(timelineRewindOperations): added in v0.14.1, remove gate after 2027-05-10.
// A conversation rewind arrives as `agent.timeline.rewind`, not a replacement.
timelineRewindOperations: z.boolean().optional(),
// COMPAT(providerSwitching): added in v0.18.0, remove gate after 2027-05-25.
providerSwitching: z.boolean().optional(),
// COMPAT(agentTimelinePromptIndex): added in v0.2.X, drop the gate when floor >= v0.2.X.
agentTimelinePromptIndex: z.boolean().optional(),
// COMPAT(agentHistorySearch): added in v0.3.0, remove gate after 2027-02-07.
@@ -4338,8 +4295,6 @@ export const AgentResumedStatusPayloadSchema = z
export const AgentRefreshedStatusPayloadSchema = z
.object({
status: z.literal("agent_refreshed"),
/** The provider's history differs from the kept history, which Reload agent did not change. */
historyDiverged: z.boolean().optional(),
})
.extend(AgentStatusWithTimelineSchema.shape);
@@ -5200,12 +5155,6 @@ export const AgentTimelineEntryPayloadSchema = z.object({
turnMetrics: z.array(AgentMetricSchema).optional(),
});
/** Active rows anchored in `[retireFromSeq, seq)` left the conversation. `seq` is the retirement's own. */
export const AgentTimelineRetirementSchema = z.object({
seq: z.number().int().nonnegative(),
retireFromSeq: z.number().int().nonnegative(),
});
export const FetchAgentTimelineResponseMessageSchema = z.object({
type: z.literal("fetch_agent_timeline_response"),
payload: z.object({
@@ -5229,11 +5178,6 @@ export const FetchAgentTimelineResponseMessageSchema = z.object({
hasNewer: z.boolean(),
mergeWindow: z.boolean().optional(),
entries: z.array(AgentTimelineEntryPayloadSchema),
// COMPAT(timelineRewindOperations): added in v0.14.1. Retirements whose seq lies in the page's
// span; apply them before the entries. Sent only to clients with the capability.
retirements: z.array(AgentTimelineRetirementSchema).optional(),
/** Seq of the latest active provider_switch marker, or 0 if never switched. */
activeSegmentStartSeq: z.number().int().nonnegative().optional(),
error: z.string().nullable(),
}),
});
@@ -5247,18 +5191,6 @@ export const AgentTimelineReplacementMessageSchema = z.object({
}),
});
/** A conversation rewind retired active rows. Apply it when `seq` follows the loaded end. */
export const AgentTimelineRewindMessageSchema = z.object({
type: z.literal("agent.timeline.rewind"),
payload: z.object({
subscriptionId: z.string().optional(),
agentId: z.string(),
epoch: z.string(),
seq: z.number().int().nonnegative(),
retireFromSeq: z.number().int().nonnegative(),
}),
});
export const AgentTimelineSearchResponseMessageSchema = z.object({
type: z.literal("agent.timeline.search.response"),
payload: z.object({
@@ -5624,17 +5556,6 @@ export const SendAgentMessageResponseMessageSchema = z.object({
}),
});
export const AgentProviderSwitchResponseMessageSchema = z.object({
type: z.literal("agent.provider.switch.response"),
payload: z.object({
requestId: z.string(),
agentId: z.string(),
accepted: z.boolean(),
agent: AgentSnapshotPayloadSchema.optional(),
error: z.string().nullable(),
}),
});
export const WaitForFinishResponseMessageSchema = z.object({
type: z.literal("wait_for_finish_response"),
payload: z.object({
@@ -7858,7 +7779,6 @@ export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [
FetchAgentResponseMessageSchema,
FetchAgentTimelineResponseMessageSchema,
AgentTimelineReplacementMessageSchema,
AgentTimelineRewindMessageSchema,
AgentTimelineSearchResponseMessageSchema,
AgentTimelineListPromptsResponseMessageSchema,
ProviderSubagentListResponseMessageSchema,
@@ -7880,7 +7800,6 @@ export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [
WorkspaceClearAttentionResponseSchema,
WorkspaceMarkUnreadResponseSchema,
SendAgentMessageResponseMessageSchema,
AgentProviderSwitchResponseMessageSchema,
SetVoiceModeResponseMessageSchema,
DaemonGetStatusResponseSchema,
DaemonGetPairingOfferResponseSchema,
@@ -8110,9 +8029,6 @@ export type AgentTimelineListPromptsResponseMessage = z.infer<
export type AgentForkContextResponseMessage = z.infer<typeof AgentForkContextResponseMessageSchema>;
export type CancelAgentResponseMessage = z.infer<typeof CancelAgentResponseMessageSchema>;
export type SendAgentMessageResponseMessage = z.infer<typeof SendAgentMessageResponseMessageSchema>;
export type AgentProviderSwitchResponseMessage = z.infer<
typeof AgentProviderSwitchResponseMessageSchema
>;
export type SetVoiceModeResponseMessage = z.infer<typeof SetVoiceModeResponseMessageSchema>;
export type SetAgentModeResponseMessage = z.infer<typeof SetAgentModeResponseMessageSchema>;
export type SetAgentModelResponseMessage = z.infer<typeof SetAgentModelResponseMessageSchema>;
@@ -8248,7 +8164,6 @@ export type ProjectSuggestionsResponse = z.infer<typeof ProjectSuggestionsRespon
export type FetchAgentRequestMessage = z.infer<typeof FetchAgentRequestMessageSchema>;
export type AgentForkContextRequestMessage = z.infer<typeof AgentForkContextRequestMessageSchema>;
export type SendAgentMessageRequest = z.infer<typeof SendAgentMessageRequestSchema>;
export type AgentProviderSwitchRequest = z.infer<typeof AgentProviderSwitchRequestSchema>;
export type WaitForFinishRequest = z.infer<typeof WaitForFinishRequestSchema>;
export type DictationStreamStartMessage = z.infer<typeof DictationStreamStartMessageSchema>;
export type DictationStreamChunkMessage = z.infer<typeof DictationStreamChunkMessageSchema>;
@@ -8568,10 +8483,7 @@ export const WSHelloMessageSchema = z.object({
[CLIENT_CAPS.compactProviderSnapshots]: z.boolean().optional(),
[CLIENT_CAPS.providerSnapshotReferences]: z.boolean().optional(),
[CLIENT_CAPS.timelineReplacementInvalidation]: z.boolean().optional(),
[CLIENT_CAPS.timelineRewindOperations]: z.boolean().optional(),
[CLIENT_CAPS.timelineNotifications]: z.boolean().optional(),
[CLIENT_CAPS.pluginTimelineItems]: z.boolean().optional(),
[CLIENT_CAPS.timelineProviderSwitches]: z.boolean().optional(),
[CLIENT_CAPS.backgroundAgents]: z.boolean().optional(),
[CLIENT_CAPS.browserHost]: BrowserAutomationHostCapabilitySchema.optional(),
})
@@ -217,64 +217,6 @@ describe("wire schema compatibility", () => {
});
});
test("rewind operations are opt-in and older fetch responses still parse", () => {
expect(
WSHelloMessageSchema.parse({
type: "hello",
clientId: "capable-client",
clientType: "mobile",
protocolVersion: 1,
capabilities: { timeline_rewind_operations: true },
}).capabilities,
).toEqual({ timeline_rewind_operations: true });
const rewind = {
type: "agent.timeline.rewind",
payload: {
subscriptionId: "sub-1",
agentId: "agent-1",
epoch: "epoch-1",
seq: 12,
retireFromSeq: 7,
},
};
expect(SessionOutboundMessageSchema.parse(rewind)).toEqual(rewind);
const page = {
requestId: "fetch-1",
agentId: "agent-1",
agent: null,
direction: "after",
projection: "projected",
epoch: "epoch-1",
reset: false,
staleCursor: false,
gap: false,
window: { minSeq: 1, maxSeq: 14, nextSeq: 15 },
startCursor: { epoch: "epoch-1", seq: 13 },
endCursor: { epoch: "epoch-1", seq: 14 },
hasOlder: true,
hasNewer: false,
entries: [],
error: null,
};
const withRetirements = { ...page, retirements: [{ seq: 12, retireFromSeq: 7 }] };
expect(
SessionOutboundMessageSchema.parse({
type: "fetch_agent_timeline_response",
payload: withRetirements,
}),
).toMatchObject({ payload: { retirements: [{ seq: 12, retireFromSeq: 7 }] } });
// A daemon before rewind operations sends no retirements.
const older = SessionOutboundMessageSchema.parse({
type: "fetch_agent_timeline_response",
payload: page,
});
expect(older.type === "fetch_agent_timeline_response" && older.payload.retirements).toBe(
undefined,
);
});
test("server info strips unknown legacy features while accepting former turn identity", () => {
const parsed = ServerInfoStatusPayloadSchema.parse({
status: "server_info",
-1
View File
@@ -19,7 +19,6 @@ export function isTimelineTurnTrigger(item: {
}): boolean {
return (
item.type === "user_message" ||
item.type === "provider_switch" ||
(item.type === "tool_call" && (item.agentMessage !== undefined || item.name === "heartbeat"))
);
}
+1 -4
View File
@@ -160,7 +160,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",
@@ -171,8 +171,5 @@
},
"overrides": {
"lightningcss": "1.30.1"
},
"engines": {
"node": ">=22.16.0"
}
}
@@ -3,7 +3,7 @@ import { buildAgentForkContextAttachment, curateAgentActivity } from "./activity
import type { AgentTimelineItem } from "./agent-sdk-types.js";
import type { AgentTimelineRow } from "./agent-timeline-store-types.js";
import { formatAgentMessage, projectAgentMessages } from "./agent-messages/index.js";
import { AgentTimeline } from "./timeline/index.js";
import { InMemoryAgentTimelineStore } from "./agent-timeline-store.js";
function toolCallItem(params: {
callId: string;
@@ -41,15 +41,12 @@ function row(seq: number, item: AgentTimelineItem): AgentTimelineRow {
}
/** Rows as the daemon hands them to a fork: projected by the timeline store. */
async function storeTimeline(items: readonly AgentTimelineItem[]) {
const store = new AgentTimeline();
const scope = { agentId: "agent-1" };
await store.create(scope);
await store.append(
scope,
items.map((item) => ({ item })),
);
return await store.fetch(scope, { limit: 0 });
function storeTimeline(items: readonly AgentTimelineItem[]) {
const store = new InMemoryAgentTimelineStore();
store.initialize("agent-1");
for (const item of items) store.append("agent-1", item);
const { epoch, rows } = store.fetch("agent-1", { limit: 0 });
return { epoch, rows };
}
function backgroundTaskItem(input: { status: "running" | "completed"; log: string }) {
@@ -455,8 +452,8 @@ second line'`,
expect(result.attachment.text).toContain("[Assistant] Done.");
});
it("forks at a response that background work outlives, by message id", async () => {
const { rows } = await storeTimeline([
it("forks at a response that background work outlives, by message id", () => {
const { rows } = storeTimeline([
{ type: "user_message", text: "Audit in the background", messageId: "user-1" },
backgroundTaskItem({ status: "running", log: "scanning" }),
{ type: "assistant_message", text: "Audit started.", messageId: "assistant-1" },
@@ -476,8 +473,8 @@ second line'`,
expect(result.attachment.text).not.toContain("Any findings?");
});
it("forks at a response that background work outlives, by timeline cursor", async () => {
const { epoch, rows } = await storeTimeline([
it("forks at a response that background work outlives, by timeline cursor", () => {
const { epoch, rows } = storeTimeline([
{ type: "user_message", text: "Audit in the background", messageId: "user-1" },
backgroundTaskItem({ status: "running", log: "scanning" }),
{ type: "assistant_message", text: "Audit started." },
@@ -10,7 +10,7 @@ import { projectTimelineRows, selectItemsByProjectedLimit } from "./timeline-pro
const DEFAULT_MAX_ITEMS = 0;
const MAX_TOOL_INPUT_CHARS = 400;
const MAX_TOOL_SUMMARY_CHARS = 200;
export const MAX_FORK_CONTEXT_CHARS = 100_000;
const MAX_FORK_CONTEXT_CHARS = 100_000;
const MAX_FORK_METADATA_CHARS = 1_000;
const FORK_HISTORY_OMITTED = "[Earlier chat history omitted]\n";
// A fork copies only these kinds.
@@ -27,7 +27,7 @@ interface ActivityCuratorOptions {
includeExternalToolInput?: boolean;
}
export interface ActivityEntry {
interface ActivityEntry {
text: string;
}
@@ -138,7 +138,7 @@ function appendAgentMessageEntries(entries: ActivityEntry[], message: AgentMessa
if (body) entries.push(activityEntry(body));
}
export function curateProjectedActivityEntries(
function curateProjectedActivityEntries(
items: readonly AgentTimelineItem[],
options?: ActivityCuratorOptions,
): ActivityEntry[] {
@@ -186,11 +186,6 @@ export function curateProjectedActivityEntries(
case "compaction":
entries.push(activityEntry("[Compacted]"));
break;
case "provider_switch":
entries.push(
activityEntry(`[Switched provider: ${item.fromProvider} -> ${item.toProvider}]`),
);
break;
}
}
@@ -1,11 +1,11 @@
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { expect, test, vi } from "vitest";
import { expect, test } from "vitest";
import { createTestLogger } from "../../test-utils/test-logger.js";
import { AgentManager } from "./agent-manager.js";
import { AgentNotFoundError, ensureAgentLoaded, loadAgentHistory } from "./agent-loading.js";
import { ensureAgentLoaded } from "./agent-loading.js";
import { startAgentRun } from "./agent-prompt.js";
import { AgentStorage } from "./agent-storage.js";
import type {
@@ -227,109 +227,6 @@ test("reopening an agent with no resumable session keeps a metadata write that o
}
});
test("reads stored history without starting or requiring the provider, and imports history that is not stored", async () => {
const root = await mkdtemp(path.join(tmpdir(), "agent-loading-history-"));
const logger = createTestLogger();
const storage = new AgentStorage(path.join(root, "agents"), logger);
const baseClient = createTestAgentClients().codex;
if (!baseClient) {
throw new Error("expected Codex test client");
}
let resumes = 0;
const client: AgentClient = {
provider: baseClient.provider,
capabilities: baseClient.capabilities,
createSession: async (config: AgentSessionConfig, launchContext?: AgentLaunchContext) =>
await baseClient.createSession(config, launchContext),
resumeSession: async (
handle: AgentPersistenceHandle,
overrides?: Partial<AgentSessionConfig>,
launchContext?: AgentLaunchContext,
) => {
resumes += 1;
return await baseClient.resumeSession(handle, overrides, launchContext);
},
fetchCatalog: async (options) => await baseClient.fetchCatalog(options),
isAvailable: async () => await baseClient.isAvailable(),
};
const agentId = "00000000-0000-4000-8000-000000000601";
const managers: AgentManager[] = [];
function startDaemon(): AgentManager {
const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger });
managers.push(manager);
return manager;
}
try {
const manager = startDaemon();
const agent = await manager.createAgent({ provider: "codex", cwd: root }, agentId, {
workspaceId: "workspace-a",
});
await manager.runAgent(agent.id, "hello");
const transcript = await manager.getTimeline(agent.id);
expect(transcript.map((item) => item.type)).toContain("assistant_message");
await manager.closeAgent(agent.id);
await manager.flush();
await storage.flush();
const stored = await loadAgentHistory(agentId, {
agentManager: manager,
agentStorage: storage,
logger,
});
expect(stored).toMatchObject({ kind: "stored", record: { id: agentId } });
expect(await manager.getTimeline(agentId)).toEqual(transcript);
expect(manager.getAgent(agentId)).toBeNull();
// Stored history needs no provider, so it still reads once the provider is removed.
await expect(
loadAgentHistory(agentId, {
agentManager: manager,
agentStorage: storage,
logger,
validProviders: [],
}),
).resolves.toMatchObject({ kind: "stored", record: { id: agentId } });
expect(resumes).toBe(0);
// A restarted daemon has no history in memory; the provider's own history is imported,
// which needs the provider.
const restarted = startDaemon();
await expect(
loadAgentHistory(agentId, {
agentManager: restarted,
agentStorage: storage,
logger,
validProviders: [],
}),
).rejects.toThrow("references unavailable provider 'codex'");
const loaded = await loadAgentHistory(agentId, {
agentManager: restarted,
agentStorage: storage,
logger,
});
expect(loaded).toMatchObject({ kind: "live", agent: { id: agentId } });
expect(resumes).toBe(1);
expect((await restarted.getTimeline(agentId)).map((item) => item.type)).toEqual(
transcript.map((item) => item.type),
);
await expect(
loadAgentHistory("00000000-0000-4000-8000-000000000602", {
agentManager: restarted,
agentStorage: storage,
logger,
}),
).rejects.toBeInstanceOf(AgentNotFoundError);
} finally {
for (const manager of managers) {
await manager.closeAgent(agentId).catch(() => undefined);
await manager.flush().catch(() => undefined);
}
await storage.flush().catch(() => undefined);
await rm(root, { recursive: true, force: true });
}
});
test.each([false, true])(
"loads history after its working directory is removed (archived: %s)",
async (archived) => {
@@ -374,11 +271,11 @@ test.each([false, true])(
});
expect(loaded.id).toBe(agentId);
// The manager kept the transcript when the agent closed, so the reply the agent gave
// before the worktree went away is still readable.
const replies = (await manager.getTimeline(agentId)).filter(
(item) => item.type === "assistant_message",
);
// The transcript is replayed from the provider's persisted history, so the reply the
// agent gave before the worktree went away is still readable.
const replies = manager
.getTimeline(agentId)
.filter((item) => item.type === "assistant_message");
expect(replies.length).toBeGreaterThan(0);
expect(
replies.every((item) => item.type === "assistant_message" && item.text.length > 0),
@@ -421,7 +318,7 @@ test("timeline requests read unarchived stored history with a deleted cwd", asyn
}
}, 30000);
test("timeline reads of stored history leave the provider closed until a prompt resumes it interactively", async () => {
test("timeline reads keep runnable unarchived agents interactive for the next prompt", async () => {
const clients = createTestAgentClients();
const base = clients.codex!;
const purposes: Array<AgentResumeSessionOptions | undefined> = [];
@@ -442,8 +339,7 @@ test("timeline reads of stored history leave the provider closed until a prompt
const agent = await ctx.client.createAgent({ provider: "codex", cwd });
await ctx.daemon.daemon.agentManager.closeAgent(agent.id);
await ctx.client.fetchAgentTimeline(agent.id);
// The manager serves the stored timeline itself, so the read resumes no provider session.
expect(purposes).toEqual([]);
expect(purposes).toEqual([{ purpose: "interactive" }]);
await ctx.client.sendMessage(agent.id, "continue after opening history");
expect((await ctx.client.waitForFinish(agent.id, 15000)).status).toBe("idle");
const timeline = await ctx.client.fetchAgentTimeline(agent.id);
@@ -457,9 +353,11 @@ test("timeline reads of stored history leave the provider closed until a prompt
manager.tryRunOutOfBand(agent.id, "first prompt"),
manager.tryRunOutOfBand(agent.id, "second prompt"),
]);
// The prompt resumed once, and the concurrent prompts after the removed-cwd read share one
// resume. Every resume is interactive, so no history session needs replacing.
expect(purposes).toEqual([{ purpose: "interactive" }, { purpose: "interactive" }]);
expect(purposes).toEqual([
{ purpose: "interactive" },
{ purpose: "history" },
undefined, // Reload uses the provider's interactive default.
]);
} finally {
await ctx.cleanup();
await rm(cwd, { recursive: true, force: true });
@@ -553,13 +451,9 @@ test.each(["mode", "thinking", "rewind"])(
runtime.recordedLaunches.filter((launch) => launch.session === sessionFile),
).toHaveLength(1);
expect(manager.getAgent(agentId)?.currentModeId).toBe("full");
// The run reads its timeline before the provider starts the turn.
await vi.waitFor(() =>
expect(runtime.latestSession().prompts).toEqual([
expect.objectContaining({ message: "continue" }),
]),
);
runtime.latestSession().beginTurn();
expect(runtime.latestSession().prompts).toEqual([
expect.objectContaining({ message: "continue" }),
]);
runtime.latestSession().finishTurn();
await manager.waitForAgentEvent(agentId);
await manager.archiveAgent(agentId);
@@ -2,7 +2,7 @@ import type { Logger } from "pino";
import type { AgentProvider } from "./agent-sdk-types.js";
import type { AgentManager, ManagedAgent } from "./agent-manager.js";
import type { AgentStorage, StoredAgentRecord } from "./agent-storage.js";
import type { AgentStorage } from "./agent-storage.js";
import {
buildConfigOverrides,
extractAttention,
@@ -18,67 +18,32 @@ export class AgentNotFoundError extends Error {
}
}
const pendingAgentInitializations = new Map<string, Promise<ManagedAgent>>();
interface PendingAgentInitialization {
promise: Promise<ManagedAgent>;
options: { broadcastTimeline: boolean };
}
const pendingAgentInitializations = new Map<string, PendingAgentInitialization>();
export type AgentLoaderManager = Pick<
AgentManager,
"createAgentFromRecord" | "getAgent" | "getRegisteredProviderIds" | "resumeAgentFromPersistence"
| "createAgentFromRecord"
| "getAgent"
| "getRegisteredProviderIds"
| "hydrateTimelineFromProvider"
| "resumeAgentFromPersistence"
> &
Partial<Pick<AgentManager, "waitForAgentClose" | "reconcilePendingProviderSwitch">>;
Partial<Pick<AgentManager, "waitForAgentClose">>;
export interface EnsureAgentLoadedDeps {
agentManager: AgentLoaderManager;
agentStorage: AgentStorage;
validProviders?: Iterable<AgentProvider>;
broadcastTimeline?: boolean;
purpose?: "history" | "interactive";
logger: Logger;
}
/** The agent's history to read: from its runtime, or stored, with no provider session opened. */
export type AgentHistorySource =
| { kind: "live"; agent: ManagedAgent }
| { kind: "stored"; record: StoredAgentRecord };
export interface LoadAgentHistoryDeps extends EnsureAgentLoadedDeps {
agentManager: AgentLoaderManager & Pick<AgentManager, "hasStoredHistory">;
}
/**
* Resolves an agent for reading its history. A loaded agent is read live. A stored agent whose
* history the timeline holds is read without resuming its provider, so it reads even when its
* provider is no longer available. Otherwise the provider is resumed, which imports its history
* and requires the provider.
*/
export async function loadAgentHistory(
agentId: string,
deps: LoadAgentHistoryDeps,
): Promise<AgentHistorySource> {
const live = deps.agentManager.getAgent(agentId);
if (live) return { kind: "live", agent: live };
await deps.agentManager.reconcilePendingProviderSwitch?.(agentId);
const record = await deps.agentStorage.get(agentId);
if (!record) throw new AgentNotFoundError(agentId);
if (await deps.agentManager.hasStoredHistory(agentId)) {
return { kind: "stored", record };
}
return { kind: "live", agent: await ensureAgentLoaded(agentId, deps) };
}
async function requireLoadableRecord(
agentId: string,
deps: EnsureAgentLoadedDeps,
): Promise<StoredAgentRecord> {
const record = await deps.agentStorage.get(agentId);
if (!record) {
throw new AgentNotFoundError(agentId);
}
const validProviders = deps.validProviders ?? deps.agentManager.getRegisteredProviderIds();
if (!isStoredAgentProviderAvailable(record, validProviders)) {
throw new Error(`Agent ${agentId} references unavailable provider '${record.provider}'`);
}
return record;
}
export async function ensureUnarchivedAgentLoaded(
agentId: string,
deps: EnsureAgentLoadedDeps & {
@@ -110,7 +75,8 @@ export async function ensureAgentLoaded(
const inflight = pendingAgentInitializations.get(agentId);
if (inflight) {
return inflight;
inflight.options.broadcastTimeline ||= deps.broadcastTimeline === true;
return inflight.promise;
}
const existing = deps.agentManager.getAgent(agentId);
@@ -125,13 +91,24 @@ export async function ensureAgentLoaded(
const laterInflight = pendingAgentInitializations.get(agentId);
if (laterInflight) {
return laterInflight;
laterInflight.options.broadcastTimeline ||= deps.broadcastTimeline === true;
return laterInflight.promise;
}
const pendingOptions = {
broadcastTimeline: deps.broadcastTimeline === true,
};
const initPromise = (async () => {
await deps.agentManager.reconcilePendingProviderSwitch?.(agentId);
const record = await requireLoadableRecord(agentId, deps);
const record = await deps.agentStorage.get(agentId);
if (!record) {
throw new AgentNotFoundError(agentId);
}
const validProviders = deps.validProviders ?? deps.agentManager.getRegisteredProviderIds();
if (!isStoredAgentProviderAvailable(record, validProviders)) {
throw new Error(`Agent ${agentId} references unavailable provider '${record.provider}'`);
}
const handle = toAgentPersistenceHandle(validProviders, record.persistence);
let snapshot: ManagedAgent;
@@ -153,16 +130,20 @@ export async function ensureAgentLoaded(
deps.logger.info({ agentId, provider: record.provider }, "Agent created from stored config");
}
await deps.agentManager.hydrateTimelineFromProvider(agentId, {
broadcast: () => pendingOptions.broadcastTimeline,
});
return deps.agentManager.getAgent(agentId) ?? snapshot;
})();
pendingAgentInitializations.set(agentId, initPromise);
const pending: PendingAgentInitialization = { promise: initPromise, options: pendingOptions };
pendingAgentInitializations.set(agentId, pending);
try {
return await initPromise;
} finally {
const current = pendingAgentInitializations.get(agentId);
if (current === initPromise) {
if (current === pending) {
pendingAgentInitializations.delete(agentId);
}
}
@@ -3,8 +3,6 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, test, vi } from "vitest";
import pino, { type Logger } from "pino";
import { createTestLogger } from "../../test-utils/test-logger.js";
import { AgentManager, type AgentManagerEvent } from "./agent-manager.js";
import { AGENT_STREAM_COALESCE_DEFAULT_WINDOW_MS } from "./agent-stream-coalescer.js";
@@ -15,8 +13,6 @@ import { FakeOmp } from "./providers/omp/test-utils/fake-omp.js";
import { PiRpcAgentClient } from "./providers/pi/agent.js";
import { FakePi } from "./providers/pi/test-utils/fake-pi.js";
import { projectTimelineRows } from "./timeline-projection.js";
import { AgentTimeline } from "./timeline/index.js";
import { DeferredTimelineBackend } from "./timeline/testing.js";
import type {
AgentCapabilityFlags,
AgentClient,
@@ -186,7 +182,6 @@ class TestAgentSession implements AgentSession {
class TestAgentClient implements AgentClient {
readonly capabilities = TEST_CAPABILITIES;
private sessionCounter = 0;
private history: AgentStreamEvent[] = [];
readonly sessions = new Map<string, TestAgentSession>();
constructor(readonly provider: AgentProvider = "codex") {}
@@ -200,7 +195,6 @@ class TestAgentClient implements AgentClient {
config,
`${config.provider}-session-${++this.sessionCounter}`,
);
session.setHistory(this.history);
this.sessions.set(config.cwd, session);
return session;
}
@@ -236,11 +230,6 @@ class TestAgentClient implements AgentClient {
return true;
}
/** The provider history of the sessions created from now on. */
setHistory(events: AgentStreamEvent[]): void {
this.history = [...events];
}
getSession(cwd: string): TestAgentSession {
const session = this.sessions.get(cwd);
if (!session) {
@@ -258,18 +247,13 @@ interface Harness {
cleanup: () => void;
}
function createHarness(options?: {
provider?: AgentProvider;
timeline?: AgentTimeline;
logger?: Logger;
}): Harness {
function createHarness(options?: { provider?: AgentProvider }): Harness {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-stream-coalescing-"));
const client = new TestAgentClient(options?.provider ?? "codex");
const manager = new AgentManager({
clients: { [client.provider]: client },
idFactory: createIdFactory(),
logger: options?.logger ?? createTestLogger(),
timeline: options?.timeline,
logger: createTestLogger(),
});
const events: AgentManagerEvent[] = [];
manager.subscribe((event) => events.push(event), { replayState: false });
@@ -288,20 +272,6 @@ function createIdFactory(): () => string {
return () => AGENT_IDS[index++] ?? `00000000-0000-4000-8000-${String(index).padStart(12, "0")}`;
}
/** Resumes an agent whose history Paseo does not hold, so it imports the provider's. */
async function resumeWithProviderHistory(
harness: Harness,
history: AgentStreamEvent[],
): Promise<{ agentId: string }> {
harness.client.setHistory(history);
const agent = await harness.manager.resumeAgentFromPersistence(
{ provider: harness.client.provider, sessionId: "provider-history" },
{ cwd: harness.workdir },
AGENT_IDS[0],
);
return { agentId: agent.id };
}
async function createManagedSession(
harness: Harness,
options?: { agentId?: string; provider?: AgentProvider; workdir?: string },
@@ -701,15 +671,15 @@ describe("target coalesced behavior", () => {
}
});
test("bounds tool output while importing provider history", async () => {
test("bounds tool output while hydrating provider history", async () => {
const harness = createHarness();
try {
const { agentId, session } = await createManagedSession(harness);
const output = `${"a".repeat(512 * 1024)}${"z".repeat(512 * 1024)}`;
const expectedItem = limitAgentTimelineItemContent(toolCall({ status: "completed", output }));
session.setHistory([timelineEvent(toolCall({ status: "completed", output }))]);
const { agentId } = await resumeWithProviderHistory(harness, [
timelineEvent(toolCall({ status: "completed", output })),
]);
await harness.manager.hydrateTimelineFromProvider(agentId, { force: true });
expect(getTimelineItems(await harness.manager.getTimelineRows(agentId))).toEqual([
expectedItem,
@@ -1300,81 +1270,6 @@ describe("target coalesced behavior", () => {
}
});
test.each(["turn_completed", "turn_failed", "turn_canceled"] as const)(
"%s waits for the final chunk an asynchronous timeline is still committing",
async (terminalType) => {
const harness = createHarness({ timeline: new AgentTimeline(new DeferredTimelineBackend()) });
try {
const { agentId, session } = await createManagedSession(harness);
session.pushEvent(assistant("final chunk", "codex", "turn"));
session.pushEvent(terminalEvent(terminalType, "turn"));
const streamTypes = () =>
getStreamEvents(harness.events, agentId).map((event) =>
event.type === "agent_stream" ? event.event.type : event.type,
);
await expect.poll(streamTypes).toContain(terminalType);
const streamEvents = getStreamEvents(harness.events, agentId);
expect(streamEvents[0]).toMatchObject({
event: { type: "timeline", item: { type: "assistant_message", text: "final chunk" } },
seq: 1,
});
expect(streamTypes().indexOf(terminalType)).toBeGreaterThan(0);
} finally {
await harness.manager.flush();
harness.cleanup();
}
},
);
test("a final chunk the timeline fails to commit surfaces a history error after the turn", async () => {
const backend = new DeferredTimelineBackend();
const logs: Array<Record<string, unknown>> = [];
const harness = createHarness({
timeline: new AgentTimeline(backend),
logger: pino({ level: "error" }, { write: (line: string) => logs.push(JSON.parse(line)) }),
});
try {
const { agentId, session } = await createManagedSession(harness);
session.pushEvent(assistant("earlier chunk", "codex", "earlier"));
session.pushEvent(terminalEvent("turn_completed", "earlier"));
await expect.poll(() => getTimelineStreamEvents(harness.events, agentId)).toHaveLength(1);
await harness.manager.flush();
session.pushEvent({ type: "turn_started", provider: "codex", turnId: "turn" });
await expect.poll(() => harness.manager.getAgent(agentId)?.lifecycle).toBe("running");
backend.failNextAppend = true;
session.pushEvent(assistant("final chunk", "codex", "turn"));
session.pushEvent(terminalEvent("turn_completed", "turn"));
const completions = () =>
getStreamEvents(harness.events, agentId).filter(
(event) => event.type === "agent_stream" && event.event.type === "turn_completed",
);
await expect.poll(completions).toHaveLength(2);
await harness.manager.flush();
expect(harness.manager.getAgent(agentId)).toMatchObject({
lifecycle: "error",
lastError: "Conversation history could not be saved: disk full",
attention: { requiresAttention: true, attentionReason: "error" },
});
const earlier = { type: "assistant_message", text: "earlier chunk" };
expect(getTimelineStreamEvents(harness.events, agentId)).toEqual([
expect.objectContaining({ event: expect.objectContaining({ item: earlier }) }),
]);
expect(getTimelineItems(await harness.manager.getTimelineRows(agentId))).toEqual([earlier]);
expect(logs).toContainEqual(
expect.objectContaining({
msg: "Failed to record timeline item",
agentId,
err: expect.objectContaining({ message: "disk full" }),
}),
);
} finally {
harness.cleanup();
}
});
test("lifecycle paths are timer-safe", async () => {
vi.useFakeTimers();
@@ -1595,16 +1490,14 @@ describe("target coalesced behavior", () => {
}
});
test("history import projects immediately without waiting for a streaming window", async () => {
test("history hydration projects immediately without waiting for a streaming window", async () => {
vi.useFakeTimers();
const harness = createHarness();
try {
const { agentId } = await resumeWithProviderHistory(harness, [
assistant("a1"),
assistant("a2"),
reasoning("r1"),
reasoning("r2"),
]);
const { agentId, session } = await createManagedSession(harness);
session.setHistory([assistant("a1"), assistant("a2"), reasoning("r1"), reasoning("r2")]);
await harness.manager.hydrateTimelineFromProvider(agentId, { force: true });
const rows = await harness.manager.getTimelineRows(agentId);
expect(getTimelineItems(rows)).toEqual([

Some files were not shown because too many files have changed in this diff Show More