mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-26 02:05:31 +00:00
Compare commits
36
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6fba37f964 | ||
|
|
4a705540e2 | ||
|
|
ade9951393 | ||
|
|
af7d18f08e | ||
|
|
2ba6f0f3d4 | ||
|
|
b8f78ce288 | ||
|
|
b5cb229e7f | ||
|
|
e53ccc2510 | ||
|
|
0a8865178e | ||
|
|
5a847719d1 | ||
|
|
f4abc198f8 | ||
|
|
4cc532cb32 | ||
|
|
076da38c44 | ||
|
|
774110243e | ||
|
|
ed37f6f5a4 | ||
|
|
bfc2f5cb3a | ||
|
|
a060e03751 | ||
|
|
fa7b6d1a27 | ||
|
|
3c194a988d | ||
|
|
15098efcf2 | ||
|
|
c9823293b0 | ||
|
|
5fd6783c19 | ||
|
|
4719186fbb | ||
|
|
cd2bfa91a8 | ||
|
|
b26f19accd | ||
|
|
8aba8bde08 | ||
|
|
29c448ac96 | ||
|
|
e03503c0de | ||
|
|
16c8a188e0 | ||
|
|
325a65acac | ||
|
|
3c5654d2ab | ||
|
|
e531eb1f1a | ||
|
|
a462c43de2 | ||
|
|
511306bd25 | ||
|
|
eed84c01f1 | ||
|
|
6d21e28e06 |
@@ -403,7 +403,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`. Timeline rows are runtime memory; provider history is the durable transcript authority and resumed agents rebuild from it. That storage path is derived from `cwd`, not from workspace id.
|
||||
- Agent state persists to `$PASEO_HOME/agents/{cwd-with-dashes}/{agent-id}.json`. That storage path is derived from `cwd`, not from workspace id. Timeline rows persist in the daemon database, `$PASEO_HOME/paseo.db`. They are the transcript authority after the first import of provider history. See [owned history](timeline-sync.md#owned-history).
|
||||
|
||||
## Right-sidebar boundary: directory-backed vs workspace-owned
|
||||
|
||||
@@ -479,6 +479,7 @@ 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
|
||||
|
||||
+37
-5
@@ -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 uses **file-based JSON persistence** instead of a traditional database. All data is validated at runtime with Zod schemas. Most stores write atomically (write to temp file, then rename); a few still use plain `writeFile` — see each section. There is no schema-versioning/migration framework — schemas rely on optional fields with defaults for forward compatibility, with a small amount of inline normalization in `persisted-config.ts` for legacy provider/speech entries.
|
||||
Paseo persists most stores as JSON files, and agent timelines in the [daemon database](#daemon-database). JSON data is validated at runtime with Zod schemas. Most JSON stores write atomically (write to temp file, then rename); a few still use plain `writeFile` — see each section. JSON stores have no schema-versioning/migration framework — schemas rely on optional fields with defaults for forward compatibility, with a small amount of inline normalization in `persisted-config.ts` for legacy provider/speech entries.
|
||||
|
||||
All server-side stores live under `$PASEO_HOME` (defaults to `~/.paseo`).
|
||||
|
||||
@@ -53,6 +53,7 @@ $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}/
|
||||
@@ -181,11 +182,42 @@ Terminal activity contributes to the workspace status bucket **per `workspaceId`
|
||||
|
||||
---
|
||||
|
||||
## Runtime-only Agent Timelines
|
||||
## Daemon database
|
||||
|
||||
Agent timelines are not written to `$PASEO_HOME`. `AgentTimeline` owns each agent's history behind
|
||||
a backend, and the only backend is in memory, so a daemon restart loses it and the next resume
|
||||
imports provider history. See [owned history](timeline-sync.md#owned-history).
|
||||
`$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).
|
||||
|
||||
---
|
||||
|
||||
|
||||
+12
-7
@@ -46,19 +46,24 @@ deleting the agent, or a provider removing one of its own children, deletes hist
|
||||
for example because the provider stored expanded attachment text, the chat stays unchanged and
|
||||
Paseo reports a mismatch. A provider child Paseo already holds, listed or retired, is never imported again.
|
||||
- **Archive and reload** keep the history and the provider children. An archived chat reads them
|
||||
without its provider. Deleting the agent deletes its history and every child's, retired ones
|
||||
included.
|
||||
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 only backend keeps everything in
|
||||
memory, so a daemon restart loses the owned history: the next resume imports provider history into
|
||||
a new epoch, and clients take the destructive reset below. Rewinds retired before the restart come
|
||||
back if the provider history still holds them. Retained history costs memory for every loaded,
|
||||
closed or archived agent until the daemon exits or the agent is deleted.
|
||||
`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
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
sha256-TAVzJzziWDAapQkG4TLkLzOlodkdFNKSl3y/Tm9HB28=
|
||||
sha256-IAhKhkolW4xvFvMaAEFdhYvPAhTm2azsqbGMKCKL3q0=
|
||||
|
||||
Generated
+20
-1
@@ -45,6 +45,9 @@
|
||||
"react-dom": "19.2.3",
|
||||
"typescript": "^5.9.3",
|
||||
"ws": "^8.20.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.16.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@0no-co/graphql.web": {
|
||||
@@ -39719,6 +39722,9 @@
|
||||
"typescript": "^5.2.2",
|
||||
"vitest": "^4.1.6",
|
||||
"zx": "^8.8.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.16.0"
|
||||
}
|
||||
},
|
||||
"packages/cli/node_modules/@vitest/expect": {
|
||||
@@ -40646,7 +40652,7 @@
|
||||
"@playwright/test": "^1.56.1",
|
||||
"@types/express": "^4.17.20",
|
||||
"@types/markdown-it": "^14.2.0",
|
||||
"@types/node": "^20.9.0",
|
||||
"@types/node": "^22.16.0",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@types/uuid": "^9.0.7",
|
||||
"@types/ws": "^8.5.8",
|
||||
@@ -40654,6 +40660,9 @@
|
||||
"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": {
|
||||
@@ -41101,6 +41110,16 @@
|
||||
"@types/mdurl": "^2"
|
||||
}
|
||||
},
|
||||
"packages/server/node_modules/@types/node": {
|
||||
"version": "22.20.5",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz",
|
||||
"integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"undici-types": "~6.21.0"
|
||||
}
|
||||
},
|
||||
"packages/server/node_modules/@vitest/expect": {
|
||||
"version": "4.1.6",
|
||||
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.6.tgz",
|
||||
|
||||
@@ -169,5 +169,8 @@
|
||||
"tiny-async-pool": {
|
||||
"semver@^5": "5.7.2"
|
||||
}
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.16.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,6 +45,26 @@ 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([]);
|
||||
@@ -69,8 +89,8 @@ test.describe("Agent profiles in the model picker", () => {
|
||||
page,
|
||||
}) => {
|
||||
const seed = await seedAgentProfiles([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.
|
||||
// With only the mock provider enabled on this host, the picker opens
|
||||
// directly into its models and shows its pinned profile.
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "agent-profiles-picker-",
|
||||
title: "Agent profiles picker",
|
||||
|
||||
@@ -0,0 +1,509 @@
|
||||
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();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -23,7 +23,15 @@ export interface DraftAgentProfileControls {
|
||||
}
|
||||
|
||||
export type AgentProfileApplyTarget =
|
||||
| { kind: "agent"; agentId: string; availableModeIds: readonly string[] | null }
|
||||
| {
|
||||
kind: "agent";
|
||||
agentId: string;
|
||||
availableModeIds: readonly string[] | null;
|
||||
currentProvider?: string | null;
|
||||
isSwitchInFlight?: () => boolean;
|
||||
onApplySameProvider?: () => void;
|
||||
onStageProviderSwitch?: (profile: MaterializedAgentProfile) => void;
|
||||
}
|
||||
| { kind: "draft"; controls: DraftAgentProfileControls };
|
||||
|
||||
/** Everything the model picker renders for one profile. It never sees the profile itself. */
|
||||
@@ -139,6 +147,16 @@ 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;
|
||||
@@ -148,7 +166,11 @@ export function useAgentProfilePicker(
|
||||
return;
|
||||
}
|
||||
void client
|
||||
.applyAgentConfig(target.agentId, toAgentConfigApply(reconciled))
|
||||
.applyAgentConfig(
|
||||
target.agentId,
|
||||
toAgentConfigApply(reconciled),
|
||||
target.currentProvider ? { expectedProvider: target.currentProvider } : undefined,
|
||||
)
|
||||
.then((notice) => showProviderNoticeToast(toast, notice))
|
||||
.catch((error) => {
|
||||
console.warn("[useAgentProfilePicker] applyAgentConfig failed", error);
|
||||
|
||||
@@ -101,7 +101,7 @@ function summaryRow(
|
||||
}
|
||||
|
||||
function staysVisibleWhenCollapsed(item: StreamItem): boolean {
|
||||
return isTurnTrigger(item) || item.kind === "compaction";
|
||||
return isTurnTrigger(item) || item.kind === "compaction" || item.kind === "provider_switch";
|
||||
}
|
||||
|
||||
function findLastReplyIndex(tail: StreamItem[], start: number, end: number): number {
|
||||
|
||||
@@ -37,6 +37,7 @@ import {
|
||||
ToolCall,
|
||||
TodoListCard,
|
||||
CompactionMarker,
|
||||
ProviderSwitchMarker,
|
||||
MessageOuterSpacingProvider,
|
||||
type InlinePathTarget,
|
||||
} from "@/components/message";
|
||||
@@ -57,6 +58,7 @@ 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";
|
||||
@@ -715,8 +717,15 @@ 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}
|
||||
@@ -728,7 +737,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
images={item.images}
|
||||
attachments={item.attachments}
|
||||
timestamp={item.timestamp.getTime()}
|
||||
capabilities={context.capabilities}
|
||||
capabilities={canRewindPrompt ? context.capabilities : undefined}
|
||||
client={client}
|
||||
isFirstInGroup={layoutItem.isFirstInUserGroup}
|
||||
isLastInGroup={layoutItem.isLastInUserGroup}
|
||||
@@ -739,7 +748,14 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
/>
|
||||
);
|
||||
},
|
||||
[context.capabilities, agentId, client, pendingClientMessageIds, resolvedServerId],
|
||||
[
|
||||
activeSegmentStartSeq,
|
||||
context.capabilities,
|
||||
agentId,
|
||||
client,
|
||||
pendingClientMessageIds,
|
||||
resolvedServerId,
|
||||
],
|
||||
);
|
||||
|
||||
const renderAssistantMessageItem = useCallback(
|
||||
@@ -945,6 +961,18 @@ 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} />
|
||||
|
||||
@@ -75,6 +75,7 @@ export function estimateStreamItemHeight({
|
||||
case "notification":
|
||||
return 88;
|
||||
case "compaction":
|
||||
case "provider_switch":
|
||||
return 72;
|
||||
default:
|
||||
return 120;
|
||||
|
||||
@@ -19,9 +19,11 @@ 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";
|
||||
@@ -40,13 +42,17 @@ 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,
|
||||
@@ -1487,6 +1493,188 @@ 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,7 +10,11 @@ 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 { isRewindableMessage, useRewindMenuItems } from "./use-rewind-capabilities";
|
||||
import {
|
||||
isPromptInActiveSegment,
|
||||
isRewindableMessage,
|
||||
useRewindMenuItems,
|
||||
} from "./use-rewind-capabilities";
|
||||
|
||||
export function RewindCommandCenterRegistration({
|
||||
serverId,
|
||||
@@ -42,10 +46,16 @@ export function RewindCommandCenterRegistration({
|
||||
if (timeline.status !== "synced" || timeline.newer === "available") {
|
||||
return undefined;
|
||||
}
|
||||
return (
|
||||
const candidate =
|
||||
session.agentStreamHead.get(agentId)?.findLast((item) => item.kind === "user_message") ??
|
||||
timeline.items.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;
|
||||
});
|
||||
const { rewindAgent, isPending } = useRewindAgentMutation({
|
||||
serverId,
|
||||
|
||||
@@ -26,6 +26,20 @@ 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<
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
import type { SelectedFile } from "@/attachments/selected-file";
|
||||
import { FILE_UPLOAD_MAX_BYTES } from "@/attachments/upload-limit";
|
||||
import type { ForgeSearchItem } from "@getpaseo/protocol/messages";
|
||||
import type { ActiveTurnBehavior } from "@getpaseo/protocol/messages";
|
||||
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 {
|
||||
AttachmentMetadata,
|
||||
ComposerAttachment,
|
||||
@@ -56,6 +62,20 @@ 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: {
|
||||
@@ -197,6 +217,8 @@ export interface DispatchComposerAgentMessageInput {
|
||||
submission: MessageSubmissionWriter;
|
||||
activeTurnBehavior?: ActiveTurnBehavior;
|
||||
activeTurnId?: string;
|
||||
stagedProviderSwitch?: StagedProviderSwitch | null;
|
||||
onProviderSwitchCommitted?: (agent: AgentSnapshotPayload | undefined) => void | Promise<void>;
|
||||
}
|
||||
|
||||
export async function dispatchComposerAgentMessage(
|
||||
@@ -212,13 +234,29 @@ export async function dispatchComposerAgentMessage(
|
||||
timestamp: new Date(),
|
||||
images: wirePayload.images,
|
||||
attachments: wirePayload.attachments,
|
||||
...(input.activeTurnBehavior === "steer" && input.activeTurnId
|
||||
...(input.activeTurnBehavior === "steer" && input.activeTurnId && !input.stagedProviderSwitch
|
||||
? { 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 } : {}),
|
||||
@@ -228,6 +266,9 @@ 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,12 +16,21 @@ 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 {
|
||||
@@ -102,6 +111,7 @@ import {
|
||||
type AgentProfilePicker,
|
||||
type AgentProfileSeed,
|
||||
type DraftAgentProfileControls,
|
||||
type MaterializedAgentProfile,
|
||||
} from "@/agent-profiles";
|
||||
import { buildSettingsHostSectionRoute } from "@/utils/host-routes";
|
||||
|
||||
@@ -138,6 +148,7 @@ interface ControlledAgentControlsProps {
|
||||
modeControl?: AgentModeControlValue | null;
|
||||
modelSelectorServerId?: string | null;
|
||||
isCompactLayout?: boolean;
|
||||
openModelBrowserAtProviders?: boolean;
|
||||
}
|
||||
|
||||
export interface DraftAgentControlsProps {
|
||||
@@ -451,6 +462,7 @@ function ControlledAgentControls({
|
||||
modeControl,
|
||||
modelSelectorServerId = null,
|
||||
isCompactLayout,
|
||||
openModelBrowserAtProviders,
|
||||
}: ControlledAgentControlsProps) {
|
||||
const { t } = useTranslation();
|
||||
const isCompactFormFactor = useIsCompactFormFactor();
|
||||
@@ -710,6 +722,7 @@ function ControlledAgentControls({
|
||||
showLabels={presentation.showModelLabel}
|
||||
modelSelectorServerId={modelSelectorServerId}
|
||||
canSwitchProvider={Boolean(onSelectProviderAndModel)}
|
||||
openModelBrowserAtProviders={openModelBrowserAtProviders}
|
||||
/>
|
||||
)}
|
||||
{!isCompact ? (
|
||||
@@ -907,6 +920,7 @@ interface SheetAgentControlsContentProps extends AgentControlsContentProps {
|
||||
displayThinking: string | null;
|
||||
handleSheetModelSelect: (providerId: string, modelId: string) => void;
|
||||
canSwitchProvider: boolean;
|
||||
openModelBrowserAtProviders?: boolean;
|
||||
}
|
||||
|
||||
function SheetAgentControlsContent(props: SheetAgentControlsContentProps) {
|
||||
@@ -939,6 +953,7 @@ function SheetAgentControlsContent(props: SheetAgentControlsContentProps) {
|
||||
showLabels,
|
||||
modelSelectorServerId,
|
||||
canSwitchProvider,
|
||||
openModelBrowserAtProviders,
|
||||
} = props;
|
||||
|
||||
const sheetControls = (
|
||||
@@ -988,6 +1003,7 @@ function SheetAgentControlsContent(props: SheetAgentControlsContentProps) {
|
||||
glyphs={glyphs}
|
||||
showLabels={showLabels}
|
||||
canSwitchProvider={canSwitchProvider}
|
||||
openModelBrowserAtProviders={openModelBrowserAtProviders}
|
||||
>
|
||||
{sheetControls}
|
||||
</CompactModelSheet>
|
||||
@@ -1006,6 +1022,148 @@ 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,
|
||||
@@ -1013,15 +1171,22 @@ export const AgentControls = memo(function AgentControls({
|
||||
onDropdownClose,
|
||||
isCompactLayout,
|
||||
}: AgentControlsProps) {
|
||||
const { updatePreferences } = useFormPreferences();
|
||||
const { preferences, 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 modeControl = useLiveAgentModeControl(serverId, agentId);
|
||||
const commandCenterModes = toCommandCenterModes(modeControl);
|
||||
const modeProviderDefinitions = getModeProviderDefinitions(modeControl);
|
||||
const liveModeControl = useLiveAgentModeControl(serverId, agentId);
|
||||
|
||||
const {
|
||||
entries: snapshotEntries,
|
||||
@@ -1031,24 +1196,35 @@ 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, agent?.provider),
|
||||
[snapshotEntries, agent?.provider],
|
||||
() => resolveProviderSnapshotEntry(snapshotEntries, effectiveProvider),
|
||||
[snapshotEntries, effectiveProvider],
|
||||
);
|
||||
|
||||
const models = filterSelectableModels(snapshotSelectedEntry?.models ?? null);
|
||||
const selectedProviderIsLoading = snapshotSelectedEntry?.status === "loading";
|
||||
|
||||
const agentProviderDefinitions = useMemo(
|
||||
() => buildAgentProviderDefinitions(agent?.provider, snapshotEntries),
|
||||
[agent?.provider, snapshotEntries],
|
||||
() => buildAgentProviderDefinitions(effectiveProvider, snapshotEntries),
|
||||
[effectiveProvider, snapshotEntries],
|
||||
);
|
||||
|
||||
const agentProviderModels = useMemo(
|
||||
() => buildAgentProviderModels(agent?.provider, models),
|
||||
[agent?.provider, models],
|
||||
() => buildAgentProviderModels(effectiveProvider, models),
|
||||
[effectiveProvider, 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)];
|
||||
}
|
||||
@@ -1056,14 +1232,19 @@ export const AgentControls = memo(function AgentControls({
|
||||
providerDefinitions: agentProviderDefinitions,
|
||||
modelsByProvider: agentProviderModels,
|
||||
});
|
||||
}, [agentProviderDefinitions, agentProviderModels, snapshotSelectedEntry]);
|
||||
}, [
|
||||
agentProviderDefinitions,
|
||||
agentProviderModels,
|
||||
effectiveProvider,
|
||||
snapshotEntries,
|
||||
snapshotSelectedEntry,
|
||||
supportsProviderSwitching,
|
||||
]);
|
||||
|
||||
const modelSelection = resolveAgentModelSelection({
|
||||
const modelSelection = resolveAgentModelSelectionWithStagedSwitch({
|
||||
models,
|
||||
runtimeModelId: agent?.runtimeModelId,
|
||||
configuredModelId: agent?.model,
|
||||
runtimeThinkingOptionId: agent?.runtimeThinkingOptionId,
|
||||
explicitThinkingOptionId: agent?.thinkingOptionId,
|
||||
agent,
|
||||
activeStagedSwitch,
|
||||
});
|
||||
|
||||
const modelOptions = useMemo<AgentControlOption[]>(() => {
|
||||
@@ -1080,13 +1261,71 @@ export const AgentControls = memo(function AgentControls({
|
||||
const agentProvider = agent?.provider;
|
||||
const activeModelId = modelSelection.activeModelId;
|
||||
|
||||
const handleSelectModel = useCallback(
|
||||
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(
|
||||
async (modelId: string) => {
|
||||
if (!client || !agentProvider) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await client.setAgentModel(agentId, modelId);
|
||||
await client.setAgentModel(agentId, modelId, { expectedProvider: agentProvider });
|
||||
await updatePreferences((current) =>
|
||||
mergeProviderPreferences({
|
||||
preferences: current,
|
||||
@@ -1101,21 +1340,147 @@ export const AgentControls = memo(function AgentControls({
|
||||
},
|
||||
[agentId, agentProvider, client, toast, updatePreferences],
|
||||
);
|
||||
const handleSelectCommandCenterModel = useCallback(
|
||||
(_provider: AgentProvider, modelId: string) => handleSelectModel(modelId),
|
||||
[handleSelectModel],
|
||||
|
||||
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,
|
||||
],
|
||||
);
|
||||
|
||||
// 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 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],
|
||||
);
|
||||
|
||||
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],
|
||||
);
|
||||
const profileModeIds = useMemo(
|
||||
() => resolveSnapshotModeIds(snapshotSelectedEntry),
|
||||
[snapshotSelectedEntry],
|
||||
() => resolveSnapshotModeIds(liveSnapshotEntry),
|
||||
[liveSnapshotEntry],
|
||||
);
|
||||
const profileTarget = useMemo<AgentProfileApplyTarget>(
|
||||
() => ({ kind: "agent", agentId, availableModeIds: profileModeIds }),
|
||||
[agentId, profileModeIds],
|
||||
() => ({
|
||||
kind: "agent",
|
||||
agentId,
|
||||
availableModeIds: profileModeIds,
|
||||
currentProvider: agentProvider,
|
||||
isSwitchInFlight: () => isStagedProviderSwitchInFlight(serverId, agentId),
|
||||
onApplySameProvider: handleClearStagedSwitchOnProfile,
|
||||
onStageProviderSwitch: supportsProviderSwitching ? handleStageAgentProfileSwitch : undefined,
|
||||
}),
|
||||
[
|
||||
agentId,
|
||||
agentProvider,
|
||||
handleClearStagedSwitchOnProfile,
|
||||
handleStageAgentProfileSwitch,
|
||||
profileModeIds,
|
||||
serverId,
|
||||
supportsProviderSwitching,
|
||||
],
|
||||
);
|
||||
const agentProfiles = useAgentProfilePicker({
|
||||
serverId,
|
||||
@@ -1128,6 +1493,13 @@ 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;
|
||||
}
|
||||
@@ -1148,18 +1520,35 @@ export const AgentControls = memo(function AgentControls({
|
||||
});
|
||||
}
|
||||
void client
|
||||
.setAgentThinkingOption(agentId, thinkingOptionId)
|
||||
.setAgentThinkingOption(agentId, thinkingOptionId, { expectedProvider: agentProvider })
|
||||
.then((notice) => showProviderNoticeToast(toast, notice))
|
||||
.catch((error) => {
|
||||
console.warn("[AgentControls] setAgentThinkingOption failed", error);
|
||||
toast.error(toErrorMessage(error));
|
||||
});
|
||||
},
|
||||
[activeModelId, agentId, agentProvider, client, toast, updatePreferences],
|
||||
[
|
||||
activeModelId,
|
||||
activeStagedSwitch,
|
||||
agentId,
|
||||
agentProvider,
|
||||
client,
|
||||
serverId,
|
||||
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;
|
||||
}
|
||||
@@ -1176,15 +1565,36 @@ export const AgentControls = memo(function AgentControls({
|
||||
).catch((error) => {
|
||||
console.warn("[AgentControls] persist option preference failed", error);
|
||||
});
|
||||
void client.setAgentOptions(agentId, { [key]: value }).catch((error) => {
|
||||
console.warn("[AgentControls] setAgentOptions failed", error);
|
||||
toast.error(toErrorMessage(error));
|
||||
});
|
||||
void client
|
||||
.setAgentOptions(agentId, { [key]: value }, { expectedProvider: agentProvider })
|
||||
.catch((error) => {
|
||||
console.warn("[AgentControls] setAgentOptions failed", error);
|
||||
toast.error(toErrorMessage(error));
|
||||
});
|
||||
},
|
||||
[agentId, agentProvider, client, toast, updatePreferences],
|
||||
[
|
||||
activeStagedSwitch,
|
||||
agentId,
|
||||
agentProvider,
|
||||
client,
|
||||
serverId,
|
||||
stagedDraftOptions,
|
||||
toast,
|
||||
updatePreferences,
|
||||
],
|
||||
);
|
||||
|
||||
const agentOptionControls = useAgentOptionControls(agent, handleSetOption);
|
||||
const liveOptionControls = useAgentOptionControls(agent, handleSetOption);
|
||||
const agentOptionControls = useMemo<ComposerOptionControls>(
|
||||
() =>
|
||||
resolveAgentOptionControlsForComposer({
|
||||
activeStagedSwitch,
|
||||
stagedControls: stagedDraftOptions.optionControls,
|
||||
liveOptionControls,
|
||||
onSetOption: handleSetOption,
|
||||
}),
|
||||
[activeStagedSwitch, handleSetOption, liveOptionControls, stagedDraftOptions.optionControls],
|
||||
);
|
||||
|
||||
// The agent's composer exists apart from this component; while this is mounted, prompt
|
||||
// commands go through the input the user is typing in.
|
||||
@@ -1208,12 +1618,12 @@ export const AgentControls = memo(function AgentControls({
|
||||
() => ({
|
||||
serverId,
|
||||
ownerKey: agentId,
|
||||
provider: agentProvider,
|
||||
provider: effectiveProvider,
|
||||
providerDefinitions: modeProviderDefinitions,
|
||||
profiles: agentProfiles,
|
||||
models: {
|
||||
providers: agentModelSelectorProviders,
|
||||
selectedProvider: agentProvider,
|
||||
selectedProvider: effectiveProvider,
|
||||
selectedModelId: activeModelId,
|
||||
select: handleSelectCommandCenterModel,
|
||||
},
|
||||
@@ -1232,7 +1642,7 @@ export const AgentControls = memo(function AgentControls({
|
||||
client,
|
||||
agentId,
|
||||
agentModelSelectorProviders,
|
||||
agentProvider,
|
||||
effectiveProvider,
|
||||
commandCenterModes,
|
||||
handleSelectCommandCenterModel,
|
||||
handleSelectThinkingOption,
|
||||
@@ -1252,8 +1662,8 @@ export const AgentControls = memo(function AgentControls({
|
||||
);
|
||||
|
||||
const handleModelSelectorOpen = useCallback(() => {
|
||||
refetchSnapshotIfStale(agentProvider);
|
||||
}, [agentProvider, refetchSnapshotIfStale]);
|
||||
refetchSnapshotIfStale(supportsProviderSwitching ? undefined : effectiveProvider);
|
||||
}, [effectiveProvider, refetchSnapshotIfStale, supportsProviderSwitching]);
|
||||
|
||||
const handleRetryModelProvider = useCallback(
|
||||
(provider: AgentProvider) => {
|
||||
@@ -1266,6 +1676,18 @@ 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}
|
||||
@@ -1273,21 +1695,17 @@ export const AgentControls = memo(function AgentControls({
|
||||
<>
|
||||
{profileEditor.element}
|
||||
<ControlledAgentControls
|
||||
provider={agent.provider}
|
||||
{...resolvedControlProps}
|
||||
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}
|
||||
@@ -1521,6 +1939,7 @@ 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)
|
||||
.setAgentMode(agentId, modeId, { expectedProvider: slice.provider })
|
||||
.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({
|
||||
canSwitchProvider: true,
|
||||
openAtProviders: true,
|
||||
providers: [codex],
|
||||
selectedProvider: "codex",
|
||||
}),
|
||||
).toEqual({ kind: "all" });
|
||||
});
|
||||
|
||||
it("opens a running agent directly at its fixed provider", () => {
|
||||
it("opens a running agent directly at its current provider even when other providers are available", () => {
|
||||
expect(
|
||||
resolveModelSheetOpening({
|
||||
canSwitchProvider: false,
|
||||
openAtProviders: 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({
|
||||
canSwitchProvider: false,
|
||||
openAtProviders: false,
|
||||
providers: [codex],
|
||||
selectedProvider: "",
|
||||
}),
|
||||
|
||||
@@ -2,15 +2,16 @@ import type { ModelBrowserView } from "@/components/model-browser-view";
|
||||
import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection";
|
||||
|
||||
export function resolveModelSheetOpening({
|
||||
canSwitchProvider,
|
||||
openAtProviders,
|
||||
providers,
|
||||
selectedProvider,
|
||||
}: {
|
||||
canSwitchProvider: boolean;
|
||||
/** Drafts open at the provider list; live agents open directly at their active provider. */
|
||||
openAtProviders: boolean;
|
||||
providers: ProviderSelectorProvider[];
|
||||
selectedProvider: string;
|
||||
}): ModelBrowserView {
|
||||
if (canSwitchProvider) return { kind: "all" };
|
||||
if (openAtProviders) return { kind: "all" };
|
||||
|
||||
const provider = providers.find((entry) => entry.id === selectedProvider) ?? providers[0] ?? null;
|
||||
return provider
|
||||
|
||||
@@ -68,6 +68,8 @@ 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;
|
||||
@@ -160,6 +162,7 @@ export function CompactModelSheet({
|
||||
glyphs,
|
||||
showLabels,
|
||||
canSwitchProvider,
|
||||
openModelBrowserAtProviders = false,
|
||||
contextBridge = null,
|
||||
children,
|
||||
}: CompactModelSheetProps) {
|
||||
@@ -239,7 +242,7 @@ export function CompactModelSheet({
|
||||
const openModelBrowser = useCallback(() => {
|
||||
Keyboard.dismiss();
|
||||
const destination = resolveModelSheetOpening({
|
||||
canSwitchProvider,
|
||||
openAtProviders: openModelBrowserAtProviders,
|
||||
providers: availableProviders,
|
||||
selectedProvider,
|
||||
});
|
||||
@@ -249,7 +252,7 @@ export function CompactModelSheet({
|
||||
modelBrowser.drillDown(destination.providerId, destination.providerLabel);
|
||||
}
|
||||
setIsModelBrowserOpen(true);
|
||||
}, [availableProviders, canSwitchProvider, modelBrowser, selectedProvider]);
|
||||
}, [availableProviders, modelBrowser, openModelBrowserAtProviders, selectedProvider]);
|
||||
|
||||
const closeModelBrowser = useCallback(() => {
|
||||
setIsModelBrowserOpen(false);
|
||||
|
||||
@@ -9,6 +9,20 @@ 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,
|
||||
@@ -48,6 +62,7 @@ import { usePanelStore, type MobilePanelView } from "@/stores/panel-store";
|
||||
import { usePointerCapabilities } from "@/hooks/pointer-capabilities";
|
||||
import { useShallow } from "zustand/shallow";
|
||||
import {
|
||||
ArrowRightLeft,
|
||||
ArrowUp,
|
||||
Square,
|
||||
Pencil,
|
||||
@@ -298,16 +313,29 @@ 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 {
|
||||
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,
|
||||
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,
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -1351,10 +1379,56 @@ 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);
|
||||
@@ -1709,25 +1783,62 @@ function ComposerContentImpl({
|
||||
if (!client) {
|
||||
throw new Error(t("workspace.terminal.hostDisconnected"));
|
||||
}
|
||||
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,
|
||||
});
|
||||
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);
|
||||
}
|
||||
}
|
||||
onAttentionPromptSend?.();
|
||||
};
|
||||
}, [appSettings.sendBehavior, client, onAttentionPromptSend, serverId, supportsForgeSearch, t]);
|
||||
@@ -1803,7 +1914,7 @@ function ComposerContentImpl({
|
||||
attachments: outgoingAttachments,
|
||||
hasExternalContent,
|
||||
allowEmptySubmit,
|
||||
forceSend,
|
||||
forceSend: stagedSwitch && isAgentRunning ? false : forceSend,
|
||||
submitBehavior,
|
||||
isAgentRunning,
|
||||
// Parent-managed submits are still valid submit paths even when the
|
||||
@@ -1845,6 +1956,7 @@ function ComposerContentImpl({
|
||||
queueMessage,
|
||||
setSelectedAttachments,
|
||||
replaceUserInput,
|
||||
stagedSwitch,
|
||||
submitBehavior,
|
||||
submitMessage,
|
||||
t,
|
||||
@@ -2079,15 +2191,17 @@ function ComposerContentImpl({
|
||||
queue: queueWriter,
|
||||
});
|
||||
if (!result) return;
|
||||
useSessionStore.getState().setQueuedSendError(serverId, agentId, null);
|
||||
replaceUserInput(result.text);
|
||||
setSelectedAttachments(result.attachments);
|
||||
},
|
||||
[agentId, queueWriter, replaceUserInput, setSelectedAttachments],
|
||||
[agentId, queueWriter, replaceUserInput, serverId, 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,
|
||||
@@ -2101,7 +2215,7 @@ function ComposerContentImpl({
|
||||
setSendError(result.errorMessage);
|
||||
}
|
||||
},
|
||||
[agentId, queueWriter, submitMessage, t],
|
||||
[agentId, queueWriter, serverId, submitMessage, t],
|
||||
);
|
||||
|
||||
const handleQueue = useCallback(
|
||||
@@ -2554,18 +2668,71 @@ 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;
|
||||
const displayError =
|
||||
externalError || sendError || failedStartupSettings?.errorMessage || queuedSendError;
|
||||
const sendErrorNode = useMemo(
|
||||
() =>
|
||||
displayError ? (
|
||||
<Alert variant="error" size="sm" description={displayError} testID="composer-error" />
|
||||
<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>
|
||||
) : null,
|
||||
[displayError],
|
||||
[
|
||||
displayError,
|
||||
failedStartupSettings,
|
||||
handleDismissFailedStartupSettings,
|
||||
handleRetryFailedStartupSettings,
|
||||
t,
|
||||
],
|
||||
);
|
||||
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
|
||||
@@ -2591,6 +2758,7 @@ function ComposerContentImpl({
|
||||
>
|
||||
<View style={inputAreaContentStyle}>
|
||||
{isFullscreen ? null : queueList}
|
||||
{isFullscreen ? null : stagedSwitchBannerNode}
|
||||
{!isFullscreen && sendErrorNode}
|
||||
|
||||
<ComposerAutocompleteBinding
|
||||
@@ -2846,9 +3014,35 @@ 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);
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
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
@@ -0,0 +1,86 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,401 @@
|
||||
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,
|
||||
);
|
||||
}
|
||||
@@ -205,6 +205,10 @@ export const ar: TranslationResources = {
|
||||
pasteImageFailed: "تعذر لصق الصورة",
|
||||
fileTooLarge: "{{fileName}} is too large (max {{size}})",
|
||||
},
|
||||
providerSwitch: {
|
||||
switchingNextMessage: "التبديل إلى {{provider}} في الرسالة التالية",
|
||||
switchingAfterTurn: "سيتم التبديل إلى {{provider}} بعد هذا الدور",
|
||||
},
|
||||
clientCommands: {
|
||||
archiveAgent: "أرشفة الوكيل الحالي",
|
||||
freshDraft: "أرشفة هذا الوكيل وابدأ مسودة جديدة",
|
||||
@@ -436,6 +440,13 @@ export const ar: TranslationResources = {
|
||||
turnFooter: {
|
||||
workedFor: "عمل لمدة {{duration}}",
|
||||
},
|
||||
providerSwitch: {
|
||||
switched: "تم التبديل من {{from}} إلى {{to}}",
|
||||
contextSummary: "تم نقل {{count}} عنصر ({{chars}} / {{budget}} حرف)",
|
||||
trimmed: "تم الاقتطاع: {{reasons}}",
|
||||
reasonTailWindow: "سجل أقدم خارج النطاق",
|
||||
reasonCharBudget: "حد الأحرف",
|
||||
},
|
||||
compaction: {
|
||||
loading: "الضغط...",
|
||||
auto: "يتم ضغط السياق تلقائيًا",
|
||||
|
||||
@@ -203,6 +203,10 @@ 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",
|
||||
@@ -435,6 +439,13 @@ 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",
|
||||
|
||||
@@ -207,6 +207,10 @@ 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",
|
||||
@@ -441,6 +445,13 @@ 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",
|
||||
|
||||
@@ -208,6 +208,10 @@ 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",
|
||||
@@ -441,6 +445,13 @@ 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",
|
||||
|
||||
@@ -207,6 +207,10 @@ export const ja: TranslationResources = {
|
||||
pasteImageFailed: "画像を貼り付けられませんでした",
|
||||
fileTooLarge: "{{fileName}}が大きすぎます(最大{{size}})",
|
||||
},
|
||||
providerSwitch: {
|
||||
switchingNextMessage: "次のメッセージで {{provider}} に切り替えます",
|
||||
switchingAfterTurn: "このターン終了後に {{provider}} に切り替えます",
|
||||
},
|
||||
clientCommands: {
|
||||
archiveAgent: "現在のエージェントをアーカイブ",
|
||||
freshDraft: "このエージェントをアーカイブして新しい下書きを開始",
|
||||
@@ -441,6 +445,13 @@ export const ja: TranslationResources = {
|
||||
turnFooter: {
|
||||
workedFor: "作業時間 {{duration}}",
|
||||
},
|
||||
providerSwitch: {
|
||||
switched: "{{from}} から {{to}} に切り替えました",
|
||||
contextSummary: "{{count}} 件を引き継ぎました ({{chars}} / {{budget}} 文字)",
|
||||
trimmed: "省略: {{reasons}}",
|
||||
reasonTailWindow: "ウィンドウ外の古い履歴",
|
||||
reasonCharBudget: "文字数上限",
|
||||
},
|
||||
compaction: {
|
||||
loading: "コンテキストを圧縮中...",
|
||||
auto: "コンテキストが自動的に圧縮されました",
|
||||
|
||||
@@ -205,6 +205,10 @@ export const ko: TranslationResources = {
|
||||
pasteImageFailed: "이미지를 붙여넣지 못했습니다.",
|
||||
fileTooLarge: "{{fileName}}이(가) 너무 큽니다 (최대 {{size}})",
|
||||
},
|
||||
providerSwitch: {
|
||||
switchingNextMessage: "다음 메시지에서 {{provider}}(으)로 전환합니다",
|
||||
switchingAfterTurn: "이 턴이 끝난 후 {{provider}}(으)로 전환합니다",
|
||||
},
|
||||
clientCommands: {
|
||||
archiveAgent: "현재 에이전트 보관",
|
||||
freshDraft: "이 에이전트를 보관하고 새 초안을 시작합니다",
|
||||
@@ -437,6 +441,13 @@ export const ko: TranslationResources = {
|
||||
turnFooter: {
|
||||
workedFor: "작업 시간 {{duration}}",
|
||||
},
|
||||
providerSwitch: {
|
||||
switched: "{{from}}에서 {{to}}(으)로 전환됨",
|
||||
contextSummary: "{{count}}개 항목 전달됨 ({{chars}} / {{budget}}자)",
|
||||
trimmed: "생략됨: {{reasons}}",
|
||||
reasonTailWindow: "창 범위를 벗어난 이전 기록",
|
||||
reasonCharBudget: "문자 수 제한",
|
||||
},
|
||||
compaction: {
|
||||
loading: "압축하는 중...",
|
||||
auto: "컨텍스트가 자동으로 압축되었습니다",
|
||||
|
||||
@@ -206,6 +206,10 @@ 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",
|
||||
@@ -440,6 +444,13 @@ 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",
|
||||
|
||||
@@ -207,6 +207,10 @@ export const ru: TranslationResources = {
|
||||
pasteImageFailed: "Не удалось вставить изображение",
|
||||
fileTooLarge: "Файл {{fileName}} слишком большой (максимальный размер: {{size}})",
|
||||
},
|
||||
providerSwitch: {
|
||||
switchingNextMessage: "Переключение на {{provider}} в следующем сообщении",
|
||||
switchingAfterTurn: "Переключение на {{provider}} после этого хода",
|
||||
},
|
||||
clientCommands: {
|
||||
archiveAgent: "Архивировать текущего агента",
|
||||
freshDraft: "Архивировать этого агента и создать новый черновик",
|
||||
@@ -440,6 +444,13 @@ export const ru: TranslationResources = {
|
||||
turnFooter: {
|
||||
workedFor: "Время работы: {{duration}}",
|
||||
},
|
||||
providerSwitch: {
|
||||
switched: "Переключено с {{from}} на {{to}}",
|
||||
contextSummary: "Передано элементов: {{count}} ({{chars}} / {{budget}} симв.)",
|
||||
trimmed: "Сокращено: {{reasons}}",
|
||||
reasonTailWindow: "более ранняя история вне окна",
|
||||
reasonCharBudget: "лимит символов",
|
||||
},
|
||||
compaction: {
|
||||
loading: "Сжатие контекста...",
|
||||
auto: "Контекст сжат автоматически",
|
||||
|
||||
@@ -205,6 +205,10 @@ export const zhCN: TranslationResources = {
|
||||
pasteImageFailed: "无法粘贴图片",
|
||||
fileTooLarge: "{{fileName}} is too large (max {{size}})",
|
||||
},
|
||||
providerSwitch: {
|
||||
switchingNextMessage: "下一条消息将切换到 {{provider}}",
|
||||
switchingAfterTurn: "本轮结束后将切换到 {{provider}}",
|
||||
},
|
||||
clientCommands: {
|
||||
archiveAgent: "归档当前 Agent",
|
||||
freshDraft: "归档此 Agent 并开始新的草稿",
|
||||
@@ -436,6 +440,13 @@ export const zhCN: TranslationResources = {
|
||||
turnFooter: {
|
||||
workedFor: "工作了 {{duration}}",
|
||||
},
|
||||
providerSwitch: {
|
||||
switched: "已从 {{from}} 切换到 {{to}}",
|
||||
contextSummary: "已传递 {{count}} 项上下文({{chars}} / {{budget}} 字符)",
|
||||
trimmed: "已裁剪:{{reasons}}",
|
||||
reasonTailWindow: "超出窗口的早期历史",
|
||||
reasonCharBudget: "字符预算限制",
|
||||
},
|
||||
compaction: {
|
||||
loading: "正在压缩...",
|
||||
auto: "上下文已自动压缩",
|
||||
|
||||
@@ -224,8 +224,9 @@ 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) {
|
||||
removeEntryRef.current?.({ restoreFocus: shouldRestoreFocus });
|
||||
removeEntry?.({ restoreFocus: shouldRestoreFocus });
|
||||
}
|
||||
registeredRef.current = false;
|
||||
if (shouldRestoreFocus) {
|
||||
@@ -268,8 +269,14 @@ 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?.();
|
||||
@@ -277,7 +284,7 @@ export function useOverlayRegistration({
|
||||
detachedRemoveEntryRef.current = null;
|
||||
registeredRef.current = false;
|
||||
};
|
||||
}, [active, syncRegistration]);
|
||||
}, [syncRegistration]);
|
||||
|
||||
return setScope;
|
||||
}
|
||||
|
||||
@@ -74,6 +74,74 @@ 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", () => {
|
||||
|
||||
@@ -65,6 +65,7 @@ function sourceTimelineItem(item: StreamItem): AgentTimelineItem | null {
|
||||
...(item.preTokens !== undefined ? { preTokens: item.preTokens } : {}),
|
||||
};
|
||||
case "plugin":
|
||||
case "provider_switch":
|
||||
case "turn_summary":
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -83,8 +83,18 @@ 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";
|
||||
@@ -1918,6 +1928,7 @@ 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>();
|
||||
@@ -2882,9 +2893,58 @@ 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)) return;
|
||||
if (this.queuedAgentDrainInFlight.has(drainKey)) {
|
||||
this.queuedAgentDrainPending.add(drainKey);
|
||||
return;
|
||||
}
|
||||
const store = useSessionStore.getState();
|
||||
const session = store.sessions[serverId];
|
||||
const queue = session?.queuedMessages.get(agentId);
|
||||
@@ -2893,7 +2953,11 @@ 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,
|
||||
@@ -2903,28 +2967,69 @@ export class HostRuntimeStore {
|
||||
write: (update) => useSessionStore.getState().setQueuedMessages(serverId, update),
|
||||
},
|
||||
submitMessage: async ({ text, attachments }) => {
|
||||
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",
|
||||
});
|
||||
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);
|
||||
}
|
||||
}
|
||||
},
|
||||
})
|
||||
.then((result) => {
|
||||
if (result.status === "failed") {
|
||||
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);
|
||||
console.error("[HostRuntime] failed to drain queued agent message", {
|
||||
serverId,
|
||||
agentId,
|
||||
@@ -2935,6 +3040,9 @@ export class HostRuntimeStore {
|
||||
})
|
||||
.finally(() => {
|
||||
this.queuedAgentDrainInFlight.delete(drainKey);
|
||||
const hadPendingDrain = this.queuedAgentDrainPending.delete(drainKey);
|
||||
if (!drainSent || !hadPendingDrain) return;
|
||||
this.resumeIdleQueueIfReady(serverId, agentId);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -2960,6 +3068,10 @@ 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);
|
||||
}
|
||||
|
||||
@@ -170,6 +170,23 @@ 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"),
|
||||
@@ -371,6 +388,7 @@ 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(),
|
||||
@@ -482,6 +500,23 @@ 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) {
|
||||
@@ -527,6 +562,8 @@ 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 {
|
||||
@@ -579,6 +616,23 @@ 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 {
|
||||
@@ -631,6 +685,8 @@ 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") {
|
||||
@@ -862,7 +918,14 @@ function serializeTimeline(timeline: CachedTimeline): StoredTimeline | null {
|
||||
agentId: timeline.agentId,
|
||||
items,
|
||||
range: canPersistCoverage
|
||||
? { epoch: range.epoch, startSeq: range.startSeq, endSeq: range.endSeq }
|
||||
? {
|
||||
epoch: range.epoch,
|
||||
startSeq: range.startSeq,
|
||||
endSeq: range.endSeq,
|
||||
...(range.activeSegmentStartSeq !== undefined
|
||||
? { activeSegmentStartSeq: range.activeSegmentStartSeq }
|
||||
: {}),
|
||||
}
|
||||
: null,
|
||||
hasOlder: canPersistCoverage ? timeline.hasOlder : false,
|
||||
...(timeline.unsettledTurn
|
||||
|
||||
@@ -317,6 +317,7 @@ export interface AgentTimelineCursorState {
|
||||
epoch: string;
|
||||
startSeq: number;
|
||||
endSeq: number;
|
||||
activeSegmentStartSeq?: number;
|
||||
retainedRanges?: Array<{
|
||||
startSeq: number;
|
||||
endSeq: number;
|
||||
@@ -535,6 +536,7 @@ export interface SessionState {
|
||||
string,
|
||||
Array<{ id: string; text: string; attachments: ComposerAttachment[] }>
|
||||
>;
|
||||
queuedSendErrors: Map<string, string>;
|
||||
}
|
||||
|
||||
// Global store state
|
||||
@@ -726,6 +728,7 @@ 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;
|
||||
@@ -781,6 +784,7 @@ function createInitialSessionState(
|
||||
pendingPermissions: new Map(),
|
||||
fileExplorer: new Map(),
|
||||
queuedMessages: new Map(),
|
||||
queuedSendErrors: new Map(),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1976,6 +1980,32 @@ 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) => {
|
||||
|
||||
@@ -40,6 +40,7 @@ export interface TimelineCursor {
|
||||
epoch: string;
|
||||
startSeq: number;
|
||||
endSeq: number;
|
||||
activeSegmentStartSeq?: number;
|
||||
retainedRanges?: TimelineLoadedRange[];
|
||||
}
|
||||
|
||||
@@ -164,6 +165,9 @@ function mergeTimelineCoverage(
|
||||
epoch: current.epoch,
|
||||
startSeq: contiguous.startSeq,
|
||||
endSeq: contiguous.endSeq,
|
||||
...(current.activeSegmentStartSeq !== undefined
|
||||
? { activeSegmentStartSeq: current.activeSegmentStartSeq }
|
||||
: {}),
|
||||
...(retainedRanges.length > 0 ? { retainedRanges } : {}),
|
||||
};
|
||||
}
|
||||
@@ -172,7 +176,8 @@ function timelineCursorEquals(left: TimelineCursor, right: TimelineCursor): bool
|
||||
if (
|
||||
left.epoch !== right.epoch ||
|
||||
left.startSeq !== right.startSeq ||
|
||||
left.endSeq !== right.endSeq
|
||||
left.endSeq !== right.endSeq ||
|
||||
(left.activeSegmentStartSeq ?? 0) !== (right.activeSegmentStartSeq ?? 0)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
@@ -217,6 +222,7 @@ export interface ProcessTimelineResponseInput {
|
||||
hasOlder: boolean;
|
||||
mergeWindow?: boolean;
|
||||
retirements?: TimelineRetirement[];
|
||||
activeSegmentStartSeq?: number;
|
||||
};
|
||||
currentTail: StreamItem[];
|
||||
currentHead: StreamItem[];
|
||||
@@ -1304,6 +1310,57 @@ 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 {
|
||||
@@ -1459,8 +1516,12 @@ export function processTimelineResponse(
|
||||
|
||||
const nextTail = stampTimelineTurnMetrics(timelineResult.tail, payload.epoch, pageEntries);
|
||||
const nextHead = stampTimelineTurnMetrics(timelineResult.head, payload.epoch, pageEntries);
|
||||
const nextCursor = timelineResult.cursor;
|
||||
const cursorChanged = timelineResult.cursorChanged;
|
||||
const { cursor: nextCursor, cursorChanged } = mergeResponseActiveSegmentCursor(
|
||||
timelineResult.cursor,
|
||||
timelineResult.cursorChanged,
|
||||
currentCursor,
|
||||
payload.activeSegmentStartSeq,
|
||||
);
|
||||
sideEffects.push(...timelineResult.sideEffects);
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
@@ -1779,14 +1840,23 @@ 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: sequencing.nextTimelineCursor,
|
||||
cursorChanged: sequencing.cursorChanged,
|
||||
cursor: nextTimelineCursor,
|
||||
cursorChanged,
|
||||
acknowledgedClientMessageIds: streamResult.acknowledgedClientMessageIds ?? [],
|
||||
...(sequencing.shouldApplyStreamEvent && event.type === "timeline" && event.item.type === "todo"
|
||||
? { taskSnapshot: event.item.items }
|
||||
|
||||
@@ -4,6 +4,7 @@ import type {
|
||||
AgentProvider,
|
||||
AgentTimelineItem,
|
||||
JsonValue,
|
||||
ProviderSwitchContextSummary,
|
||||
ToolCallDetail,
|
||||
} from "@getpaseo/protocol/agent-types";
|
||||
import { timelineItemIdentity } from "@getpaseo/protocol/timeline-identity";
|
||||
@@ -89,9 +90,25 @@ 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 {
|
||||
@@ -1580,6 +1597,40 @@ 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" }>,
|
||||
@@ -1651,6 +1702,8 @@ 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:
|
||||
|
||||
@@ -16,6 +16,7 @@ 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;
|
||||
|
||||
@@ -47,5 +47,8 @@
|
||||
"typescript": "^5.2.2",
|
||||
"vitest": "^4.1.6",
|
||||
"zx": "^8.8.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.16.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -210,7 +210,12 @@ try {
|
||||
console.log("Foreground SIGINT reached the supervisor. The worker and ACP processes exited.");
|
||||
|
||||
daemon = await startSupervisor();
|
||||
const restoredIdle = (await daemon.client.fetchAgentTimeline(idle.id)).agent;
|
||||
// The stored timeline is served without reopening the agent.
|
||||
const storedIdle = (await daemon.client.fetchAgentTimeline(idle.id)).agent;
|
||||
assert.equal(storedIdle?.status, "closed");
|
||||
assert.equal(storedIdle?.requiresAttention, false);
|
||||
await daemon.client.refreshAgent(idle.id);
|
||||
const restoredIdle = (await daemon.client.fetchAgent(idle.id))?.agent;
|
||||
assert.equal(restoredIdle?.status, "idle");
|
||||
assert.equal(restoredIdle?.requiresAttention, false);
|
||||
await waitFor(async () => {
|
||||
|
||||
@@ -144,6 +144,7 @@ export const DEFAULT_CLIENT_CAPABILITIES = {
|
||||
[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,
|
||||
|
||||
@@ -1146,6 +1146,7 @@ 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,
|
||||
|
||||
@@ -127,6 +127,8 @@ import type {
|
||||
DaemonConfigReloadResponse,
|
||||
DiagnosticsResponse,
|
||||
AgentRewindResponseMessage,
|
||||
AgentProviderSwitchRequest,
|
||||
AgentProviderSwitchResponseMessage,
|
||||
ListTerminalsResponse,
|
||||
CreateTerminalResponse,
|
||||
SubscribeTerminalResponse,
|
||||
@@ -509,6 +511,28 @@ 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";
|
||||
@@ -4339,6 +4363,56 @@ 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,
|
||||
@@ -4427,12 +4501,29 @@ export class DaemonClient {
|
||||
}
|
||||
}
|
||||
|
||||
async setAgentMode(agentId: string, modeId: string): Promise<AgentProviderNotice | null> {
|
||||
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> {
|
||||
const requestId = this.createRequestId();
|
||||
const message = SessionInboundMessageSchema.parse({
|
||||
type: "set_agent_mode_request",
|
||||
agentId,
|
||||
modeId,
|
||||
...this.expectedProviderWireField(options),
|
||||
requestId,
|
||||
});
|
||||
const payload = await this.sendRequest({
|
||||
@@ -4455,12 +4546,17 @@ export class DaemonClient {
|
||||
return payload.notice ?? null;
|
||||
}
|
||||
|
||||
async setAgentModel(agentId: string, modelId: string | null): Promise<void> {
|
||||
async setAgentModel(
|
||||
agentId: string,
|
||||
modelId: string | null,
|
||||
options?: { expectedProvider?: AgentProvider },
|
||||
): 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({
|
||||
@@ -4482,13 +4578,19 @@ export class DaemonClient {
|
||||
}
|
||||
}
|
||||
|
||||
async setAgentFeature(agentId: string, featureId: string, value: unknown): Promise<void> {
|
||||
async setAgentFeature(
|
||||
agentId: string,
|
||||
featureId: string,
|
||||
value: unknown,
|
||||
options?: { expectedProvider?: AgentProvider },
|
||||
): 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({
|
||||
@@ -4517,6 +4619,7 @@ export class DaemonClient {
|
||||
async setAgentOptions(
|
||||
agentId: string,
|
||||
patch: Record<string, unknown>,
|
||||
options?: { expectedProvider?: AgentProvider },
|
||||
): Promise<AgentProviderNotice | null> {
|
||||
const legacy = this.legacyProviderOptions();
|
||||
if (legacy) {
|
||||
@@ -4524,11 +4627,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);
|
||||
await this.setAgentFeature(agentId, featureId, value, options);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
return this.applyAgentConfig(agentId, { options: patch });
|
||||
return this.applyAgentConfig(agentId, { options: patch }, options);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -4548,12 +4651,14 @@ 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({
|
||||
@@ -4586,6 +4691,7 @@ export class DaemonClient {
|
||||
async applyAgentConfig(
|
||||
agentId: string,
|
||||
config: AgentConfigApply,
|
||||
options?: { expectedProvider?: AgentProvider },
|
||||
): Promise<AgentProviderNotice | null> {
|
||||
let wireConfig = config;
|
||||
const legacy = this.legacyProviderOptions();
|
||||
@@ -4599,6 +4705,7 @@ export class DaemonClient {
|
||||
type: "agent.config.apply.request",
|
||||
agentId,
|
||||
config: wireConfig,
|
||||
...this.expectedProviderWireField(options),
|
||||
requestId,
|
||||
});
|
||||
const payload = await this.sendRequest({
|
||||
|
||||
@@ -401,6 +401,25 @@ 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;
|
||||
@@ -422,7 +441,8 @@ export type AgentTimelineItem =
|
||||
message: string;
|
||||
}
|
||||
| CompactionTimelineItem
|
||||
| PluginTimelineItem;
|
||||
| PluginTimelineItem
|
||||
| ProviderSwitchTimelineItem;
|
||||
|
||||
export type AgentStreamEvent =
|
||||
| { type: "thread_started"; sessionId: string; provider: AgentProvider }
|
||||
|
||||
@@ -48,6 +48,9 @@ export const CLIENT_CAPS = {
|
||||
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.
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -818,6 +818,22 @@ 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", [
|
||||
@@ -2181,6 +2197,7 @@ export const SetAgentModeRequestMessageSchema = z.object({
|
||||
type: z.literal("set_agent_mode_request"),
|
||||
agentId: z.string(),
|
||||
modeId: z.string(),
|
||||
expectedProvider: AgentProviderSchema.optional(),
|
||||
requestId: z.string(),
|
||||
});
|
||||
|
||||
@@ -2201,6 +2218,7 @@ 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(),
|
||||
});
|
||||
|
||||
@@ -2213,6 +2231,7 @@ 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(),
|
||||
});
|
||||
|
||||
@@ -2226,6 +2245,7 @@ export const SetAgentFeatureRequestMessageSchema = z.object({
|
||||
agentId: z.string(),
|
||||
featureId: z.string(),
|
||||
value: z.unknown(),
|
||||
expectedProvider: AgentProviderSchema.optional(),
|
||||
requestId: z.string(),
|
||||
});
|
||||
|
||||
@@ -2261,6 +2281,7 @@ export const AgentConfigApplyRequestMessageSchema = z.object({
|
||||
type: z.literal("agent.config.apply.request"),
|
||||
agentId: z.string(),
|
||||
config: AgentConfigApplySchema,
|
||||
expectedProvider: AgentProviderSchema.optional(),
|
||||
requestId: z.string(),
|
||||
});
|
||||
|
||||
@@ -2300,6 +2321,21 @@ 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,
|
||||
@@ -3621,6 +3657,7 @@ export const SessionInboundMessageSchema = z.discriminatedUnion("type", [
|
||||
WorkspaceArchiveUndoRequestSchema,
|
||||
SetVoiceModeMessageSchema,
|
||||
SendAgentMessageRequestSchema,
|
||||
AgentProviderSwitchRequestSchema,
|
||||
WaitForFinishRequestSchema,
|
||||
DaemonGetStatusRequestSchema,
|
||||
DaemonGetPairingOfferRequestSchema,
|
||||
@@ -4096,6 +4133,8 @@ export const ServerInfoStatusPayloadSchema = z
|
||||
// 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.
|
||||
@@ -5193,6 +5232,8 @@ export const FetchAgentTimelineResponseMessageSchema = z.object({
|
||||
// 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(),
|
||||
}),
|
||||
});
|
||||
@@ -5583,6 +5624,17 @@ 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({
|
||||
@@ -7828,6 +7880,7 @@ export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [
|
||||
WorkspaceClearAttentionResponseSchema,
|
||||
WorkspaceMarkUnreadResponseSchema,
|
||||
SendAgentMessageResponseMessageSchema,
|
||||
AgentProviderSwitchResponseMessageSchema,
|
||||
SetVoiceModeResponseMessageSchema,
|
||||
DaemonGetStatusResponseSchema,
|
||||
DaemonGetPairingOfferResponseSchema,
|
||||
@@ -8057,6 +8110,9 @@ 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>;
|
||||
@@ -8192,6 +8248,7 @@ 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>;
|
||||
@@ -8513,6 +8570,8 @@ export const WSHelloMessageSchema = z.object({
|
||||
[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(),
|
||||
})
|
||||
|
||||
@@ -19,6 +19,7 @@ export function isTimelineTurnTrigger(item: {
|
||||
}): boolean {
|
||||
return (
|
||||
item.type === "user_message" ||
|
||||
item.type === "provider_switch" ||
|
||||
(item.type === "tool_call" && (item.agentMessage !== undefined || item.name === "heartbeat"))
|
||||
);
|
||||
}
|
||||
|
||||
@@ -160,7 +160,7 @@
|
||||
"@playwright/test": "^1.56.1",
|
||||
"@types/express": "^4.17.20",
|
||||
"@types/markdown-it": "^14.2.0",
|
||||
"@types/node": "^20.9.0",
|
||||
"@types/node": "^22.16.0",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@types/uuid": "^9.0.7",
|
||||
"@types/ws": "^8.5.8",
|
||||
@@ -171,5 +171,8 @@
|
||||
},
|
||||
"overrides": {
|
||||
"lightningcss": "1.30.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.16.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
const MAX_FORK_CONTEXT_CHARS = 100_000;
|
||||
export 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;
|
||||
}
|
||||
|
||||
interface ActivityEntry {
|
||||
export interface ActivityEntry {
|
||||
text: string;
|
||||
}
|
||||
|
||||
@@ -138,7 +138,7 @@ function appendAgentMessageEntries(entries: ActivityEntry[], message: AgentMessa
|
||||
if (body) entries.push(activityEntry(body));
|
||||
}
|
||||
|
||||
function curateProjectedActivityEntries(
|
||||
export function curateProjectedActivityEntries(
|
||||
items: readonly AgentTimelineItem[],
|
||||
options?: ActivityCuratorOptions,
|
||||
): ActivityEntry[] {
|
||||
@@ -186,6 +186,11 @@ function curateProjectedActivityEntries(
|
||||
case "compaction":
|
||||
entries.push(activityEntry("[Compacted]"));
|
||||
break;
|
||||
case "provider_switch":
|
||||
entries.push(
|
||||
activityEntry(`[Switched provider: ${item.fromProvider} -> ${item.toProvider}]`),
|
||||
);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ export type AgentLoaderManager = Pick<
|
||||
AgentManager,
|
||||
"createAgentFromRecord" | "getAgent" | "getRegisteredProviderIds" | "resumeAgentFromPersistence"
|
||||
> &
|
||||
Partial<Pick<AgentManager, "waitForAgentClose">>;
|
||||
Partial<Pick<AgentManager, "waitForAgentClose" | "reconcilePendingProviderSwitch">>;
|
||||
|
||||
export interface EnsureAgentLoadedDeps {
|
||||
agentManager: AgentLoaderManager;
|
||||
@@ -55,6 +55,7 @@ export async function loadAgentHistory(
|
||||
): 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)) {
|
||||
@@ -128,6 +129,7 @@ export async function ensureAgentLoaded(
|
||||
}
|
||||
|
||||
const initPromise = (async () => {
|
||||
await deps.agentManager.reconcilePendingProviderSwitch?.(agentId);
|
||||
const record = await requireLoadableRecord(agentId, deps);
|
||||
const validProviders = deps.validProviders ?? deps.agentManager.getRegisteredProviderIds();
|
||||
const handle = toAgentPersistenceHandle(validProviders, record.persistence);
|
||||
|
||||
@@ -22,8 +22,8 @@ import {
|
||||
type ManagedAgent,
|
||||
} from "./agent-manager.js";
|
||||
import { AgentStorage, parseStoredAgentRecord } from "./agent-storage.js";
|
||||
import { AgentTimeline } from "./timeline/index.js";
|
||||
import { DeferredTimelineBackend } from "./timeline/testing.js";
|
||||
import { AgentTimeline, createStoredAgentTimeline } from "./timeline/index.js";
|
||||
import { DeferredTimelineBackend, openTestTimelineDatabase } from "./timeline/testing.js";
|
||||
import { AgentTurnStartCanceledError } from "./agent-sdk-types.js";
|
||||
import { ForegroundPromptStart } from "./agent-run-state.js";
|
||||
import {
|
||||
@@ -971,6 +971,52 @@ test("Reload agent keeps the history and its identity, and adds only what the pr
|
||||
}
|
||||
});
|
||||
|
||||
test("records the provider that wrote each row, live or from provider history", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-row-provider-"));
|
||||
class HistorySession extends TestAgentSession {
|
||||
override async *streamHistory(): AsyncGenerator<AgentStreamEvent> {
|
||||
yield {
|
||||
type: "timeline",
|
||||
provider: "codex",
|
||||
item: { type: "user_message", text: "continue", messageId: "provider-1" },
|
||||
};
|
||||
}
|
||||
}
|
||||
class HistoryClient extends TestAgentClient {
|
||||
override async createSession(config: AgentSessionConfig): Promise<AgentSession> {
|
||||
return new HistorySession(config);
|
||||
}
|
||||
|
||||
override async resumeSession(
|
||||
_handle: AgentPersistenceHandle,
|
||||
config?: Partial<AgentSessionConfig>,
|
||||
): Promise<AgentSession> {
|
||||
return new HistorySession({ provider: "codex", cwd: config?.cwd ?? workdir });
|
||||
}
|
||||
}
|
||||
const manager = new AgentManager({
|
||||
clients: { codex: new HistoryClient() },
|
||||
timeline: new AgentTimeline(new DeferredTimelineBackend()),
|
||||
logger,
|
||||
});
|
||||
let agentId: string | null = null;
|
||||
try {
|
||||
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
agentId = agent.id;
|
||||
expect(await reloadAgent(manager, agent.id)).toEqual({ kind: "appended" });
|
||||
await manager.appendTimelineItem(agent.id, { type: "assistant_message", text: "live" });
|
||||
await manager.flush();
|
||||
|
||||
const page = await manager.fetchTimeline(agent.id);
|
||||
expect(page.rows.map((row) => row.provider)).toEqual(["codex", "codex"]);
|
||||
} finally {
|
||||
if (agentId) await manager.closeAgent(agentId).catch(() => undefined);
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("Reload agent adds the provider children of new turns and leaves the children Paseo shows alone", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-timeline-reload-children-"));
|
||||
const providerHistory: AgentStreamEvent[] = [
|
||||
@@ -6898,6 +6944,207 @@ test("archiveSnapshot restoring an earlier archive time on a loaded agent keeps
|
||||
expect(events.at(-1)?.updatedAt.getTime()).toBeGreaterThanOrEqual(unarchivedAt);
|
||||
});
|
||||
|
||||
test("a turn ends even when the timeline fails to record how it ended", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-terminal-record-failure-"));
|
||||
class FailingTurnClient extends TestAgentClient {
|
||||
readonly session = new TestAgentSession({ provider: "codex", cwd: workdir });
|
||||
|
||||
override async createSession(): Promise<AgentSession> {
|
||||
return this.session;
|
||||
}
|
||||
}
|
||||
const client = new FailingTurnClient();
|
||||
const backend = new DeferredTimelineBackend();
|
||||
const manager = new AgentManager({
|
||||
clients: { codex: client },
|
||||
timeline: new AgentTimeline(backend),
|
||||
logger,
|
||||
});
|
||||
onTestFinished(async () => {
|
||||
await manager.closeAgent(agent.id);
|
||||
await manager.flush();
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
});
|
||||
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
const running = waitForAgentLifecycle(manager, agent.id, "running");
|
||||
client.session.pushEvent({ type: "turn_started", provider: "codex", turnId: "failed-turn" });
|
||||
await running;
|
||||
const failed = waitForAgentLifecycle(manager, agent.id, "error");
|
||||
// The turn's error message is the write that fails.
|
||||
backend.failNextAppend = true;
|
||||
client.session.pushEvent({
|
||||
type: "turn_failed",
|
||||
provider: "codex",
|
||||
turnId: "failed-turn",
|
||||
error: "Selected model is at capacity.",
|
||||
});
|
||||
await failed;
|
||||
expect(manager.getAgent(agent.id)?.lifecycle).toBe("error");
|
||||
// The failed turn no longer holds the agent: its next turn runs and records.
|
||||
const runningAgain = waitForAgentLifecycle(manager, agent.id, "running");
|
||||
client.session.pushEvent({ type: "turn_started", provider: "codex", turnId: "next-turn" });
|
||||
await runningAgain;
|
||||
});
|
||||
|
||||
test("a run's caller hears how its turn ended even when the timeline fails to record it", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-run-record-failure-"));
|
||||
const turnId = "failing-run";
|
||||
class HeldTurnSession extends TestAgentSession {
|
||||
override async startTurn(): Promise<{ turnId: string }> {
|
||||
setTimeout(() => this.pushEvent({ type: "turn_started", provider: "codex", turnId }), 0);
|
||||
return { turnId };
|
||||
}
|
||||
}
|
||||
const session = new HeldTurnSession({ provider: "codex", cwd: workdir });
|
||||
const client = new (class extends TestAgentClient {
|
||||
override async createSession(): Promise<AgentSession> {
|
||||
return session;
|
||||
}
|
||||
})();
|
||||
const backend = new DeferredTimelineBackend();
|
||||
const manager = new AgentManager({
|
||||
clients: { codex: client },
|
||||
timeline: new AgentTimeline(backend),
|
||||
logger,
|
||||
});
|
||||
onTestFinished(async () => {
|
||||
await manager.closeAgent(agent.id);
|
||||
await manager.flush();
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
});
|
||||
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
const running = waitForAgentLifecycle(manager, agent.id, "running");
|
||||
const run = manager.runAgent(agent.id, "hello");
|
||||
await running;
|
||||
await manager.flush();
|
||||
// The turn's error message is the write that fails.
|
||||
const failed = waitForAgentLifecycle(manager, agent.id, "error");
|
||||
backend.failNextAppend = true;
|
||||
session.pushEvent({
|
||||
type: "turn_failed",
|
||||
provider: "codex",
|
||||
turnId,
|
||||
error: "Selected model is at capacity.",
|
||||
});
|
||||
await expect(run).rejects.toThrow("Selected model is at capacity.");
|
||||
await failed;
|
||||
});
|
||||
|
||||
test("a turn the provider started ends even when the timeline fails to record its metrics", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-metrics-record-failure-"));
|
||||
const session = new TestAgentSession({ provider: "codex", cwd: workdir });
|
||||
const client = new (class extends TestAgentClient {
|
||||
override async createSession(): Promise<AgentSession> {
|
||||
return session;
|
||||
}
|
||||
})();
|
||||
const backend = new DeferredTimelineBackend();
|
||||
const manager = new AgentManager({
|
||||
clients: { codex: client },
|
||||
timeline: new AgentTimeline(backend),
|
||||
logger,
|
||||
});
|
||||
onTestFinished(async () => {
|
||||
await manager.closeAgent(agent.id);
|
||||
await manager.flush();
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
});
|
||||
const agent = await manager.createAgent(
|
||||
{ provider: "codex", cwd: workdir, model: "gpt-5.2-codex" },
|
||||
undefined,
|
||||
{ workspaceId: undefined },
|
||||
);
|
||||
const running = waitForAgentLifecycle(manager, agent.id, "running");
|
||||
session.pushEvent({ type: "turn_started", provider: "codex", turnId: "provider-turn" });
|
||||
await running;
|
||||
const idle = waitForAgentLifecycle(manager, agent.id, "idle");
|
||||
backend.failNextStampTurnMetrics = true;
|
||||
session.pushEvent({ type: "turn_completed", provider: "codex", turnId: "provider-turn" });
|
||||
await idle;
|
||||
expect(backend.failNextStampTurnMetrics).toBe(false);
|
||||
});
|
||||
|
||||
test("an internal agent's history stays out of the daemon database", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-internal-timeline-"));
|
||||
const database = openTestTimelineDatabase();
|
||||
const manager = new AgentManager({
|
||||
clients: { codex: new TestAgentClient() },
|
||||
timeline: createStoredAgentTimeline(database),
|
||||
logger,
|
||||
});
|
||||
onTestFinished(async () => {
|
||||
await manager.closeAgent(internal.id);
|
||||
await manager.closeAgent(visible.id);
|
||||
await manager.flush();
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
});
|
||||
const internal = await manager.createAgent(
|
||||
{ provider: "codex", cwd: workdir, internal: true },
|
||||
undefined,
|
||||
{ workspaceId: undefined },
|
||||
);
|
||||
const visible = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
const reply: AgentTimelineItem = { type: "assistant_message", text: "a commit message" };
|
||||
await manager.appendTimelineItem(internal.id, reply);
|
||||
await manager.appendTimelineItem(visible.id, reply);
|
||||
await manager.flush();
|
||||
|
||||
expect(await manager.getTimeline(internal.id)).toEqual([reply]);
|
||||
const storedAgents = database.read((sql) =>
|
||||
sql
|
||||
.all<{ agent_id: string }>("SELECT agent_id FROM timeline_scopes")
|
||||
.map((row) => row.agent_id),
|
||||
);
|
||||
expect(storedAgents).toEqual([visible.id]);
|
||||
});
|
||||
|
||||
test("reopening an agent the provider never gave a session keeps its saved history", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-reopen-without-session-"));
|
||||
const storagePath = join(workdir, "agents");
|
||||
const database = openTestTimelineDatabase();
|
||||
function startDaemon(): { manager: AgentManager; storage: AgentStorage } {
|
||||
const storage = new AgentStorage(storagePath, logger);
|
||||
const manager = new AgentManager({
|
||||
clients: { codex: new TestAgentClient() },
|
||||
registry: storage,
|
||||
timeline: createStoredAgentTimeline(database),
|
||||
logger,
|
||||
});
|
||||
return { manager, storage };
|
||||
}
|
||||
const first = startDaemon();
|
||||
const agent = await first.manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
const reply: AgentTimelineItem = { type: "assistant_message", text: "kept across restarts" };
|
||||
await first.manager.appendTimelineItem(agent.id, reply);
|
||||
await first.manager.closeAgent(agent.id);
|
||||
await first.manager.flush();
|
||||
const record = await first.storage.get(agent.id);
|
||||
if (!record) throw new Error("Created agent was not persisted");
|
||||
await first.storage.upsert({ ...record, persistence: null });
|
||||
|
||||
const second = startDaemon();
|
||||
onTestFinished(async () => {
|
||||
await second.manager.closeAgent(agent.id);
|
||||
await second.manager.flush();
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
});
|
||||
await ensureAgentLoaded(agent.id, {
|
||||
agentManager: second.manager,
|
||||
agentStorage: second.storage,
|
||||
logger,
|
||||
});
|
||||
|
||||
expect(await second.manager.getTimeline(agent.id)).toEqual([reply]);
|
||||
});
|
||||
|
||||
test("markAgentUnread restores error attention on a read errored agent", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-mark-unread-error-"));
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
@@ -7273,6 +7520,7 @@ test("getTimelineRows falls back to the in-memory timeline when no durable store
|
||||
sourceSeqRanges: [{ startSeq: 1, endSeq: 2 }],
|
||||
collapsed: ["assistant_merge"],
|
||||
timestamp: expect.any(String),
|
||||
provider: "codex",
|
||||
item: { type: "assistant_message", text: "row onerow two" },
|
||||
},
|
||||
]);
|
||||
@@ -16523,8 +16771,8 @@ class LaunchWrapRecordingClient extends TestAgentClient {
|
||||
readonly launchContexts: Array<AgentLaunchContext | undefined> = [];
|
||||
calls = { create: 0, resume: 0, import: 0 };
|
||||
|
||||
constructor(supportsLaunchWrap: boolean) {
|
||||
super("codex");
|
||||
constructor(supportsLaunchWrap: boolean, provider: AgentProvider = "codex") {
|
||||
super(provider);
|
||||
if (supportsLaunchWrap) this.supportsLaunchWrap = true;
|
||||
}
|
||||
|
||||
@@ -16626,13 +16874,16 @@ function createLaunchWrapManager(client: LaunchWrapRecordingClient) {
|
||||
|
||||
test("a wrapped open rejects on every path for a provider that does not apply wraps", async () => {
|
||||
const client = new LaunchWrapRecordingClient(false);
|
||||
const switchTarget = new LaunchWrapRecordingClient(false, "claude");
|
||||
const { manager, storage, workdir, failedLaunches, hook } = createLaunchWrapManager(client);
|
||||
manager.registerClient("claude", switchTarget);
|
||||
const created = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
const existing = client.sessions[0]!;
|
||||
hook.wrap = ["/opt/sandbox/bin/run", "--profile", "a b"];
|
||||
const calls = { ...client.calls };
|
||||
const targetCalls = { ...switchTarget.calls };
|
||||
const unsupported = { code: "launch_wrap_unsupported", provider: "codex" };
|
||||
|
||||
await expect(
|
||||
@@ -16650,12 +16901,20 @@ test("a wrapped open rejects on every path for a provider that does not apply wr
|
||||
}),
|
||||
).rejects.toMatchObject(unsupported);
|
||||
await expect(manager.reloadAgentSession(created.id)).rejects.toMatchObject(unsupported);
|
||||
await expect(
|
||||
manager.switchAgentProvider(created.id, {
|
||||
toProvider: "claude",
|
||||
prompt: "Switch to Claude",
|
||||
messageId: "msg-switch-wrap",
|
||||
}),
|
||||
).rejects.toMatchObject({ code: "launch_wrap_unsupported", provider: "claude" });
|
||||
|
||||
expect(client.calls).toEqual(calls);
|
||||
expect(switchTarget.calls).toEqual(targetCalls);
|
||||
expect(existing.closed).toBe(false);
|
||||
expect(manager.getAgent(created.id)?.session).toBe(existing);
|
||||
// Each refused open is discarded, so the running session keeps the tools it launched with.
|
||||
expect(failedLaunches).toHaveLength(4);
|
||||
expect(failedLaunches).toHaveLength(5);
|
||||
expect(failedLaunches.at(-1)).toBe(created.id);
|
||||
expect(manager.getPluginTools(created.id)).toEqual([]);
|
||||
await manager.flush();
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -35,6 +35,8 @@ export class AgentTurnChangedError extends Error {}
|
||||
|
||||
export interface StartAgentRunOptions {
|
||||
idleOnly?: boolean;
|
||||
/** Skip plugin-reload lifecycle checks when caller already holds the agent lifecycle lock. */
|
||||
skipPluginReload?: boolean;
|
||||
admit?: () => boolean;
|
||||
/** Called after selecting the run, before consuming its events. */
|
||||
onDispatch?: (disposition: PromptDispatchDisposition) => void;
|
||||
@@ -43,6 +45,8 @@ export interface StartAgentRunOptions {
|
||||
runOptions?: AgentRunOptions;
|
||||
/** Ask the provider to deny permissions blocking this steer. */
|
||||
clearPendingPermissions?: boolean;
|
||||
/** Exclusive switch reservation token handed off from `switchAgentProvider` into `streamAgent`. */
|
||||
switchReservationToken?: string;
|
||||
}
|
||||
|
||||
export type PromptDispatchDisposition = "out_of_band" | "steered" | "turn_started";
|
||||
@@ -112,6 +116,30 @@ async function drainAgentRunIterator(
|
||||
}
|
||||
}
|
||||
|
||||
async function startAgentRunWithPluginRecovery(
|
||||
agentManager: AgentRunController,
|
||||
agentId: string,
|
||||
prompt: AgentPromptInput,
|
||||
logger: Logger,
|
||||
options: StartAgentRunOptions | undefined,
|
||||
promptStart: ForegroundPromptStart,
|
||||
): Promise<PromptDispatchResult> {
|
||||
if (options?.skipPluginReload) {
|
||||
return await startAgentRunInner(agentManager, agentId, prompt, logger, options, promptStart);
|
||||
}
|
||||
try {
|
||||
await agentManager.reloadStalePluginSession(agentId);
|
||||
return await startAgentRunInner(agentManager, agentId, prompt, logger, options, promptStart);
|
||||
} catch (error) {
|
||||
if (!isStaleProviderSessionError(error)) throw error;
|
||||
logger.info({ agentId, err: error }, "Provider session went stale; reopening from persistence");
|
||||
// The live session belongs to a retired plugin runtime. Reload swaps in a
|
||||
// fresh session on the current runtime while preserving history and labels.
|
||||
await agentManager.reloadAgentSession(agentId);
|
||||
return await startAgentRunInner(agentManager, agentId, prompt, logger, options, promptStart);
|
||||
}
|
||||
}
|
||||
|
||||
export async function startAgentRun(
|
||||
agentManager: AgentRunController,
|
||||
agentId: string,
|
||||
@@ -145,22 +173,16 @@ export async function startAgentRun(
|
||||
options?.onDispatch?.("out_of_band");
|
||||
return { disposition: "out_of_band" };
|
||||
}
|
||||
const promptStart = new ForegroundPromptStart(agentId, admit);
|
||||
const promptStart = new ForegroundPromptStart(agentId, admit, options?.switchReservationToken);
|
||||
try {
|
||||
try {
|
||||
await agentManager.reloadStalePluginSession(agentId);
|
||||
return await startAgentRunInner(agentManager, agentId, prompt, logger, options, promptStart);
|
||||
} catch (error) {
|
||||
if (!isStaleProviderSessionError(error)) throw error;
|
||||
logger.info(
|
||||
{ agentId, err: error },
|
||||
"Provider session went stale; reopening from persistence",
|
||||
);
|
||||
// The live session belongs to a retired plugin runtime. Reload swaps in a
|
||||
// fresh session on the current runtime while preserving history and labels.
|
||||
await agentManager.reloadAgentSession(agentId);
|
||||
return await startAgentRunInner(agentManager, agentId, prompt, logger, options, promptStart);
|
||||
}
|
||||
return await startAgentRunWithPluginRecovery(
|
||||
agentManager,
|
||||
agentId,
|
||||
prompt,
|
||||
logger,
|
||||
options,
|
||||
promptStart,
|
||||
);
|
||||
} catch (error) {
|
||||
promptStart.end();
|
||||
throw error;
|
||||
@@ -179,7 +201,12 @@ async function startAgentRunInner(
|
||||
const steered = options?.idleOnly
|
||||
? null
|
||||
: await steerOrReplaceActiveRun(agentManager, agentId, prompt, options, promptStart);
|
||||
if (options?.idleOnly && agentManager.hasInFlightRun(agentId)) {
|
||||
if (
|
||||
options?.idleOnly &&
|
||||
agentManager.hasInFlightRun(agentId, {
|
||||
ignoreSwitchReservationToken: options.switchReservationToken,
|
||||
})
|
||||
) {
|
||||
throw new AgentTurnBusyError(`Agent ${agentId} is running`);
|
||||
}
|
||||
if (steered?.disposition === "steered") {
|
||||
|
||||
@@ -359,6 +359,7 @@ export class ForegroundPromptStart {
|
||||
constructor(
|
||||
private readonly agentId: string,
|
||||
readonly admit?: () => boolean,
|
||||
readonly switchReservationToken?: string,
|
||||
) {
|
||||
this.started = new Promise<void>((resolve, reject) => {
|
||||
this.resolveStarted = resolve;
|
||||
|
||||
@@ -7,6 +7,8 @@ import type {
|
||||
AgentTaskItem,
|
||||
JsonValue,
|
||||
ProviderOptions,
|
||||
ProviderSwitchContextSummary,
|
||||
ProviderSwitchTimelineItem,
|
||||
ToolPolicy,
|
||||
} from "@getpaseo/protocol/agent-types";
|
||||
import type { AgentMessage } from "@getpaseo/protocol/agent-message";
|
||||
@@ -26,6 +28,8 @@ export type {
|
||||
AgentOptionToggleControl,
|
||||
AgentProviderNotice,
|
||||
AgentTaskItem,
|
||||
ProviderSwitchContextSummary,
|
||||
ProviderSwitchTimelineItem,
|
||||
};
|
||||
|
||||
export type AgentProvider = string;
|
||||
@@ -421,7 +425,8 @@ export type AgentTimelineItem =
|
||||
message: string;
|
||||
}
|
||||
| CompactionTimelineItem
|
||||
| PluginTimelineItem;
|
||||
| PluginTimelineItem
|
||||
| ProviderSwitchTimelineItem;
|
||||
|
||||
export type AgentStreamEvent =
|
||||
| { type: "thread_started"; sessionId: string; provider: AgentProvider }
|
||||
|
||||
@@ -41,15 +41,14 @@ const SERIALIZABLE_CONFIG_SCHEMA = z
|
||||
.nullable()
|
||||
.optional();
|
||||
|
||||
const PERSISTENCE_HANDLE_SCHEMA = z
|
||||
.object({
|
||||
provider: z.string(),
|
||||
sessionId: z.string(),
|
||||
nativeHandle: z.any().optional(),
|
||||
metadata: z.record(z.string(), z.any()).optional(),
|
||||
})
|
||||
.nullable()
|
||||
.optional();
|
||||
const PERSISTENCE_HANDLE_OBJECT_SCHEMA = z.object({
|
||||
provider: z.string(),
|
||||
sessionId: z.string(),
|
||||
nativeHandle: z.any().optional(),
|
||||
metadata: z.record(z.string(), z.any()).optional(),
|
||||
});
|
||||
|
||||
const PERSISTENCE_HANDLE_SCHEMA = PERSISTENCE_HANDLE_OBJECT_SCHEMA.nullable().optional();
|
||||
|
||||
const RAW_STORED_AGENT_SCHEMA = z.object({
|
||||
id: z.string(),
|
||||
@@ -82,6 +81,7 @@ const RAW_STORED_AGENT_SCHEMA = z.object({
|
||||
// COMPAT(featureValues): added in v0.15.0, remove after 2027-05-01. Read-only; becomes controls.
|
||||
features: z.array(AgentFeatureSchema).optional(),
|
||||
persistence: PERSISTENCE_HANDLE_SCHEMA,
|
||||
previousSessions: z.array(PERSISTENCE_HANDLE_OBJECT_SCHEMA).optional(),
|
||||
sessionMetrics: z.array(AgentMetricSchema).optional(),
|
||||
lastError: z.string().nullable().optional(),
|
||||
requiresAttention: z.boolean().optional(),
|
||||
@@ -128,6 +128,75 @@ export function parseStoredAgentRecord(value: unknown): StoredAgentRecord {
|
||||
return STORED_AGENT_SCHEMA.parse(value);
|
||||
}
|
||||
|
||||
type StoredPersistenceHandle = z.infer<typeof PERSISTENCE_HANDLE_OBJECT_SCHEMA>;
|
||||
|
||||
/** Appends a prior persistence handle to `previousSessions`, deduplicating by provider + id. */
|
||||
export function appendUniquePreviousSession(
|
||||
previousSessions: readonly StoredPersistenceHandle[] | undefined,
|
||||
handle: StoredPersistenceHandle | null | undefined,
|
||||
): StoredPersistenceHandle[] | undefined {
|
||||
const existing = previousSessions ? [...previousSessions] : [];
|
||||
if (!handle) return existing.length > 0 ? existing : undefined;
|
||||
const alreadyPresent = existing.some(
|
||||
(entry) =>
|
||||
entry.provider === handle.provider &&
|
||||
entry.sessionId === handle.sessionId &&
|
||||
entry.nativeHandle === handle.nativeHandle,
|
||||
);
|
||||
if (!alreadyPresent) existing.push(handle);
|
||||
return existing;
|
||||
}
|
||||
|
||||
function resolveSnapshotFields(
|
||||
agent: ManagedAgent,
|
||||
existing: StoredAgentRecord | null | undefined,
|
||||
overrides: {
|
||||
hasTitleOverride: boolean;
|
||||
hasInternalOverride: boolean;
|
||||
options?: { title?: string | null; internal?: boolean };
|
||||
},
|
||||
) {
|
||||
const title = overrides.hasTitleOverride
|
||||
? (overrides.options?.title ?? null)
|
||||
: (existing?.title ?? null);
|
||||
const internal = overrides.hasInternalOverride
|
||||
? overrides.options?.internal
|
||||
: (agent.internal ?? existing?.internal);
|
||||
return { title, createdAt: existing?.createdAt, internal };
|
||||
}
|
||||
|
||||
function mergeStoredAgentSnapshot(
|
||||
agent: ManagedAgent,
|
||||
existing: StoredAgentRecord | null | undefined,
|
||||
overrides: {
|
||||
hasTitleOverride: boolean;
|
||||
hasInternalOverride: boolean;
|
||||
hasPreviousSessionsOverride: boolean;
|
||||
options?: {
|
||||
title?: string | null;
|
||||
internal?: boolean;
|
||||
previousSessions?: StoredPersistenceHandle[];
|
||||
};
|
||||
},
|
||||
): StoredAgentRecord {
|
||||
const record = toStoredAgentRecord(agent, resolveSnapshotFields(agent, existing, overrides));
|
||||
if (existing && existing.archivedAt !== undefined) {
|
||||
record.archivedAt = existing.archivedAt;
|
||||
}
|
||||
if (existing?.background) {
|
||||
record.background = true;
|
||||
}
|
||||
const previousSessions = overrides.hasPreviousSessionsOverride
|
||||
? overrides.options?.previousSessions
|
||||
: existing?.previousSessions;
|
||||
if (previousSessions && previousSessions.length > 0) {
|
||||
record.previousSessions = previousSessions;
|
||||
}
|
||||
record.resumeOnStartup =
|
||||
Boolean(existing?.resumeOnStartup) && agent.lifecycle !== "idle" && agent.lifecycle !== "error";
|
||||
return record;
|
||||
}
|
||||
|
||||
export class AgentStorage {
|
||||
private cache: Map<string, StoredAgentRecord> = new Map();
|
||||
private pathById: Map<string, string> = new Map();
|
||||
@@ -276,13 +345,17 @@ export class AgentStorage {
|
||||
async listByProviderSession(
|
||||
provider: string,
|
||||
providerHandleId: string,
|
||||
options?: { includePreviousSessions?: boolean },
|
||||
): Promise<StoredAgentRecord[]> {
|
||||
await this.load();
|
||||
const includePrevious = options?.includePreviousSessions === true;
|
||||
const matchesHandle = (handle: StoredPersistenceHandle | null | undefined) =>
|
||||
handle?.provider === provider &&
|
||||
(handle.sessionId === providerHandleId || handle.nativeHandle === providerHandleId);
|
||||
return Array.from(this.cache.values()).filter(
|
||||
(record) =>
|
||||
record.persistence?.provider === provider &&
|
||||
(record.persistence.sessionId === providerHandleId ||
|
||||
record.persistence.nativeHandle === providerHandleId),
|
||||
matchesHandle(record.persistence) ||
|
||||
(includePrevious && (record.previousSessions?.some(matchesHandle) ?? false)),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -364,6 +437,11 @@ export class AgentStorage {
|
||||
this.deleting.add(agentId);
|
||||
}
|
||||
|
||||
/** Ends a delete that did not happen; the agent's record takes writes again. */
|
||||
abandonDelete(agentId: string): void {
|
||||
this.deleting.delete(agentId);
|
||||
}
|
||||
|
||||
async remove(agentId: string): Promise<void> {
|
||||
await this.load();
|
||||
this.beginDelete(agentId);
|
||||
@@ -401,32 +479,27 @@ export class AgentStorage {
|
||||
|
||||
async applySnapshot(
|
||||
agent: ManagedAgent,
|
||||
options?: { title?: string | null; internal?: boolean },
|
||||
options?: {
|
||||
title?: string | null;
|
||||
internal?: boolean;
|
||||
previousSessions?: StoredPersistenceHandle[];
|
||||
},
|
||||
): Promise<void> {
|
||||
await this.load();
|
||||
const hasTitleOverride =
|
||||
options !== undefined && Object.prototype.hasOwnProperty.call(options, "title");
|
||||
const hasInternalOverride =
|
||||
options !== undefined && Object.prototype.hasOwnProperty.call(options, "internal");
|
||||
await this.queueRecordMutation(agent.id, (existing) => {
|
||||
const record = toStoredAgentRecord(agent, {
|
||||
title: hasTitleOverride ? (options?.title ?? null) : (existing?.title ?? null),
|
||||
createdAt: existing?.createdAt,
|
||||
internal: hasInternalOverride ? options?.internal : (agent.internal ?? existing?.internal),
|
||||
});
|
||||
|
||||
// Preserve soft-delete/archive status across snapshot flushes. The
|
||||
// projection runs inside the per-agent write queue so it cannot commit a
|
||||
// stale pre-archive record after the archive mutation.
|
||||
if (existing && existing.archivedAt !== undefined) {
|
||||
record.archivedAt = existing.archivedAt;
|
||||
}
|
||||
// Background is fixed at creation; a runtime opened without it cannot clear it.
|
||||
if (existing?.background) record.background = true;
|
||||
record.resumeOnStartup =
|
||||
existing?.resumeOnStartup && agent.lifecycle !== "idle" && agent.lifecycle !== "error";
|
||||
return record;
|
||||
});
|
||||
const hasPreviousSessionsOverride =
|
||||
options !== undefined && Object.prototype.hasOwnProperty.call(options, "previousSessions");
|
||||
await this.queueRecordMutation(agent.id, (existing) =>
|
||||
mergeStoredAgentSnapshot(agent, existing, {
|
||||
hasTitleOverride,
|
||||
hasInternalOverride,
|
||||
hasPreviousSessionsOverride,
|
||||
options,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async setTitle(agentId: string, title: string): Promise<void> {
|
||||
|
||||
@@ -1,12 +1,21 @@
|
||||
import type { ProjectedTimelineRow, TimelineRetirement } from "./timeline-projection.js";
|
||||
import type { AgentMetric, AgentTimelineItem } from "./agent-sdk-types.js";
|
||||
import type { AgentMetric, AgentProvider, AgentTimelineItem } from "./agent-sdk-types.js";
|
||||
|
||||
export interface AgentTimelineRow {
|
||||
seq: number;
|
||||
timestamp: string;
|
||||
item: AgentTimelineItem;
|
||||
/** The provider that wrote the row; an agent's history can span providers. */
|
||||
readonly provider?: AgentProvider;
|
||||
readonly turnId?: string;
|
||||
readonly providerMessageId?: string;
|
||||
/**
|
||||
* Daemon-internal provider-facing prompt text (e.g. including rendered attachments/handoff).
|
||||
* Used for reload reconciliation; never emitted over the wire.
|
||||
*/
|
||||
readonly providerPromptText?: string;
|
||||
/** True when a submitted prompt was rejected before the provider accepted any turn; never emitted over the wire. */
|
||||
readonly rejected?: boolean;
|
||||
/** Metrics of the turn this row carries the footer for. */
|
||||
readonly turnMetrics?: AgentMetric[];
|
||||
}
|
||||
@@ -57,4 +66,6 @@ export interface AgentTimelineFetchResult {
|
||||
retirements: TimelineRetirement[];
|
||||
/** Retirements of this history so far. */
|
||||
retirementCount: number;
|
||||
/** Seq of the latest active provider_switch marker, or 0 if never switched. */
|
||||
activeSegmentStartSeq: number;
|
||||
}
|
||||
|
||||
@@ -277,6 +277,47 @@ test("listImportableProviderSessions filters, sorts, limits, and projects import
|
||||
});
|
||||
});
|
||||
|
||||
test("listImportableProviderSessions excludes sessions recorded in active previousSessions", async () => {
|
||||
const cwd = "/tmp/project";
|
||||
const previousClaude = makeImportableSession({
|
||||
provider: "claude",
|
||||
sessionId: "claude-before-switch",
|
||||
cwd,
|
||||
lastActivityAt: "2026-04-30T12:02:00.000Z",
|
||||
});
|
||||
const freshClaude = makeImportableSession({
|
||||
provider: "claude",
|
||||
sessionId: "claude-unimported",
|
||||
cwd,
|
||||
lastActivityAt: "2026-04-30T12:01:00.000Z",
|
||||
});
|
||||
const listImportableSessions = vi.fn(async (options?: { limit?: number }) =>
|
||||
makeImportableSessionsResult([previousClaude, freshClaude].slice(0, options?.limit)),
|
||||
);
|
||||
|
||||
const result = await listImportableProviderSessions({
|
||||
request: makeRequest({ cwd, providers: ["claude"], limit: 5 }),
|
||||
agentManager: {
|
||||
listAgents: () => [],
|
||||
listImportableSessions,
|
||||
},
|
||||
agentStorage: {
|
||||
listAll: async () => [
|
||||
{
|
||||
id: "agent-switched",
|
||||
provider: "codex",
|
||||
persistence: { provider: "codex", sessionId: "codex-after-switch" },
|
||||
previousSessions: [{ provider: "claude", sessionId: "claude-before-switch" }],
|
||||
} as StoredAgentRecord,
|
||||
],
|
||||
},
|
||||
providerSnapshotManager: { getProviderLabel: () => "Claude" },
|
||||
});
|
||||
|
||||
expect(result.filteredAlreadyImportedCount).toBe(1);
|
||||
expect(result.entries.map((entry) => entry.providerHandleId)).toEqual(["claude-unimported"]);
|
||||
});
|
||||
|
||||
test("listImportableProviderSessions looks past already-imported rows to fill the requested limit", async () => {
|
||||
const cwd = "/tmp/project";
|
||||
const imported = makeImportableSession({
|
||||
|
||||
@@ -206,15 +206,17 @@ async function importProviderSessionNow(
|
||||
): Promise<ImportedProviderSession> {
|
||||
const { provider, providerHandleId, labels } = input.request;
|
||||
|
||||
const matchingRecords = await input.agentStorage.listByProviderSession(
|
||||
const currentRecords = await input.agentStorage.listByProviderSession(provider, providerHandleId);
|
||||
const allMatchingRecords = await input.agentStorage.listByProviderSession(
|
||||
provider,
|
||||
providerHandleId,
|
||||
{ includePreviousSessions: true },
|
||||
);
|
||||
const activeRecord = matchingRecords.find((record) => !record.archivedAt);
|
||||
const activeRecord = allMatchingRecords.find((record) => !record.archivedAt);
|
||||
if (activeRecord) {
|
||||
throw new Error(`Provider session is already imported: ${providerHandleId}`);
|
||||
}
|
||||
const archivedRecord = matchingRecords.find((record) => record.archivedAt);
|
||||
const archivedRecord = currentRecords.find((record) => record.archivedAt);
|
||||
if (archivedRecord?.persistence && archivedRecord.archivedAt) {
|
||||
if (!createRealpathAwarePathMatcher(cwd)(archivedRecord.cwd)) {
|
||||
throw new Error(`Provider session cwd does not match import cwd: ${providerHandleId}`);
|
||||
@@ -292,6 +294,7 @@ async function resolveProviderSessionImportMutationKey(
|
||||
await input.agentStorage.listByProviderSession(
|
||||
input.request.provider,
|
||||
input.request.providerHandleId,
|
||||
{ includePreviousSessions: true },
|
||||
)
|
||||
).at(0);
|
||||
return matchingRecord
|
||||
@@ -372,6 +375,9 @@ async function collectImportedProviderSessions(
|
||||
continue;
|
||||
}
|
||||
collect(record.provider, record.persistence);
|
||||
for (const previous of record.previousSessions ?? []) {
|
||||
collect(previous.provider, previous);
|
||||
}
|
||||
}
|
||||
|
||||
return { handles, count: sessions.size };
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
type ManagedAgent,
|
||||
} from "./agent-manager.js";
|
||||
import type { StoredAgentRecord } from "./agent-storage.js";
|
||||
import type { AgentProviderNotice } from "./agent-sdk-types.js";
|
||||
import type { AgentProvider, AgentProviderNotice } from "./agent-sdk-types.js";
|
||||
|
||||
export type LifecycleAgentSnapshot = Pick<ManagedAgent, "id" | "cwd" | "lifecycle" | "internal">;
|
||||
|
||||
@@ -25,7 +25,11 @@ export interface LifecycleAgentManager {
|
||||
previousParentAgentId: string | null;
|
||||
}>;
|
||||
notifyAgentState(agentId: string): void;
|
||||
setAgentMode(agentId: string, modeId: string): Promise<AgentProviderNotice | null>;
|
||||
setAgentMode(
|
||||
agentId: string,
|
||||
modeId: string,
|
||||
options?: { expectedProvider?: AgentProvider },
|
||||
): Promise<AgentProviderNotice | null>;
|
||||
updateAgentMetadata(
|
||||
agentId: string,
|
||||
updates: {
|
||||
@@ -212,9 +216,14 @@ export async function setAgentModeCommand(
|
||||
input: {
|
||||
agentId: string;
|
||||
modeId: string;
|
||||
expectedProvider?: AgentProvider;
|
||||
},
|
||||
): Promise<{ modeId: string; notice: AgentProviderNotice | null }> {
|
||||
const notice = await dependencies.agentManager.setAgentMode(input.agentId, input.modeId);
|
||||
const notice = await dependencies.agentManager.setAgentMode(
|
||||
input.agentId,
|
||||
input.modeId,
|
||||
input.expectedProvider ? { expectedProvider: input.expectedProvider } : undefined,
|
||||
);
|
||||
return { modeId: input.modeId, notice };
|
||||
}
|
||||
|
||||
|
||||
@@ -95,7 +95,7 @@ export class ProviderSubagentStore {
|
||||
|
||||
if (event.type === "timeline") {
|
||||
const commits = await this.timeline.recordChildEntries(scope, [
|
||||
{ item: event.item, timestamp: event.timestamp },
|
||||
{ item: event.item, provider, timestamp: event.timestamp },
|
||||
]);
|
||||
if (!commits) return null;
|
||||
const [{ row, epoch }] = commits;
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { ProjectedTimelineRow } from "../timeline-projection.js";
|
||||
import {
|
||||
buildProviderSwitchHandoff,
|
||||
prependHandoffAttachment,
|
||||
renderProviderPromptText,
|
||||
} from "./index.js";
|
||||
|
||||
const TS = "2026-11-25T10:00:00.000Z";
|
||||
|
||||
function row(
|
||||
seq: number,
|
||||
item: ProjectedTimelineRow["item"],
|
||||
provider = "claude",
|
||||
): ProjectedTimelineRow {
|
||||
return {
|
||||
seq,
|
||||
seqStart: seq,
|
||||
seqEnd: seq,
|
||||
sourceSeqRanges: [[seq, seq]],
|
||||
timestamp: TS,
|
||||
provider,
|
||||
item,
|
||||
collapsed: [],
|
||||
};
|
||||
}
|
||||
|
||||
describe("buildProviderSwitchHandoff", () => {
|
||||
it("returns a null attachment and zero summary when there is no prior active history", () => {
|
||||
const handoff = buildProviderSwitchHandoff({
|
||||
rows: [],
|
||||
hasOlder: false,
|
||||
fromProvider: "claude",
|
||||
toProvider: "codex",
|
||||
agentTitle: "Refactor auth",
|
||||
cwd: "/repo",
|
||||
});
|
||||
|
||||
expect(handoff.attachment).toBeNull();
|
||||
expect(handoff.summary).toEqual({
|
||||
includedItems: 0,
|
||||
truncated: false,
|
||||
charCount: 0,
|
||||
budgetChars: 100_000,
|
||||
});
|
||||
});
|
||||
|
||||
it("curates user messages, assistant messages, tool calls, and prior provider switches while omitting reasoning and errors", () => {
|
||||
const handoff = buildProviderSwitchHandoff({
|
||||
rows: [
|
||||
row(1, { type: "user_message", text: "Fix the bug", messageId: "m1" }),
|
||||
row(2, { type: "reasoning", text: "Internal chain of thought" }),
|
||||
row(3, {
|
||||
type: "tool_call",
|
||||
callId: "c1",
|
||||
name: "read_file",
|
||||
status: "completed",
|
||||
error: null,
|
||||
detail: { type: "read", filePath: "src/app.ts" },
|
||||
}),
|
||||
row(4, { type: "assistant_message", text: "I found the issue in src/app.ts." }),
|
||||
row(5, { type: "error", message: "Transient warning" }),
|
||||
row(6, {
|
||||
type: "provider_switch",
|
||||
fromProvider: "claude",
|
||||
toProvider: "opencode",
|
||||
fromModel: "sonnet",
|
||||
toModel: "gemini",
|
||||
fromSessionId: "s1",
|
||||
toSessionId: "s2",
|
||||
context: { includedItems: 2, truncated: false, charCount: 100, budgetChars: 100_000 },
|
||||
}),
|
||||
],
|
||||
hasOlder: false,
|
||||
fromProvider: "opencode",
|
||||
toProvider: "codex",
|
||||
agentTitle: "Bug fix",
|
||||
cwd: "/repo",
|
||||
});
|
||||
|
||||
expect(handoff.attachment).not.toBeNull();
|
||||
expect(handoff.attachment?.type).toBe("text");
|
||||
expect(handoff.attachment?.mimeType).toBe("text/plain");
|
||||
expect(handoff.attachment?.contextKind).toBe("chat_history");
|
||||
expect(handoff.attachment?.text).toContain("<chat-history-summary>");
|
||||
expect(handoff.attachment?.text).toContain("[User] Fix the bug");
|
||||
expect(handoff.attachment?.text).toContain("[Assistant] I found the issue in src/app.ts.");
|
||||
expect(handoff.attachment?.text).toContain("[Switched provider: claude -> opencode]");
|
||||
expect(handoff.attachment?.text).not.toContain("Internal chain of thought");
|
||||
expect(handoff.attachment?.text).not.toContain("Transient warning");
|
||||
expect(handoff.summary.includedItems).toBe(4);
|
||||
expect(handoff.summary.truncated).toBe(false);
|
||||
expect(handoff.summary.omittedReasons).toBeUndefined();
|
||||
expect(handoff.summary.charCount).toBe(handoff.attachment?.text.length);
|
||||
});
|
||||
|
||||
it("marks tail_window_limit when hasOlder is true and char_budget when history exceeds budgetChars", () => {
|
||||
const bigReply = "x".repeat(500);
|
||||
const handoff = buildProviderSwitchHandoff({
|
||||
rows: [
|
||||
row(10, { type: "user_message", text: "First prompt in window", messageId: "m1" }),
|
||||
row(11, { type: "assistant_message", text: bigReply }),
|
||||
row(12, { type: "user_message", text: "Most recent prompt", messageId: "m2" }),
|
||||
],
|
||||
hasOlder: true,
|
||||
fromProvider: "claude",
|
||||
toProvider: "codex",
|
||||
budgetChars: 350,
|
||||
});
|
||||
|
||||
expect(handoff.attachment).not.toBeNull();
|
||||
expect(handoff.attachment!.text.length).toBeLessThanOrEqual(350);
|
||||
expect(handoff.attachment!.text).toContain("[Earlier chat history omitted]");
|
||||
expect(handoff.attachment!.text).toContain("[User] Most recent prompt");
|
||||
expect(handoff.summary.truncated).toBe(true);
|
||||
expect(handoff.summary.omittedReasons).toEqual(["tail_window_limit", "char_budget"]);
|
||||
expect(handoff.summary.includedItems).toBe(1);
|
||||
});
|
||||
|
||||
it("caps included items to HANDOFF_TAIL_LIMIT when a single turn exceeds 80 rows", () => {
|
||||
const oversizedRows = Array.from({ length: 85 }, (_, index) =>
|
||||
row(index + 1, {
|
||||
type: "assistant_message",
|
||||
text: `Step ${index + 1}`,
|
||||
}),
|
||||
);
|
||||
const handoff = buildProviderSwitchHandoff({
|
||||
rows: oversizedRows,
|
||||
hasOlder: false,
|
||||
fromProvider: "claude",
|
||||
toProvider: "codex",
|
||||
});
|
||||
|
||||
expect(handoff.attachment).not.toBeNull();
|
||||
expect(handoff.summary.includedItems).toBe(80);
|
||||
expect(handoff.summary.truncated).toBe(true);
|
||||
expect(handoff.summary.omittedReasons).toEqual(["tail_window_limit"]);
|
||||
expect(handoff.attachment!.text).toContain("[Earlier chat history omitted]");
|
||||
expect(handoff.attachment!.text).toContain("Step 85");
|
||||
expect(handoff.attachment!.text).not.toContain("Step 1\n");
|
||||
});
|
||||
|
||||
it("prepends handoff attachment and renders providerPromptText including attachments", () => {
|
||||
const attachment = {
|
||||
type: "text" as const,
|
||||
mimeType: "text/plain",
|
||||
contextKind: "chat_history" as const,
|
||||
title: "Chat history",
|
||||
text: "<chat-history-summary>\n[User] hi\n</chat-history-summary>",
|
||||
};
|
||||
const combined = prependHandoffAttachment("Continue here", attachment);
|
||||
expect(Array.isArray(combined)).toBe(true);
|
||||
expect(renderProviderPromptText(combined)).toContain("<chat-history-summary>");
|
||||
expect(renderProviderPromptText(combined)).toContain("Continue here");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,207 @@
|
||||
import type { AgentAttachment } from "@getpaseo/protocol/messages";
|
||||
import type {
|
||||
AgentPromptInput,
|
||||
AgentProvider,
|
||||
AgentTimelineItem,
|
||||
ProviderSwitchContextSummary,
|
||||
} from "../agent-sdk-types.js";
|
||||
import type { ProjectedTimelineRow } from "../timeline-projection.js";
|
||||
import {
|
||||
curateProjectedActivityEntries,
|
||||
MAX_FORK_CONTEXT_CHARS,
|
||||
type ActivityEntry,
|
||||
} from "../activity-curator.js";
|
||||
|
||||
export const HANDOFF_TAIL_LIMIT = 80;
|
||||
export const MAX_HANDOFF_CONTEXT_CHARS = MAX_FORK_CONTEXT_CHARS;
|
||||
const MAX_HANDOFF_METADATA_CHARS = 1_000;
|
||||
const HANDOFF_OMITTED_MARKER = "[Earlier chat history omitted]\n";
|
||||
const HANDOFF_CONTEXT_KINDS: readonly AgentTimelineItem["type"][] = [
|
||||
"user_message",
|
||||
"assistant_message",
|
||||
"tool_call",
|
||||
"provider_switch",
|
||||
];
|
||||
|
||||
type TextAgentAttachment = Extract<AgentAttachment, { type: "text" }>;
|
||||
|
||||
export interface ProviderSwitchHandoffResult {
|
||||
attachment: TextAgentAttachment | null;
|
||||
summary: ProviderSwitchContextSummary;
|
||||
}
|
||||
|
||||
function trimMetadata(value: string | null | undefined): string | null {
|
||||
const trimmed = value?.trim();
|
||||
return trimmed ? trimmed.slice(0, MAX_HANDOFF_METADATA_CHARS) : null;
|
||||
}
|
||||
|
||||
function wrapHandoffContextText(input: {
|
||||
body: string;
|
||||
fromProvider: AgentProvider;
|
||||
toProvider: AgentProvider;
|
||||
agentTitle?: string | null;
|
||||
cwd?: string | null;
|
||||
}): string {
|
||||
const header = [
|
||||
`Chat history from this Paseo conversation before switching from ${input.fromProvider} to ${input.toProvider}.`,
|
||||
];
|
||||
const agentTitle = trimMetadata(input.agentTitle);
|
||||
const cwd = trimMetadata(input.cwd);
|
||||
if (agentTitle) header.push(`Conversation: ${agentTitle}`);
|
||||
if (cwd) header.push(`Directory: ${cwd}`);
|
||||
return `<chat-history-summary>\n${header.join("\n")}\n\n${input.body}\n</chat-history-summary>`;
|
||||
}
|
||||
|
||||
function fitHandoffEntries(
|
||||
entries: readonly ActivityEntry[],
|
||||
budget: number,
|
||||
alreadyHasOlder: boolean,
|
||||
): { body: string; includedItems: number; charBudgetTruncated: boolean } {
|
||||
const prefix = alreadyHasOlder ? HANDOFF_OMITTED_MARKER : "";
|
||||
const fullJoined = entries.map((entry) => entry.text).join("\n");
|
||||
if (prefix.length + fullJoined.length <= budget) {
|
||||
return {
|
||||
body: prefix + fullJoined,
|
||||
includedItems: entries.length,
|
||||
charBudgetTruncated: false,
|
||||
};
|
||||
}
|
||||
|
||||
const selected: string[] = [];
|
||||
let remaining = Math.max(0, budget - HANDOFF_OMITTED_MARKER.length);
|
||||
for (let index = entries.length - 1; index >= 0; index--) {
|
||||
const text = entries[index]!.text;
|
||||
const size = text.length + (selected.length > 0 ? 1 : 0);
|
||||
if (size > remaining) {
|
||||
if (selected.length === 0 && remaining > 0) {
|
||||
const marker = "\n[Message truncated]\n";
|
||||
if (remaining > marker.length + 2) {
|
||||
const available = remaining - marker.length;
|
||||
const head = Math.ceil(available / 2);
|
||||
selected.push(text.slice(0, head) + marker + text.slice(-(available - head)));
|
||||
} else {
|
||||
selected.push(text.slice(0, remaining));
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
selected.push(text);
|
||||
remaining -= size;
|
||||
}
|
||||
|
||||
return {
|
||||
body: HANDOFF_OMITTED_MARKER + selected.toReversed().join("\n"),
|
||||
includedItems: selected.length,
|
||||
charBudgetTruncated: true,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildProviderSwitchHandoff(input: {
|
||||
rows: readonly ProjectedTimelineRow[];
|
||||
hasOlder: boolean;
|
||||
fromProvider: AgentProvider;
|
||||
toProvider: AgentProvider;
|
||||
agentTitle?: string | null;
|
||||
cwd?: string | null;
|
||||
budgetChars?: number;
|
||||
}): ProviderSwitchHandoffResult {
|
||||
const budgetChars = input.budgetChars ?? MAX_HANDOFF_CONTEXT_CHARS;
|
||||
const tailWindowExceeded = input.rows.length > HANDOFF_TAIL_LIMIT;
|
||||
const boundedRows = tailWindowExceeded ? input.rows.slice(-HANDOFF_TAIL_LIMIT) : input.rows;
|
||||
const hasOlder = input.hasOlder || tailWindowExceeded;
|
||||
const entries = curateProjectedActivityEntries(
|
||||
boundedRows.map((row) => row.item),
|
||||
{
|
||||
maxItems: 0,
|
||||
labelAssistantMessages: true,
|
||||
includeKinds: HANDOFF_CONTEXT_KINDS,
|
||||
includeExternalToolInput: false,
|
||||
},
|
||||
);
|
||||
|
||||
if (entries.length === 0 && !hasOlder) {
|
||||
return {
|
||||
attachment: null,
|
||||
summary: {
|
||||
includedItems: 0,
|
||||
truncated: false,
|
||||
charCount: 0,
|
||||
budgetChars,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const wrapperOverhead = wrapHandoffContextText({
|
||||
body: "",
|
||||
fromProvider: input.fromProvider,
|
||||
toProvider: input.toProvider,
|
||||
agentTitle: input.agentTitle,
|
||||
cwd: input.cwd,
|
||||
}).length;
|
||||
const bodyBudget = Math.max(0, budgetChars - wrapperOverhead);
|
||||
|
||||
const fitted =
|
||||
entries.length > 0
|
||||
? fitHandoffEntries(entries, bodyBudget, hasOlder)
|
||||
: { body: HANDOFF_OMITTED_MARKER.trimEnd(), includedItems: 0, charBudgetTruncated: false };
|
||||
|
||||
const omittedReasons: string[] = [];
|
||||
if (hasOlder) omittedReasons.push("tail_window_limit");
|
||||
if (fitted.charBudgetTruncated) omittedReasons.push("char_budget");
|
||||
|
||||
const text = wrapHandoffContextText({
|
||||
body: fitted.body,
|
||||
fromProvider: input.fromProvider,
|
||||
toProvider: input.toProvider,
|
||||
agentTitle: input.agentTitle,
|
||||
cwd: input.cwd,
|
||||
});
|
||||
|
||||
return {
|
||||
attachment: {
|
||||
type: "text",
|
||||
mimeType: "text/plain",
|
||||
contextKind: "chat_history",
|
||||
title: "Chat history",
|
||||
text,
|
||||
},
|
||||
summary: {
|
||||
includedItems: fitted.includedItems,
|
||||
truncated: omittedReasons.length > 0,
|
||||
charCount: text.length,
|
||||
budgetChars,
|
||||
...(omittedReasons.length > 0 ? { omittedReasons } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function promptHasChatHistoryAttachment(prompt: AgentPromptInput): boolean {
|
||||
if (!Array.isArray(prompt)) return false;
|
||||
return prompt.some(
|
||||
(block) =>
|
||||
block.type === "text" && "contextKind" in block && block.contextKind === "chat_history",
|
||||
);
|
||||
}
|
||||
|
||||
export function prependHandoffAttachment(
|
||||
prompt: AgentPromptInput,
|
||||
attachment: TextAgentAttachment | null,
|
||||
): AgentPromptInput {
|
||||
if (!attachment) return prompt;
|
||||
if (typeof prompt === "string") {
|
||||
return [attachment, { type: "text", text: prompt }];
|
||||
}
|
||||
if (!Array.isArray(prompt)) {
|
||||
return prompt;
|
||||
}
|
||||
return [attachment, ...prompt];
|
||||
}
|
||||
|
||||
export function renderProviderPromptText(prompt: AgentPromptInput): string {
|
||||
if (typeof prompt === "string") return prompt;
|
||||
if (!Array.isArray(prompt)) return "";
|
||||
return prompt
|
||||
.flatMap((block) => (block.type === "text" ? [block.text] : []))
|
||||
.join("\n\n")
|
||||
.trim();
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
export {
|
||||
buildProviderSwitchHandoff,
|
||||
HANDOFF_TAIL_LIMIT,
|
||||
MAX_HANDOFF_CONTEXT_CHARS,
|
||||
prependHandoffAttachment,
|
||||
promptHasChatHistoryAttachment,
|
||||
renderProviderPromptText,
|
||||
type ProviderSwitchHandoffResult,
|
||||
} from "./handoff-context.js";
|
||||
@@ -0,0 +1,648 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it, onTestFinished } from "vitest";
|
||||
import { createTestLogger } from "../../../test-utils/test-logger.js";
|
||||
import { AgentManager, AgentProviderSwitchStartError } from "../agent-manager.js";
|
||||
import { AgentStorage } from "../agent-storage.js";
|
||||
import { ensureAgentLoaded } from "../agent-loading.js";
|
||||
import { startAgentRun } from "../agent-prompt.js";
|
||||
import { createStoredAgentTimeline } from "../timeline/index.js";
|
||||
import { openTestTimelineDatabase } from "../timeline/testing.js";
|
||||
import type {
|
||||
AgentClient,
|
||||
AgentPersistenceHandle,
|
||||
AgentPromptInput,
|
||||
AgentProvider,
|
||||
AgentRunOptions,
|
||||
AgentRunResult,
|
||||
AgentSession,
|
||||
AgentSessionConfig,
|
||||
AgentStreamEvent,
|
||||
ConversationRewindResult,
|
||||
} from "../agent-sdk-types.js";
|
||||
import { renderProviderPromptText } from "./index.js";
|
||||
|
||||
const BASE_CAPABILITIES = {
|
||||
supportsStreaming: true,
|
||||
supportsSessionPersistence: true,
|
||||
supportsDynamicModes: false,
|
||||
supportsMcpServers: true,
|
||||
supportsReasoningStream: false,
|
||||
supportsToolInvocations: true,
|
||||
supportsRewindConversation: true,
|
||||
supportsRewindFiles: false,
|
||||
supportsRewindBoth: false,
|
||||
} as const;
|
||||
|
||||
class FakeSession implements AgentSession {
|
||||
readonly id: string;
|
||||
readonly provider: AgentProvider;
|
||||
readonly capabilities = BASE_CAPABILITIES;
|
||||
readonly receivedPrompts: Array<{ prompt: AgentPromptInput; options?: AgentRunOptions }> = [];
|
||||
closed = false;
|
||||
private listeners = new Set<(event: AgentStreamEvent) => void>();
|
||||
private persistence: AgentPersistenceHandle | null;
|
||||
private turnCount = 0;
|
||||
private readonly onStartTurn?: (
|
||||
session: FakeSession,
|
||||
prompt: AgentPromptInput,
|
||||
options?: AgentRunOptions,
|
||||
) => Promise<void> | void;
|
||||
private readonly onClose?: () => Promise<void> | void;
|
||||
private readonly persistAfterFirstTurn: boolean;
|
||||
private readonly echoBeforeStartResolves: boolean;
|
||||
|
||||
constructor(params: {
|
||||
id: string;
|
||||
provider: AgentProvider;
|
||||
initialPersistence: AgentPersistenceHandle | null;
|
||||
persistAfterFirstTurn?: boolean;
|
||||
echoBeforeStartResolves?: boolean;
|
||||
onStartTurn?: (
|
||||
session: FakeSession,
|
||||
prompt: AgentPromptInput,
|
||||
options?: AgentRunOptions,
|
||||
) => Promise<void> | void;
|
||||
onClose?: () => Promise<void> | void;
|
||||
}) {
|
||||
this.id = params.id;
|
||||
this.provider = params.provider;
|
||||
this.persistence = params.initialPersistence;
|
||||
this.persistAfterFirstTurn = params.persistAfterFirstTurn ?? false;
|
||||
this.echoBeforeStartResolves = params.echoBeforeStartResolves ?? false;
|
||||
this.onStartTurn = params.onStartTurn;
|
||||
this.onClose = params.onClose;
|
||||
}
|
||||
|
||||
emit(event: AgentStreamEvent): void {
|
||||
for (const listener of this.listeners) listener(event);
|
||||
}
|
||||
|
||||
subscribe(listener: (event: AgentStreamEvent) => void): () => void {
|
||||
this.listeners.add(listener);
|
||||
return () => this.listeners.delete(listener);
|
||||
}
|
||||
|
||||
async startTurn(
|
||||
prompt: AgentPromptInput,
|
||||
options?: AgentRunOptions,
|
||||
): Promise<{ turnId: string }> {
|
||||
this.receivedPrompts.push({ prompt, options });
|
||||
if (this.onStartTurn) {
|
||||
await this.onStartTurn(this, prompt, options);
|
||||
}
|
||||
this.turnCount += 1;
|
||||
const turnId = `${this.provider}-turn-${this.turnCount}`;
|
||||
const providerMessageId = `${this.provider}-msg-${this.turnCount}`;
|
||||
if (this.persistAfterFirstTurn && !this.persistence) {
|
||||
this.persistence = { provider: this.provider, sessionId: `${this.provider}-late-${this.id}` };
|
||||
}
|
||||
const rendered = renderProviderPromptText(prompt);
|
||||
const emitTurn = () => {
|
||||
if (options?.clientMessageId) {
|
||||
this.emit({
|
||||
type: "timeline",
|
||||
provider: this.provider,
|
||||
turnId,
|
||||
item: {
|
||||
type: "user_message",
|
||||
text: rendered,
|
||||
messageId: providerMessageId,
|
||||
clientMessageId: options.clientMessageId,
|
||||
},
|
||||
});
|
||||
}
|
||||
this.emit({
|
||||
type: "timeline",
|
||||
provider: this.provider,
|
||||
turnId,
|
||||
item: {
|
||||
type: "assistant_message",
|
||||
text: `${this.provider} reply ${this.turnCount}`,
|
||||
},
|
||||
});
|
||||
this.emit({
|
||||
type: "turn_completed",
|
||||
provider: this.provider,
|
||||
turnId,
|
||||
});
|
||||
};
|
||||
|
||||
if (this.echoBeforeStartResolves) {
|
||||
emitTurn();
|
||||
} else {
|
||||
queueMicrotask(emitTurn);
|
||||
}
|
||||
return { turnId };
|
||||
}
|
||||
|
||||
async run(prompt: AgentPromptInput, options?: AgentRunOptions): Promise<AgentRunResult> {
|
||||
await this.startTurn(prompt, options);
|
||||
return { sessionId: this.id, finalText: "", timeline: [] };
|
||||
}
|
||||
|
||||
async *stream(): AsyncGenerator<AgentStreamEvent> {}
|
||||
async *streamHistory(): AsyncGenerator<AgentStreamEvent> {}
|
||||
|
||||
async revertConversation(): Promise<ConversationRewindResult> {
|
||||
return { kind: "after", retainedMessageId: null };
|
||||
}
|
||||
|
||||
async interrupt(): Promise<void> {}
|
||||
async getAvailableModes() {
|
||||
return [];
|
||||
}
|
||||
async getCurrentMode() {
|
||||
return null;
|
||||
}
|
||||
async setMode() {}
|
||||
async getRuntimeInfo() {
|
||||
return {
|
||||
provider: this.provider,
|
||||
sessionId: this.persistence?.sessionId ?? null,
|
||||
model: `${this.provider}-model`,
|
||||
};
|
||||
}
|
||||
describePersistence(): AgentPersistenceHandle | null {
|
||||
return this.persistence;
|
||||
}
|
||||
async close(): Promise<void> {
|
||||
if (this.onClose) {
|
||||
await this.onClose();
|
||||
}
|
||||
this.closed = true;
|
||||
}
|
||||
}
|
||||
|
||||
class FakeClient implements AgentClient {
|
||||
readonly capabilities = BASE_CAPABILITIES;
|
||||
readonly createdSessions: FakeSession[] = [];
|
||||
resumeCalls = 0;
|
||||
available = true;
|
||||
failNextCreate: Error | null = null;
|
||||
initialPersistenceNull = false;
|
||||
persistAfterFirstTurn = false;
|
||||
echoBeforeStartResolves = false;
|
||||
onStartTurn?: (
|
||||
session: FakeSession,
|
||||
prompt: AgentPromptInput,
|
||||
options?: AgentRunOptions,
|
||||
) => Promise<void> | void;
|
||||
onClose?: () => Promise<void> | void;
|
||||
|
||||
constructor(readonly provider: AgentProvider) {}
|
||||
|
||||
async isAvailable(): Promise<boolean> {
|
||||
return this.available;
|
||||
}
|
||||
|
||||
async createSession(_config: AgentSessionConfig): Promise<AgentSession> {
|
||||
if (this.failNextCreate) {
|
||||
const error = this.failNextCreate;
|
||||
this.failNextCreate = null;
|
||||
throw error;
|
||||
}
|
||||
const id = `${this.provider}-sess-${this.createdSessions.length + 1}`;
|
||||
const session = new FakeSession({
|
||||
id,
|
||||
provider: this.provider,
|
||||
initialPersistence: this.initialPersistenceNull
|
||||
? null
|
||||
: { provider: this.provider, sessionId: id },
|
||||
persistAfterFirstTurn: this.persistAfterFirstTurn,
|
||||
echoBeforeStartResolves: this.echoBeforeStartResolves,
|
||||
onStartTurn: (activeSession, prompt, options) =>
|
||||
this.onStartTurn?.(activeSession, prompt, options),
|
||||
onClose: () => this.onClose?.(),
|
||||
});
|
||||
this.createdSessions.push(session);
|
||||
return session;
|
||||
}
|
||||
|
||||
async resumeSession(handle: AgentPersistenceHandle): Promise<AgentSession> {
|
||||
this.resumeCalls += 1;
|
||||
const session = new FakeSession({
|
||||
id: handle.sessionId,
|
||||
provider: this.provider,
|
||||
initialPersistence: handle,
|
||||
onStartTurn: this.onStartTurn,
|
||||
});
|
||||
this.createdSessions.push(session);
|
||||
return session;
|
||||
}
|
||||
}
|
||||
|
||||
function createHarness() {
|
||||
const dir = mkdtempSync(join(tmpdir(), "paseo-switch-test-"));
|
||||
onTestFinished(() => rmSync(dir, { recursive: true, force: true }));
|
||||
const cwd = mkdtempSync(join(tmpdir(), "paseo-switch-cwd-"));
|
||||
onTestFinished(() => rmSync(cwd, { recursive: true, force: true }));
|
||||
const logger = createTestLogger();
|
||||
const db = openTestTimelineDatabase();
|
||||
const timeline = createStoredAgentTimeline(db);
|
||||
const storage = new AgentStorage(dir, logger);
|
||||
const claude = new FakeClient("claude");
|
||||
const codex = new FakeClient("codex");
|
||||
const manager = new AgentManager({
|
||||
logger,
|
||||
registry: storage,
|
||||
timeline,
|
||||
clients: { claude, codex },
|
||||
});
|
||||
onTestFinished(async () => {
|
||||
await manager.flush().catch(() => undefined);
|
||||
await timeline.close().catch(() => undefined);
|
||||
});
|
||||
return { dir, cwd, logger, db, timeline, storage, claude, codex, manager };
|
||||
}
|
||||
|
||||
async function runAndWaitIdle(
|
||||
manager: AgentManager,
|
||||
agentId: string,
|
||||
prompt: AgentPromptInput,
|
||||
clientMessageId: string,
|
||||
): Promise<void> {
|
||||
const logger = createTestLogger();
|
||||
const idle = new Promise<void>((resolve) => {
|
||||
const unsub = manager.subscribe(
|
||||
(event) => {
|
||||
if (event.type === "agent_state" && event.agent.lifecycle === "idle") {
|
||||
unsub();
|
||||
resolve();
|
||||
}
|
||||
},
|
||||
{ agentId, replayState: false },
|
||||
);
|
||||
});
|
||||
const dispatch = await startAgentRun(manager, agentId, prompt, logger, {
|
||||
runOptions: { clientMessageId },
|
||||
});
|
||||
if (dispatch.disposition === "turn_started") {
|
||||
await dispatch.started;
|
||||
}
|
||||
await idle;
|
||||
await manager.flush();
|
||||
}
|
||||
|
||||
describe("AgentManager provider switching", () => {
|
||||
it("switches a live agent to a provider with null initial persistence, preserves history, keeps <chat-history-summary> out of item.text, and tracks previousSessions", async () => {
|
||||
const { cwd, manager, storage, timeline, claude, codex } = createHarness();
|
||||
// Simulate Codex/Claude returning persistence: null until turn 1 runs
|
||||
codex.initialPersistenceNull = true;
|
||||
codex.persistAfterFirstTurn = true;
|
||||
|
||||
const agentId = randomUUID();
|
||||
const created = await manager.createAgent(
|
||||
{ provider: "claude", cwd, title: "Auth refactor" },
|
||||
agentId,
|
||||
{ workspaceId: "ws-1", labels: { team: "core" }, metadata: { ticket: "P-1" } },
|
||||
);
|
||||
await runAndWaitIdle(manager, created.id, "Analyze auth.ts", "msg-c1");
|
||||
|
||||
const switched = await manager.switchAgentProvider(created.id, {
|
||||
toProvider: "codex",
|
||||
model: "gpt-5.4",
|
||||
prompt: "Now rewrite it cleanly",
|
||||
messageId: "msg-sw1",
|
||||
});
|
||||
|
||||
expect(switched.agent.id).toBe(agentId);
|
||||
expect(switched.agent.provider).toBe("codex");
|
||||
expect(switched.agent.workspaceId).toBe("ws-1");
|
||||
expect(switched.agent.labels).toEqual({ team: "core" });
|
||||
expect(switched.agent.metadata).toEqual({ ticket: "P-1" });
|
||||
expect(claude.createdSessions[0]!.closed).toBe(true);
|
||||
|
||||
// Marker persisted with toSessionId: null (since codex had null persistence before turn 1)
|
||||
const rowsBeforeTurn1 = await timeline.readRows({ agentId });
|
||||
const marker = rowsBeforeTurn1.find((r) => r.item.type === "provider_switch");
|
||||
expect(marker?.item).toMatchObject({
|
||||
type: "provider_switch",
|
||||
fromProvider: "claude",
|
||||
toProvider: "codex",
|
||||
fromSessionId: "claude-sess-1",
|
||||
toSessionId: null,
|
||||
});
|
||||
|
||||
// Run turn 1 on Codex with the handoffPrompt
|
||||
await runAndWaitIdle(manager, agentId, switched.handoffPrompt, "msg-sw1");
|
||||
|
||||
// Codex received the handoff attachment + user prompt
|
||||
const codexPrompt1 = codex.createdSessions[0]!.receivedPrompts[0]!.prompt;
|
||||
expect(renderProviderPromptText(codexPrompt1)).toContain("<chat-history-summary>");
|
||||
expect(renderProviderPromptText(codexPrompt1)).toContain("Analyze auth.ts");
|
||||
|
||||
// Stored timeline rows: earlier rows keep provider "claude", switch prompt keeps clean item.text!
|
||||
const allRows = await timeline.readRows({ agentId });
|
||||
const claudePrompt = allRows.find(
|
||||
(r) => r.item.type === "user_message" && r.item.messageId === "msg-c1",
|
||||
);
|
||||
const codexPrompt = allRows.find(
|
||||
(r) => r.item.type === "user_message" && r.item.messageId === "msg-sw1",
|
||||
);
|
||||
expect(claudePrompt?.provider).toBe("claude");
|
||||
expect(codexPrompt?.provider).toBe("codex");
|
||||
expect(codexPrompt?.item).toMatchObject({
|
||||
type: "user_message",
|
||||
text: "Now rewrite it cleanly",
|
||||
});
|
||||
expect(codexPrompt?.item.type === "user_message" ? codexPrompt.item.text : "").not.toContain(
|
||||
"<chat-history-summary>",
|
||||
);
|
||||
expect(codexPrompt?.providerPromptText).toContain("<chat-history-summary>");
|
||||
|
||||
// previousSessions tracks Claude's handle: resume lookup ignores it, import lookup finds it
|
||||
const stored = await storage.get(agentId);
|
||||
expect(stored?.provider).toBe("codex");
|
||||
expect(stored?.previousSessions).toEqual([
|
||||
expect.objectContaining({ provider: "claude", sessionId: "claude-sess-1" }),
|
||||
]);
|
||||
const foundForResume = await storage.listByProviderSession("claude", "claude-sess-1");
|
||||
expect(foundForResume).toEqual([]);
|
||||
const foundForImport = await storage.listByProviderSession("claude", "claude-sess-1", {
|
||||
includePreviousSessions: true,
|
||||
});
|
||||
expect(foundForImport.map((r) => r.id)).toEqual([agentId]);
|
||||
});
|
||||
|
||||
it("keeps the original session live and leaves no switch marker when target creation fails", async () => {
|
||||
const { cwd, manager, timeline, claude, codex } = createHarness();
|
||||
const created = await manager.createAgent({ provider: "claude", cwd }, randomUUID(), {});
|
||||
await runAndWaitIdle(manager, created.id, "Hello", "msg-1");
|
||||
|
||||
codex.failNextCreate = new Error("codex CLI failed to start");
|
||||
await expect(
|
||||
manager.switchAgentProvider(created.id, {
|
||||
toProvider: "codex",
|
||||
prompt: "Switch now",
|
||||
messageId: "msg-2",
|
||||
}),
|
||||
).rejects.toThrow("codex CLI failed to start");
|
||||
|
||||
// Claude session is still live and usable, and no marker or open switch intent exists
|
||||
expect(manager.getAgent(created.id)?.provider).toBe("claude");
|
||||
expect(claude.createdSessions[0]!.closed).toBe(false);
|
||||
expect((await timeline.describe({ agentId: created.id }))?.providerSwitch).toBeNull();
|
||||
expect((await timeline.describe({ agentId: created.id }))?.activeSegmentStartSeq).toBe(0);
|
||||
|
||||
await runAndWaitIdle(manager, created.id, "Still on Claude", "msg-3");
|
||||
expect(claude.createdSessions[0]!.receivedPrompts).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("switches a closed agent directly from SQLite history without booting the old provider", async () => {
|
||||
const { cwd, manager, claude, codex } = createHarness();
|
||||
const created = await manager.createAgent({ provider: "claude", cwd }, randomUUID(), {});
|
||||
await runAndWaitIdle(manager, created.id, "Stored turn", "msg-1");
|
||||
await manager.closeAgent(created.id);
|
||||
expect(manager.getAgent(created.id)).toBeNull();
|
||||
|
||||
const switched = await manager.switchAgentProvider(created.id, {
|
||||
toProvider: "codex",
|
||||
prompt: "Continue on Codex",
|
||||
messageId: "msg-2",
|
||||
});
|
||||
|
||||
expect(switched.agent.provider).toBe("codex");
|
||||
expect(claude.resumeCalls).toBe(0);
|
||||
expect(renderProviderPromptText(switched.handoffPrompt)).toContain("Stored turn");
|
||||
expect(codex.createdSessions).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("heals crash recovery for marker_committed with null targetPersistence through ensureAgentLoaded and re-injects context on turn 1", async () => {
|
||||
const { cwd, manager, storage, timeline, logger, codex } = createHarness();
|
||||
codex.initialPersistenceNull = true;
|
||||
|
||||
const created = await manager.createAgent({ provider: "claude", cwd }, randomUUID(), {});
|
||||
await runAndWaitIdle(manager, created.id, "Before crash", "msg-1");
|
||||
await manager.closeAgent(created.id);
|
||||
|
||||
// Simulate a crash right after commitProviderSwitch (marker_committed) before StoredAgentRecord updated!
|
||||
const intent = await timeline.beginProviderSwitch(
|
||||
{ agentId: created.id },
|
||||
{
|
||||
messageId: "msg-crash-sw",
|
||||
fromProvider: "claude",
|
||||
fromPersistence: { provider: "claude", sessionId: "claude-sess-1" },
|
||||
fromModel: "claude-model",
|
||||
toProvider: "codex",
|
||||
toConfig: { model: "gpt-5.4", modeId: "auto" },
|
||||
targetPersistence: null,
|
||||
context: { includedItems: 2, truncated: false, charCount: 80, budgetChars: 100_000 },
|
||||
},
|
||||
);
|
||||
await timeline.commitProviderSwitch({ agentId: created.id }, intent.id, {
|
||||
markerEntry: {
|
||||
provider: "codex",
|
||||
item: {
|
||||
type: "provider_switch",
|
||||
fromProvider: "claude",
|
||||
toProvider: "codex",
|
||||
fromModel: "claude-model",
|
||||
toModel: "gpt-5.4",
|
||||
fromSessionId: "claude-sess-1",
|
||||
toSessionId: null,
|
||||
context: { includedItems: 2, truncated: false, charCount: 80, budgetChars: 100_000 },
|
||||
},
|
||||
},
|
||||
targetPersistence: null,
|
||||
});
|
||||
|
||||
// StoredAgentRecord on disk is still stale (points to claude with claude persistence & runtimeInfo)
|
||||
const staleRecord = await storage.get(created.id);
|
||||
expect(staleRecord?.provider).toBe("claude");
|
||||
|
||||
// ensureAgentLoaded reconciles the committed switch and opens Codex cleanly via createAgentFromRecord
|
||||
const loaded = await ensureAgentLoaded(created.id, {
|
||||
agentManager: manager,
|
||||
agentStorage: storage,
|
||||
logger,
|
||||
});
|
||||
expect(loaded.provider).toBe("codex");
|
||||
expect((await timeline.describe({ agentId: created.id }))?.providerSwitch).toBeNull();
|
||||
|
||||
const repairedRecord = await storage.get(created.id);
|
||||
expect(repairedRecord?.provider).toBe("codex");
|
||||
expect(repairedRecord?.previousSessions).toEqual([
|
||||
expect.objectContaining({ provider: "claude", sessionId: "claude-sess-1" }),
|
||||
]);
|
||||
|
||||
// First prompt sent after crash recovery automatically receives fresh pre-switch context!
|
||||
await runAndWaitIdle(manager, created.id, "First prompt after recovery", "msg-after-crash");
|
||||
const delivered = renderProviderPromptText(
|
||||
codex.createdSessions[0]!.receivedPrompts[0]!.prompt,
|
||||
);
|
||||
expect(delivered).toContain("<chat-history-summary>");
|
||||
expect(delivered).toContain("Before crash");
|
||||
expect(delivered).toContain("First prompt after recovery");
|
||||
|
||||
// Second prompt in the same segment does NOT double-inject context
|
||||
await runAndWaitIdle(manager, created.id, "Second prompt", "msg-after-crash-2");
|
||||
const delivered2 = renderProviderPromptText(
|
||||
codex.createdSessions[0]!.receivedPrompts[1]!.prompt,
|
||||
);
|
||||
expect(delivered2).not.toContain("<chat-history-summary>");
|
||||
});
|
||||
|
||||
it("re-injects fresh pre-switch context after rewinding turn 1 and after a rejected turn 1, and prevents <chat-history-summary> leak on early echo race", async () => {
|
||||
const { cwd, manager, timeline, codex } = createHarness();
|
||||
// Simulate early echo race (provider echoes user_message before startTurn resolves!)
|
||||
codex.echoBeforeStartResolves = true;
|
||||
|
||||
const created = await manager.createAgent({ provider: "claude", cwd }, randomUUID(), {});
|
||||
await runAndWaitIdle(manager, created.id, "Claude context turn", "msg-c1");
|
||||
|
||||
let failFirstCodexTurn = true;
|
||||
codex.onStartTurn = () => {
|
||||
if (failFirstCodexTurn) {
|
||||
failFirstCodexTurn = false;
|
||||
throw new Error("Transient Codex start error");
|
||||
}
|
||||
};
|
||||
|
||||
const switched = await manager.switchAgentProvider(created.id, {
|
||||
toProvider: "codex",
|
||||
prompt: "Attempt 1",
|
||||
messageId: "msg-sw1",
|
||||
});
|
||||
|
||||
// Turn 1 rejects before Codex accepts -> rejected user_message recorded
|
||||
const logger = createTestLogger();
|
||||
await expect(
|
||||
(async () => {
|
||||
const dispatch = await startAgentRun(manager, created.id, switched.handoffPrompt, logger, {
|
||||
runOptions: { clientMessageId: "msg-sw1" },
|
||||
});
|
||||
if (dispatch.disposition === "turn_started") await dispatch.started;
|
||||
})(),
|
||||
).rejects.toThrow("Transient Codex start error");
|
||||
await manager.flush();
|
||||
|
||||
// Retry with a fresh messageId (no attachment passed by caller) -> auto-reinjects fresh context!
|
||||
await runAndWaitIdle(manager, created.id, "Attempt 2 succeeds", "msg-sw2");
|
||||
const retryDelivered = renderProviderPromptText(
|
||||
codex.createdSessions[0]!.receivedPrompts[1]!.prompt,
|
||||
);
|
||||
expect(retryDelivered).toContain("<chat-history-summary>");
|
||||
expect(retryDelivered).toContain("Claude context turn");
|
||||
|
||||
// Early echo race MUST NOT leak <chat-history-summary> into item.text!
|
||||
const rowsAfterRetry = await timeline.readRows({ agentId: created.id });
|
||||
const retryRow = rowsAfterRetry.find(
|
||||
(r) => r.item.type === "user_message" && r.item.messageId === "msg-sw2",
|
||||
);
|
||||
expect(retryRow?.item).toMatchObject({ type: "user_message", text: "Attempt 2 succeeds" });
|
||||
expect(retryRow?.item.type === "user_message" ? retryRow.item.text : "").not.toContain(
|
||||
"<chat-history-summary>",
|
||||
);
|
||||
expect(retryRow?.providerPromptText).toContain("<chat-history-summary>");
|
||||
|
||||
// Now rewind Attempt 2 (first accepted post-switch turn) -> pre-switch history & marker stay!
|
||||
await manager.rewind(created.id, "msg-sw2", "conversation");
|
||||
const rowsAfterRewind = await timeline.readRows({ agentId: created.id });
|
||||
expect(rowsAfterRewind.some((r) => r.item.type === "provider_switch")).toBe(true);
|
||||
expect(
|
||||
rowsAfterRewind.some((r) => r.item.type === "user_message" && r.item.messageId === "msg-c1"),
|
||||
).toBe(true);
|
||||
|
||||
// Sending a fresh prompt after rewinding turn 1 re-injects bounded pre-switch context!
|
||||
await runAndWaitIdle(manager, created.id, "After rewind prompt", "msg-sw3");
|
||||
const afterRewindDelivered = renderProviderPromptText(
|
||||
codex.createdSessions[0]!.receivedPrompts[2]!.prompt,
|
||||
);
|
||||
expect(afterRewindDelivered).toContain("<chat-history-summary>");
|
||||
expect(afterRewindDelivered).toContain("Claude context turn");
|
||||
expect(afterRewindDelivered).toContain("After rewind prompt");
|
||||
});
|
||||
|
||||
it("keeps waitForAgentEvent following the same chat across provider-switch session replacement while blocking overlapping turns", async () => {
|
||||
const { cwd, manager, claude, codex } = createHarness();
|
||||
const logger = createTestLogger();
|
||||
|
||||
const created = await manager.createAgent({ provider: "claude", cwd }, randomUUID(), {});
|
||||
await runAndWaitIdle(manager, created.id, "Before switch", "msg-before");
|
||||
|
||||
let notifySourceClosing!: () => void;
|
||||
const sourceClosing = new Promise<void>((resolve) => {
|
||||
notifySourceClosing = resolve;
|
||||
});
|
||||
let releaseSourceClose!: () => void;
|
||||
const sourceCloseGate = new Promise<void>((resolve) => {
|
||||
releaseSourceClose = resolve;
|
||||
});
|
||||
claude.onClose = async () => {
|
||||
notifySourceClosing();
|
||||
await sourceCloseGate;
|
||||
};
|
||||
|
||||
let notifyTargetTurnStarting!: () => void;
|
||||
const targetTurnStarting = new Promise<void>((resolve) => {
|
||||
notifyTargetTurnStarting = resolve;
|
||||
});
|
||||
let releaseTargetTurn!: () => void;
|
||||
const targetTurnGate = new Promise<void>((resolve) => {
|
||||
releaseTargetTurn = resolve;
|
||||
});
|
||||
codex.onStartTurn = async () => {
|
||||
notifyTargetTurnStarting();
|
||||
await targetTurnGate;
|
||||
};
|
||||
|
||||
const switchPromise = manager.switchAgentProvider(created.id, {
|
||||
toProvider: "codex",
|
||||
prompt: "After switch",
|
||||
messageId: "msg-after",
|
||||
admitFirstTurn: async (result, switchReservationToken) => {
|
||||
const dispatch = await startAgentRun(manager, created.id, result.handoffPrompt, logger, {
|
||||
idleOnly: true,
|
||||
skipPluginReload: true,
|
||||
switchReservationToken,
|
||||
runOptions: { clientMessageId: "msg-after" },
|
||||
});
|
||||
expect(dispatch.disposition).toBe("turn_started");
|
||||
},
|
||||
});
|
||||
|
||||
// Wait until the switch holds its reservation and is closing the source session.
|
||||
await sourceClosing;
|
||||
|
||||
// Overlap protection remains enforced while the switch reservation is held.
|
||||
expect(manager.hasInFlightRun(created.id)).toBe(true);
|
||||
expect(() => manager.streamAgent(created.id, "Overlapping prompt")).toThrow(
|
||||
/already has an active run/,
|
||||
);
|
||||
await expect(manager.cancelAgentRun(created.id)).resolves.toEqual({ status: "refused" });
|
||||
|
||||
// Start waitForAgentEvent right before prepareAgentForClosure deletes the source session.
|
||||
let waitSettled = false;
|
||||
const waitResultPromise = manager.waitForAgentEvent(created.id).then((res) => {
|
||||
waitSettled = true;
|
||||
return res;
|
||||
});
|
||||
|
||||
// Aborting another waiter during the switch reservation still rejects promptly.
|
||||
const abortController = new AbortController();
|
||||
const abortedWait = manager.waitForAgentEvent(created.id, { signal: abortController.signal });
|
||||
abortController.abort();
|
||||
await expect(abortedWait).rejects.toThrow(/aborted/i);
|
||||
|
||||
// Let source close finish, register Codex, and atomically hand off into Codex's first turn.
|
||||
releaseSourceClose();
|
||||
await targetTurnStarting;
|
||||
|
||||
// Waiter MUST NOT have thrown "Agent not found" or resolved early during session replacement.
|
||||
await Promise.resolve();
|
||||
expect(waitSettled).toBe(false);
|
||||
|
||||
// Complete Codex's turn and confirm the waiter receives Codex's reply on the same chat.
|
||||
releaseTargetTurn();
|
||||
await switchPromise;
|
||||
const waitResult = await waitResultPromise;
|
||||
expect(waitResult.status).toBe("idle");
|
||||
expect(waitResult.lastMessage).toBe("codex reply 1");
|
||||
});
|
||||
});
|
||||
|
||||
// Touch AgentProviderSwitchStartError to verify export
|
||||
void AgentProviderSwitchStartError;
|
||||
@@ -1,5 +1,10 @@
|
||||
import { continuesTimelineTurn, isTimelineTurnTrigger } from "@getpaseo/protocol/timeline-turn";
|
||||
import type { AgentMetric, AgentTimelineItem, ToolCallDetail } from "./agent-sdk-types.js";
|
||||
import type {
|
||||
AgentMetric,
|
||||
AgentProvider,
|
||||
AgentTimelineItem,
|
||||
ToolCallDetail,
|
||||
} from "./agent-sdk-types.js";
|
||||
import { timelineItemIdentity } from "@getpaseo/protocol/timeline-identity";
|
||||
|
||||
import type { AgentTimelineRow } from "./agent-timeline-store-types.js";
|
||||
@@ -20,8 +25,11 @@ export type TimelineLimitDirection = "tail" | "before" | "after";
|
||||
|
||||
export interface TimelineProjectionEntry {
|
||||
item: AgentTimelineItem;
|
||||
provider?: AgentProvider;
|
||||
turnId?: string;
|
||||
providerMessageId?: string;
|
||||
providerPromptText?: string;
|
||||
rejected?: boolean;
|
||||
turnMetrics?: AgentMetric[];
|
||||
timestamp: string;
|
||||
seqStart: number;
|
||||
@@ -135,8 +143,13 @@ function makeCanonicalEntries(rows: readonly AgentTimelineRow[]): WorkingEntry[]
|
||||
return {
|
||||
item: row.item,
|
||||
timestamp: row.timestamp,
|
||||
...(row.provider ? { provider: row.provider } : {}),
|
||||
...(row.turnId ? { turnId: row.turnId } : {}),
|
||||
...(row.providerMessageId ? { providerMessageId: row.providerMessageId } : {}),
|
||||
...(row.providerPromptText !== undefined
|
||||
? { providerPromptText: row.providerPromptText }
|
||||
: {}),
|
||||
...(row.rejected ? { rejected: true } : {}),
|
||||
...(row.turnMetrics ? { turnMetrics: row.turnMetrics } : {}),
|
||||
seqStart: row.seq,
|
||||
seqEnd: row.seq,
|
||||
@@ -332,7 +345,7 @@ function mergeAssistantChunks(entries: readonly WorkingEntry[]): WorkingEntry[]
|
||||
/** A retained item. `seq` is its latest source event, not its display anchor. */
|
||||
export type ProjectedTimelineRow = AgentTimelineRow & TimelineProjectionEntry;
|
||||
|
||||
interface ProjectedTimelinePageOptions {
|
||||
export interface ProjectedTimelinePageOptions {
|
||||
wholeTurns?: boolean;
|
||||
bounds: { minSeq: number; maxSeq: number };
|
||||
direction: TimelineLimitDirection;
|
||||
@@ -340,6 +353,61 @@ interface ProjectedTimelinePageOptions {
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* How a new source row lands in a projection:
|
||||
* - `identity`: it updates `identityRow`, the active row with the same item identity;
|
||||
* - `adjacent`: it continues `lastRow`, the last active row (streamed assistant or reasoning text);
|
||||
* - `new`: it becomes a new last row.
|
||||
* The result is the whole projected row. For `adjacent`, a merged text is `lastRow`'s text followed
|
||||
* by the new chunk, so a `lastRow` passed with empty text yields the chunk alone.
|
||||
*/
|
||||
export type TimelineRowFold =
|
||||
| { kind: "identity"; row: ProjectedTimelineRow }
|
||||
| { kind: "adjacent"; row: ProjectedTimelineRow }
|
||||
| { kind: "new"; row: ProjectedTimelineRow };
|
||||
|
||||
export function foldTimelineRow(input: {
|
||||
row: AgentTimelineRow;
|
||||
/** The row the projection holds for `timelineItemIdentity(row.item)`, if any. */
|
||||
identityRow: ProjectedTimelineRow | undefined;
|
||||
lastRow: ProjectedTimelineRow | undefined;
|
||||
}): TimelineRowFold {
|
||||
const entry = makeCanonicalEntries([input.row])[0];
|
||||
const merged = input.identityRow ? mergeIdentityEntries(input.identityRow, entry) : null;
|
||||
if (merged) return { kind: "identity", row: { ...merged, seq: merged.seqEnd } };
|
||||
const previous = input.lastRow;
|
||||
const adjacent = previous
|
||||
? mergeReasoningChunks(mergeAssistantChunks([previous, entry]))
|
||||
: [entry];
|
||||
if (previous && adjacent.length === 1) {
|
||||
return { kind: "adjacent", row: { ...adjacent[0], seq: adjacent[0].seqEnd } };
|
||||
}
|
||||
return { kind: "new", row: { ...entry, seq: entry.seqEnd } };
|
||||
}
|
||||
|
||||
/**
|
||||
* Merges neighbouring retirements that no active row separates. Merging keeps the meaning (drop
|
||||
* rows anchored in `[retireFromSeq, seq)`) and bounds the count by the active rows in the span.
|
||||
*/
|
||||
export function coalesceTimelineRetirements(
|
||||
retirements: readonly TimelineRetirement[],
|
||||
hasActiveAnchorIn: (startSeq: number, endSeq: number) => boolean,
|
||||
): TimelineRetirement[] {
|
||||
const coalesced: TimelineRetirement[] = [];
|
||||
for (const retirement of retirements) {
|
||||
const previous = coalesced.at(-1);
|
||||
if (previous && !hasActiveAnchorIn(previous.seq, retirement.retireFromSeq)) {
|
||||
coalesced[coalesced.length - 1] = {
|
||||
seq: retirement.seq,
|
||||
retireFromSeq: Math.min(previous.retireFromSeq, retirement.retireFromSeq),
|
||||
};
|
||||
continue;
|
||||
}
|
||||
coalesced.push({ ...retirement });
|
||||
}
|
||||
return coalesced;
|
||||
}
|
||||
|
||||
/** Owns projected state; source events are consumed, never retained. */
|
||||
export class TimelineProjection {
|
||||
private readonly rows: ProjectedTimelineRow[] = [];
|
||||
@@ -354,6 +422,7 @@ export class TimelineProjection {
|
||||
private readonly retirements: TimelineRetirement[] = [];
|
||||
private readonly retiredIdentities = new Set<string>();
|
||||
private readonly retiredTurnIds = new Set<string>();
|
||||
private activeSegmentStartSeq = 0;
|
||||
|
||||
constructor(rows: readonly AgentTimelineRow[] = []) {
|
||||
for (const row of rows) this.appendProjected(row);
|
||||
@@ -375,28 +444,29 @@ export class TimelineProjection {
|
||||
}
|
||||
|
||||
private appendProjected(row: AgentTimelineRow): number {
|
||||
const entry = makeCanonicalEntries([row])[0];
|
||||
const identity = timelineItemIdentity(row.item);
|
||||
const index = identity === null ? undefined : this.identities.get(identity);
|
||||
const existing = index === undefined ? undefined : this.rows[index];
|
||||
const merged = existing ? mergeIdentityEntries(existing, entry) : null;
|
||||
if (merged && index !== undefined) {
|
||||
this.rows[index] = { ...merged, seq: merged.seqEnd };
|
||||
const fold = foldTimelineRow({
|
||||
row,
|
||||
identityRow: index === undefined ? undefined : this.rows[index],
|
||||
lastRow: this.rows.at(-1),
|
||||
});
|
||||
if (fold.kind === "identity" && index !== undefined) {
|
||||
this.rows[index] = fold.row;
|
||||
this.extendSpan(index);
|
||||
return index;
|
||||
}
|
||||
const previous = this.rows.at(-1);
|
||||
const adjacent = previous
|
||||
? mergeReasoningChunks(mergeAssistantChunks([previous, entry]))
|
||||
: [entry];
|
||||
if (previous && adjacent.length === 1) {
|
||||
const mergedText = adjacent[0];
|
||||
this.rows[this.rows.length - 1] = { ...mergedText, seq: mergedText.seqEnd };
|
||||
if (fold.kind === "adjacent") {
|
||||
this.rows[this.rows.length - 1] = fold.row;
|
||||
this.extendSpan(this.rows.length - 1);
|
||||
return this.rows.length - 1;
|
||||
}
|
||||
const entry = fold.row;
|
||||
if (entry.item.type === "provider_switch") {
|
||||
this.resetProviderSegment(entry.seqStart);
|
||||
}
|
||||
if (identity !== null) this.identities.set(identity, this.rows.length);
|
||||
this.rows.push({ ...entry, seq: entry.seqEnd });
|
||||
this.rows.push(entry);
|
||||
const last = this.spans.at(-1);
|
||||
if (last && last.endSeq >= entry.seqStart) {
|
||||
last.endSeq = Math.max(last.endSeq, entry.seqEnd);
|
||||
@@ -445,6 +515,25 @@ export class TimelineProjection {
|
||||
return this.retiredIdentities.has(identity);
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts a fresh provider segment at `markerSeq`. Tool-call live identities and retired keys from
|
||||
* the closed previous provider session are cleared so IDs in the new session cannot collide.
|
||||
*/
|
||||
private resetProviderSegment(markerSeq: number): void {
|
||||
this.activeSegmentStartSeq = markerSeq;
|
||||
for (const [identity, rowIndex] of this.identities) {
|
||||
if (this.rows[rowIndex]?.item.type === "tool_call") {
|
||||
this.identities.delete(identity);
|
||||
}
|
||||
}
|
||||
this.retiredIdentities.clear();
|
||||
this.retiredTurnIds.clear();
|
||||
}
|
||||
|
||||
getActiveSegmentStartSeq(): number {
|
||||
return this.activeSegmentStartSeq;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retires the active rows anchored at or after `retireFromSeq`. Rows are in anchor order, so they
|
||||
* form the display suffix. Their source seqs and the retirement's own seq stay covered.
|
||||
@@ -452,7 +541,9 @@ export class TimelineProjection {
|
||||
retire(retirement: TimelineRetirement): ProjectedTimelineRow[] {
|
||||
const cut = this.firstRowAnchoredAtOrAfter(retirement.retireFromSeq);
|
||||
const retired = this.rows.splice(cut);
|
||||
const activeTurnIds = new Set(this.rows.map((row) => row.turnId));
|
||||
const activeTurnIds = new Set(
|
||||
this.rows.filter((row) => row.seqStart > this.activeSegmentStartSeq).map((row) => row.turnId),
|
||||
);
|
||||
for (const row of retired) {
|
||||
if (row.item.type === "tool_call") {
|
||||
const identity = timelineItemIdentity(row.item);
|
||||
@@ -516,19 +607,9 @@ export class TimelineProjection {
|
||||
}
|
||||
|
||||
private coalesceRetirements(retirements: readonly TimelineRetirement[]): TimelineRetirement[] {
|
||||
const coalesced: TimelineRetirement[] = [];
|
||||
for (const retirement of retirements) {
|
||||
const previous = coalesced.at(-1);
|
||||
if (previous && !this.hasActiveAnchorIn(previous.seq, retirement.retireFromSeq)) {
|
||||
coalesced[coalesced.length - 1] = {
|
||||
seq: retirement.seq,
|
||||
retireFromSeq: Math.min(previous.retireFromSeq, retirement.retireFromSeq),
|
||||
};
|
||||
continue;
|
||||
}
|
||||
coalesced.push({ ...retirement });
|
||||
}
|
||||
return coalesced;
|
||||
return coalesceTimelineRetirements(retirements, (startSeq, endSeq) =>
|
||||
this.hasActiveAnchorIn(startSeq, endSeq),
|
||||
);
|
||||
}
|
||||
|
||||
private hasActiveAnchorIn(startSeq: number, endSeq: number): boolean {
|
||||
@@ -693,7 +774,7 @@ export class TimelineProjection {
|
||||
const start = input.wholeTurns ? this.wholeTurnWindowStart(requestedStart) : requestedStart;
|
||||
// Choose the window before extending the right edge, so a prompt jump
|
||||
// cannot lose its target when the next turn is arbitrarily large.
|
||||
if (input.wholeTurns) {
|
||||
if (input.wholeTurns && low > 0) {
|
||||
while (low < this.rows.length && continuesProjectedTurn(this.rows[low - 1], this.rows[low]))
|
||||
low++;
|
||||
}
|
||||
@@ -732,12 +813,19 @@ export class TimelineProjection {
|
||||
enrichSubmittedUserMessage(
|
||||
clientMessageId: string,
|
||||
providerMessageId: string,
|
||||
options?: { providerPromptText?: string },
|
||||
): ProjectedTimelineRow | null {
|
||||
const index = this.rows.findIndex(
|
||||
(row) => row.item.type === "user_message" && row.item.clientMessageId === clientMessageId,
|
||||
);
|
||||
if (index < 0) return null;
|
||||
this.rows[index] = { ...this.rows[index], providerMessageId };
|
||||
this.rows[index] = {
|
||||
...this.rows[index],
|
||||
providerMessageId,
|
||||
...(options?.providerPromptText !== undefined
|
||||
? { providerPromptText: options.providerPromptText }
|
||||
: {}),
|
||||
};
|
||||
return { ...this.rows[index] };
|
||||
}
|
||||
|
||||
@@ -768,11 +856,16 @@ export class TimelineProjection {
|
||||
const tail = this.rows.length - 1;
|
||||
if (tail < 0) return null;
|
||||
if (turnId === undefined) return tail;
|
||||
const index = this.rows.findLastIndex((row) => row.turnId === turnId);
|
||||
const index = this.rows.findLastIndex(
|
||||
(row) => row.seqStart > this.activeSegmentStartSeq && row.turnId === turnId,
|
||||
);
|
||||
if (index >= 0) return index;
|
||||
// Rows replayed from provider history carry no turn id, so the turn is the
|
||||
// trailing one. A tail owned by another turn means this turn wrote no rows.
|
||||
return this.rows[tail].turnId === undefined ? tail : null;
|
||||
return this.rows[tail].seqStart > this.activeSegmentStartSeq &&
|
||||
this.rows[tail].turnId === undefined
|
||||
? tail
|
||||
: null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -898,7 +991,7 @@ interface ProjectedEntryCandidate {
|
||||
firstSourceSeq: number;
|
||||
}
|
||||
|
||||
function selectProjectedEntriesAfter(input: {
|
||||
export function selectProjectedEntriesAfter(input: {
|
||||
entries: readonly TimelineProjectionEntry[];
|
||||
/** Seqs covered without an active row; they advance the cursor but add no entry. */
|
||||
covered?: readonly TimelineSeqRange[];
|
||||
@@ -940,7 +1033,7 @@ function selectProjectedEntriesAfter(input: {
|
||||
};
|
||||
}
|
||||
|
||||
function continuesProjectedTurn(
|
||||
export function continuesProjectedTurn(
|
||||
previous: TimelineProjectionEntry,
|
||||
next: TimelineProjectionEntry,
|
||||
): boolean {
|
||||
|
||||
@@ -64,6 +64,24 @@ describe.each(
|
||||
expect(published).toEqual([1, 2, 3]);
|
||||
});
|
||||
|
||||
it("keeps the provider that wrote each row, and a merged row the one it started with", async () => {
|
||||
const timeline = createTimeline();
|
||||
await timeline.create(root("a"), { epoch: "e" });
|
||||
await timeline.append(root("a"), [
|
||||
{ item: { type: "user_message", text: "prompt" }, provider: "codex" },
|
||||
{ item: { type: "assistant_message", text: "A" }, provider: "claude" },
|
||||
{ item: { type: "assistant_message", text: "B" }, provider: "claude" },
|
||||
{ item: { type: "user_message", text: "unattributed" } },
|
||||
]);
|
||||
|
||||
const page = await timeline.fetch(root("a"), { direction: "tail", limit: 0 });
|
||||
expect(page.rows.map((row) => [row.item.type, row.provider])).toEqual([
|
||||
["user_message", "codex"],
|
||||
["assistant_message", "claude"],
|
||||
["user_message", undefined],
|
||||
]);
|
||||
});
|
||||
|
||||
it("publishes each commit before the next operation starts", async () => {
|
||||
const timeline = createTimeline();
|
||||
await timeline.create(root("a"), { epoch: "e" });
|
||||
@@ -211,7 +229,9 @@ describe.each(
|
||||
seq: 1,
|
||||
size: 1,
|
||||
retirementCount: 0,
|
||||
activeSegmentStartSeq: 0,
|
||||
rewind: null,
|
||||
providerSwitch: null,
|
||||
});
|
||||
await expect(timeline.readRows(child)).rejects.toBeInstanceOf(UnknownTimelineError);
|
||||
});
|
||||
@@ -353,6 +373,27 @@ describe.each(TIMELINE_CONTRACT_BACKENDS)("history paging over a $name backend",
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("resets an after cursor ahead of the history, as after a restored database", async () => {
|
||||
const timeline = new AgentTimeline(create());
|
||||
await timeline.create(root("agent-1"), { epoch: "epoch-1", nextSeq: 8, rows: seededRows });
|
||||
|
||||
const result = await timeline.fetch(root("agent-1"), {
|
||||
direction: "after",
|
||||
cursor: { epoch: "epoch-1", seq: 20 },
|
||||
limit: 1,
|
||||
});
|
||||
|
||||
// Without the reset the client keeps its cursor and drops seqs 8 to 20 when they arrive.
|
||||
expect(result).toMatchObject({
|
||||
direction: "after",
|
||||
reset: true,
|
||||
staleCursor: false,
|
||||
gap: true,
|
||||
window: { minSeq: 5, maxSeq: 7, nextSeq: 8 },
|
||||
rows: [{ seq: 7 }],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("projected timeline retention", () => {
|
||||
@@ -615,7 +656,8 @@ async function assertSelectionMatchesReference(
|
||||
const expected = selectReferenceProjectedTimelinePage({
|
||||
rows,
|
||||
bounds: actual.window,
|
||||
direction,
|
||||
// A reset serves the tail, as `fetchTimelinePage` does.
|
||||
direction: actual.reset ? "tail" : direction,
|
||||
limit,
|
||||
cursorSeq,
|
||||
});
|
||||
@@ -769,7 +811,9 @@ describe.each(TIMELINE_CONTRACT_BACKENDS)(
|
||||
seq: 8,
|
||||
size: 4,
|
||||
retirementCount: 1,
|
||||
activeSegmentStartSeq: 0,
|
||||
rewind: null,
|
||||
providerSwitch: null,
|
||||
});
|
||||
const tail = await timeline.fetch(scope);
|
||||
expect(texts(tail.rows)).toEqual(["a", "A", "c", "C"]);
|
||||
|
||||
@@ -1,7 +1,14 @@
|
||||
import type { DaemonDatabase } from "../../database/index.js";
|
||||
import { AgentTimeline } from "./internal/agent-timeline.js";
|
||||
import { SqliteTimelineBackend } from "./internal/sqlite-backend.js";
|
||||
|
||||
export {
|
||||
AgentTimeline,
|
||||
TimelineClosedError,
|
||||
TimelineProviderSwitchPendingError,
|
||||
TimelineRewindBoundaryError,
|
||||
TimelineRewindPendingError,
|
||||
TimelineRewindSegmentBoundaryError,
|
||||
TimelineRewindTargetError,
|
||||
type TimelineAppendResult,
|
||||
type TimelineChild,
|
||||
@@ -9,7 +16,10 @@ export {
|
||||
type TimelineEntry,
|
||||
type TimelineHead,
|
||||
type TimelineImportResult,
|
||||
type TimelinePrompts,
|
||||
type TimelineIngestResult,
|
||||
type TimelineProviderSwitchCommit,
|
||||
type TimelineProviderSwitchIntent,
|
||||
type TimelineReconcileResult,
|
||||
type TimelineRetirement,
|
||||
type TimelineRetirementCommit,
|
||||
@@ -19,3 +29,9 @@ export {
|
||||
type TimelineScope,
|
||||
type TimelineSeed,
|
||||
} from "./internal/agent-timeline.js";
|
||||
export { timelineSchema } from "./internal/sqlite-backend.js";
|
||||
|
||||
/** The daemon's timeline, stored in the daemon database. Open the database with `timelineSchema`. */
|
||||
export function createStoredAgentTimeline(database: DaemonDatabase): AgentTimeline {
|
||||
return new AgentTimeline(new SqliteTimelineBackend(database));
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type {
|
||||
AgentMetric,
|
||||
AgentPersistenceHandle,
|
||||
AgentTimelineItem,
|
||||
ConversationRewindCut,
|
||||
} from "../../agent-sdk-types.js";
|
||||
@@ -18,6 +19,7 @@ import type {
|
||||
TimelineEntry,
|
||||
TimelineHead,
|
||||
TimelinePrompt,
|
||||
TimelineProviderSwitchIntent,
|
||||
TimelineRewindIntent,
|
||||
TimelineScope,
|
||||
TimelineSeed,
|
||||
@@ -30,12 +32,18 @@ export type {
|
||||
TimelineChild,
|
||||
TimelineEntry,
|
||||
TimelineHead,
|
||||
TimelineProviderSwitchIntent,
|
||||
TimelineRewindIntent,
|
||||
TimelineScope,
|
||||
TimelineSeed,
|
||||
} from "./backend.js";
|
||||
export type { TimelineRetirement } from "../../timeline-projection.js";
|
||||
|
||||
export interface TimelinePrompts {
|
||||
head: TimelineHead;
|
||||
rows: ProjectedTimelineRow[];
|
||||
}
|
||||
|
||||
export interface TimelineCommit {
|
||||
row: AgentTimelineRow;
|
||||
epoch: string;
|
||||
@@ -60,6 +68,13 @@ export type TimelineRewindCompletion =
|
||||
/** No rewind with this id is open: it completed or was abandoned. Nothing changed. */
|
||||
| { kind: "absent" };
|
||||
|
||||
export type TimelineProviderSwitchCommit =
|
||||
| ({ kind: "committed"; activeSegmentStartSeq: number } & TimelineCommit)
|
||||
/** Committed, but `publish` threw; see `TimelineIngestResult`. */
|
||||
| ({ kind: "unpublished"; activeSegmentStartSeq: number; error: unknown } & TimelineCommit)
|
||||
/** No switch with this id is open: it completed or was abandoned. Nothing changed. */
|
||||
| { kind: "absent" };
|
||||
|
||||
/**
|
||||
* What the provider's own history says about an open rewind, judged against the active prompts.
|
||||
* `unknown` carries the reason the evidence does not decide it.
|
||||
@@ -72,6 +87,14 @@ export type TimelineRewindVerdict =
|
||||
| { kind: "absent" };
|
||||
|
||||
/** Another rewind is open on the history; it must settle first. */
|
||||
/** The timeline was closed for shutdown; it takes no more operations. */
|
||||
export class TimelineClosedError extends Error {
|
||||
constructor() {
|
||||
super("The agent timeline is closed");
|
||||
this.name = "TimelineClosedError";
|
||||
}
|
||||
}
|
||||
|
||||
export class TimelineRewindPendingError extends Error {
|
||||
constructor(readonly intent: TimelineRewindIntent) {
|
||||
super("Another rewind of this conversation has not settled");
|
||||
@@ -79,6 +102,13 @@ export class TimelineRewindPendingError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export class TimelineProviderSwitchPendingError extends Error {
|
||||
constructor(readonly intent: TimelineProviderSwitchIntent) {
|
||||
super("Another provider switch of this conversation has not settled");
|
||||
this.name = "TimelineProviderSwitchPendingError";
|
||||
}
|
||||
}
|
||||
|
||||
/** The rewind target is not an active prompt: it never existed or a rewind already retired it. */
|
||||
export class TimelineRewindTargetError extends Error {
|
||||
constructor(readonly messageId: string) {
|
||||
@@ -87,6 +117,14 @@ export class TimelineRewindTargetError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
/** The rewind target belongs to a provider segment before the latest provider switch. */
|
||||
export class TimelineRewindSegmentBoundaryError extends Error {
|
||||
constructor(readonly messageId: string) {
|
||||
super("Cannot rewind to a message from a previous provider segment");
|
||||
this.name = "TimelineRewindSegmentBoundaryError";
|
||||
}
|
||||
}
|
||||
|
||||
/** The provider's cut does not resolve to a prompt at or before the target. */
|
||||
export class TimelineRewindBoundaryError extends Error {
|
||||
constructor(readonly intent: TimelineRewindIntent) {
|
||||
@@ -127,7 +165,9 @@ export type TimelineReconcileResult =
|
||||
/** The provider's history disagrees with the owned history, which is kept unchanged. */
|
||||
| { kind: "diverged"; reason: string }
|
||||
/** A rewind is open; it settles first. Nothing changed. */
|
||||
| { kind: "rewind_open" };
|
||||
| { kind: "rewind_open" }
|
||||
/** A provider switch is open; it settles first. Nothing changed. */
|
||||
| { kind: "provider_switch_open" };
|
||||
|
||||
export interface TimelineIngestOptions {
|
||||
/**
|
||||
@@ -143,6 +183,14 @@ export interface TimelineAppendOptions {
|
||||
publish?: (commits: TimelineCommit[]) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a new history lives. `inMemory` keeps an agent's history, its children included, in
|
||||
* process memory only, for agents that must leave nothing on disk; it ends with the process.
|
||||
*/
|
||||
export interface TimelineRetention {
|
||||
inMemory?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Owner of agent timeline history: item identity, sequence numbers, projection, and reads.
|
||||
*
|
||||
@@ -153,23 +201,37 @@ export interface TimelineAppendOptions {
|
||||
export class AgentTimeline {
|
||||
private readonly tails = new Map<string, Promise<void>>();
|
||||
private readonly sizes = new Map<string, number>();
|
||||
private closed = false;
|
||||
|
||||
constructor(private readonly backend: AgentTimelineBackend = new MemoryTimelineBackend()) {}
|
||||
/** Agents whose history lives only in `memory`; see `TimelineRetention`. */
|
||||
private readonly memoryAgents = new Set<string>();
|
||||
|
||||
constructor(
|
||||
private readonly backend: AgentTimelineBackend = new MemoryTimelineBackend(),
|
||||
private readonly memory: AgentTimelineBackend = new MemoryTimelineBackend(),
|
||||
) {}
|
||||
|
||||
describe(scope: TimelineScope): Promise<TimelineHead | null> {
|
||||
return this.run(scope, () => this.backend.head(scope));
|
||||
return this.run(scope, () => this.backendFor(scope).head(scope));
|
||||
}
|
||||
|
||||
/** Creates the scope's history with a new identity, replacing any existing history. */
|
||||
create(scope: TimelineScope, seed: TimelineSeed = {}): Promise<TimelineHead> {
|
||||
return this.run(scope, async () => this.track(scope, await this.backend.create(scope, seed)));
|
||||
create(
|
||||
scope: TimelineScope,
|
||||
seed: TimelineSeed = {},
|
||||
options: TimelineRetention = {},
|
||||
): Promise<TimelineHead> {
|
||||
return this.run(scope, async () => {
|
||||
this.retain(scope, options);
|
||||
return this.track(scope, await this.backendFor(scope).create(scope, seed));
|
||||
});
|
||||
}
|
||||
|
||||
/** Returns the existing history, or creates an empty one. */
|
||||
open(scope: TimelineScope): Promise<TimelineHead> {
|
||||
return this.run(scope, async () => {
|
||||
const existing = await this.backend.head(scope);
|
||||
return existing ?? this.track(scope, await this.backend.create(scope, {}));
|
||||
const existing = await this.backendFor(scope).head(scope);
|
||||
return existing ?? this.track(scope, await this.backendFor(scope).create(scope, {}));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -180,12 +242,13 @@ export class AgentTimeline {
|
||||
importHistory(
|
||||
scope: TimelineScope,
|
||||
entries: readonly TimelineEntry[],
|
||||
options: { timestamp?: string } = {},
|
||||
options: { timestamp?: string } & TimelineRetention = {},
|
||||
): Promise<TimelineImportResult> {
|
||||
return this.run(scope, async () => {
|
||||
const existing = await this.backend.head(scope);
|
||||
this.retain(scope, options);
|
||||
const existing = await this.backendFor(scope).head(scope);
|
||||
if (existing) return { kind: "present", head: existing };
|
||||
const head = await this.backend.create(scope, {
|
||||
const head = await this.backendFor(scope).create(scope, {
|
||||
entries: entries.map(providerHistoryEntry),
|
||||
timestamp: options.timestamp,
|
||||
});
|
||||
@@ -206,10 +269,12 @@ export class AgentTimeline {
|
||||
return this.run(scope, async () => {
|
||||
const head = await this.requireHead(scope);
|
||||
if (head.rewind) return { kind: "rewind_open" };
|
||||
if (head.providerSwitch) return { kind: "provider_switch_open" };
|
||||
const plan = planProviderHistory({
|
||||
rows: await this.backend.readRows(scope),
|
||||
prompts: await this.backend.prompts(scope),
|
||||
rows: await this.backendFor(scope).readRows(scope),
|
||||
prompts: await this.prompts(scope),
|
||||
provider: entries.map(providerHistoryEntry),
|
||||
activeSegmentStartSeq: head.activeSegmentStartSeq,
|
||||
});
|
||||
if (plan.kind !== "append") return plan;
|
||||
const commits = await this.commit(scope, plan.entries);
|
||||
@@ -222,7 +287,7 @@ export class AgentTimeline {
|
||||
|
||||
/** The agent's provider children, retired ones included. */
|
||||
listChildren(agentId: string): Promise<TimelineChild[]> {
|
||||
return this.run({ agentId }, () => this.backend.children(agentId));
|
||||
return this.run({ agentId }, () => this.backendFor({ agentId }).children(agentId));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -234,10 +299,10 @@ export class AgentTimeline {
|
||||
update: (previous: ProviderSubagentDescriptor | null) => ProviderSubagentDescriptor,
|
||||
): Promise<ProviderSubagentDescriptor | null> {
|
||||
return this.run(scope, async () => {
|
||||
const child = await this.backend.child(scope);
|
||||
const child = await this.backendFor(scope).child(scope);
|
||||
if (child?.retired) return null;
|
||||
const descriptor = update(child?.descriptor ?? null);
|
||||
await this.backend.setChild(scope, descriptor);
|
||||
await this.backendFor(scope).setChild(scope, descriptor);
|
||||
return descriptor;
|
||||
});
|
||||
}
|
||||
@@ -248,9 +313,9 @@ export class AgentTimeline {
|
||||
entries: readonly TimelineEntry[],
|
||||
): Promise<TimelineCommit[] | null> {
|
||||
return this.run(scope, async () => {
|
||||
const child = await this.backend.child(scope);
|
||||
const child = await this.backendFor(scope).child(scope);
|
||||
if (child?.retired) return null;
|
||||
if (!child) this.track(scope, await this.backend.create(scope, {}));
|
||||
if (!child) this.track(scope, await this.backendFor(scope).create(scope, {}));
|
||||
return entries.length === 0 ? [] : await this.commit(scope, entries);
|
||||
});
|
||||
}
|
||||
@@ -258,9 +323,9 @@ export class AgentTimeline {
|
||||
/** Deletes a child's history. A retired child stays stored and resolves false. */
|
||||
removeChild(scope: TimelineScope): Promise<boolean> {
|
||||
return this.run(scope, async () => {
|
||||
const child = await this.backend.child(scope);
|
||||
const child = await this.backendFor(scope).child(scope);
|
||||
if (child?.retired) return false;
|
||||
await this.backend.delete(scope);
|
||||
await this.backendFor(scope).delete(scope);
|
||||
this.sizes.delete(sizeKey(scope));
|
||||
return true;
|
||||
});
|
||||
@@ -269,9 +334,10 @@ export class AgentTimeline {
|
||||
/** Deleting an agent's root history deletes all of its children's too. */
|
||||
delete(scope: TimelineScope): Promise<void> {
|
||||
return this.run(scope, async () => {
|
||||
await this.backend.delete(scope);
|
||||
await this.backendFor(scope).delete(scope);
|
||||
this.sizes.delete(sizeKey(scope));
|
||||
if (scope.subagentId !== undefined) return;
|
||||
this.memoryAgents.delete(scope.agentId);
|
||||
const childPrefix = sizeKey({ agentId: scope.agentId, subagentId: "" });
|
||||
for (const key of this.sizes.keys()) {
|
||||
if (key.startsWith(childPrefix)) this.sizes.delete(key);
|
||||
@@ -287,7 +353,7 @@ export class AgentTimeline {
|
||||
return this.run(scope, async () => {
|
||||
const clientMessageId = submittedPromptId(entry.item);
|
||||
if (clientMessageId) {
|
||||
const existing = await this.backend.findSubmittedPrompt(scope, clientMessageId);
|
||||
const existing = await this.backendFor(scope).findSubmittedPrompt(scope, clientMessageId);
|
||||
if (existing) {
|
||||
const head = await this.requireHead(scope);
|
||||
return {
|
||||
@@ -298,7 +364,7 @@ export class AgentTimeline {
|
||||
};
|
||||
}
|
||||
}
|
||||
if (await this.backend.isRetired(scope, entry)) return { kind: "dropped" };
|
||||
if (await this.backendFor(scope).isRetired(scope, entry)) return { kind: "dropped" };
|
||||
const [commit] = await this.commit(scope, [entry]);
|
||||
const failure = publishCommitted(options?.publish, commit);
|
||||
return failure
|
||||
@@ -327,9 +393,15 @@ export class AgentTimeline {
|
||||
scope: TimelineScope,
|
||||
clientMessageId: string,
|
||||
providerMessageId: string,
|
||||
options?: { providerPromptText?: string },
|
||||
): Promise<AgentTimelineRow | null> {
|
||||
return this.run(scope, () =>
|
||||
this.backend.attachProviderMessageId(scope, clientMessageId, providerMessageId),
|
||||
this.backendFor(scope).attachProviderMessageId(
|
||||
scope,
|
||||
clientMessageId,
|
||||
providerMessageId,
|
||||
options,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -339,29 +411,39 @@ export class AgentTimeline {
|
||||
metrics: AgentMetric[],
|
||||
options?: { turnId?: string },
|
||||
): Promise<ProjectedTimelineRow | null> {
|
||||
return this.run(scope, () => this.backend.stampTurnMetrics(scope, metrics, options));
|
||||
return this.run(scope, () => this.backendFor(scope).stampTurnMetrics(scope, metrics, options));
|
||||
}
|
||||
|
||||
findSubmittedPrompt(
|
||||
scope: TimelineScope,
|
||||
clientMessageId: string,
|
||||
): Promise<AgentTimelineRow | null> {
|
||||
return this.run(scope, () => this.backend.findSubmittedPrompt(scope, clientMessageId));
|
||||
return this.run(scope, () =>
|
||||
this.backendFor(scope).findSubmittedPrompt(scope, clientMessageId),
|
||||
);
|
||||
}
|
||||
|
||||
fetch(
|
||||
scope: TimelineScope,
|
||||
options: AgentTimelineFetchOptions = {},
|
||||
): Promise<AgentTimelineFetchResult> {
|
||||
return this.run(scope, () => this.backend.fetch(scope, options));
|
||||
return this.run(scope, () => this.backendFor(scope).fetch(scope, options));
|
||||
}
|
||||
|
||||
readRows(scope: TimelineScope): Promise<ProjectedTimelineRow[]> {
|
||||
return this.run(scope, () => this.backend.readRows(scope));
|
||||
return this.run(scope, () => this.backendFor(scope).readRows(scope));
|
||||
}
|
||||
|
||||
/** The active user prompt rows and the head they belong to, without replies or tool output. */
|
||||
readPrompts(scope: TimelineScope): Promise<TimelinePrompts> {
|
||||
return this.run(scope, async () => ({
|
||||
head: await this.requireHead(scope),
|
||||
rows: await this.backendFor(scope).promptRows(scope),
|
||||
}));
|
||||
}
|
||||
|
||||
lastItem(scope: TimelineScope): Promise<AgentTimelineItem | null> {
|
||||
return this.run(scope, () => this.backend.lastItem(scope));
|
||||
return this.run(scope, () => this.backendFor(scope).lastItem(scope));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -370,7 +452,98 @@ export class AgentTimeline {
|
||||
* before it ends the run. Null when the history has no assistant message.
|
||||
*/
|
||||
lastAssistantMessage(scope: TimelineScope): Promise<string | null> {
|
||||
return this.run(scope, () => this.backend.lastAssistantMessage(scope));
|
||||
return this.run(scope, () => this.backendFor(scope).lastAssistantMessage(scope));
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens a durable provider-switch intent. Refused while a rewind or another switch is open.
|
||||
*/
|
||||
beginProviderSwitch(
|
||||
scope: TimelineScope,
|
||||
input: Omit<TimelineProviderSwitchIntent, "id" | "phase" | "markerSeq">,
|
||||
): Promise<TimelineProviderSwitchIntent> {
|
||||
return this.run(scope, async () => {
|
||||
const head = await this.requireHead(scope);
|
||||
if (head.rewind) throw new TimelineRewindPendingError(head.rewind);
|
||||
if (head.providerSwitch) throw new TimelineProviderSwitchPendingError(head.providerSwitch);
|
||||
const intent: TimelineProviderSwitchIntent = {
|
||||
...input,
|
||||
id: randomUUID(),
|
||||
phase: "preparing",
|
||||
};
|
||||
await this.backendFor(scope).setProviderSwitch(scope, intent);
|
||||
return intent;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomically appends the `provider_switch` marker, advances `activeSegmentStartSeq`, clears
|
||||
* live tool-call identities and retired keys, and moves the intent to `marker_committed`.
|
||||
*/
|
||||
commitProviderSwitch(
|
||||
scope: TimelineScope,
|
||||
intentId: string,
|
||||
options: {
|
||||
markerEntry: TimelineEntry;
|
||||
targetPersistence?: AgentPersistenceHandle | null;
|
||||
publish?: (commit: TimelineCommit) => void;
|
||||
},
|
||||
): Promise<TimelineProviderSwitchCommit> {
|
||||
return this.run(scope, async () => {
|
||||
const head = await this.requireHead(scope);
|
||||
const intent = head.providerSwitch;
|
||||
if (intent?.id !== intentId) return { kind: "absent" };
|
||||
const nextIntent: TimelineProviderSwitchIntent = {
|
||||
...intent,
|
||||
phase: "marker_committed",
|
||||
...(options.targetPersistence !== undefined
|
||||
? { targetPersistence: options.targetPersistence }
|
||||
: {}),
|
||||
};
|
||||
const result = await this.backendFor(scope).commitProviderSwitch(scope, {
|
||||
markerEntry: boundEntry(options.markerEntry),
|
||||
nextIntent,
|
||||
});
|
||||
this.track(scope, result.head);
|
||||
const commit: TimelineCommit = {
|
||||
row: result.row,
|
||||
epoch: result.head.epoch,
|
||||
retirementCount: result.head.retirementCount,
|
||||
};
|
||||
const failure = publishCommitted(options.publish, commit);
|
||||
return failure
|
||||
? {
|
||||
kind: "unpublished",
|
||||
error: failure.error,
|
||||
activeSegmentStartSeq: result.head.activeSegmentStartSeq,
|
||||
...commit,
|
||||
}
|
||||
: {
|
||||
kind: "committed",
|
||||
activeSegmentStartSeq: result.head.activeSegmentStartSeq,
|
||||
...commit,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/** Closes a committed provider switch once `StoredAgentRecord` has been updated. */
|
||||
completeProviderSwitch(scope: TimelineScope, intentId: string): Promise<void> {
|
||||
return this.run(scope, async () => {
|
||||
const head = await this.requireHead(scope);
|
||||
if (head.providerSwitch?.id === intentId) {
|
||||
await this.backendFor(scope).setProviderSwitch(scope, null);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** Closes an uncommitted (`preparing`) provider switch. History is unchanged. */
|
||||
abandonProviderSwitch(scope: TimelineScope, intentId: string): Promise<void> {
|
||||
return this.run(scope, async () => {
|
||||
const head = await this.requireHead(scope);
|
||||
if (head.providerSwitch?.id === intentId && head.providerSwitch.phase === "preparing") {
|
||||
await this.backendFor(scope).setProviderSwitch(scope, null);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -381,16 +554,18 @@ export class AgentTimeline {
|
||||
return this.run(scope, async () => {
|
||||
const head = await this.requireHead(scope);
|
||||
if (head.rewind) throw new TimelineRewindPendingError(head.rewind);
|
||||
const target = (await this.backend.prompts(scope)).find(
|
||||
(prompt) => prompt.messageId === messageId,
|
||||
);
|
||||
if (head.providerSwitch) throw new TimelineProviderSwitchPendingError(head.providerSwitch);
|
||||
const target = (await this.prompts(scope)).find((prompt) => prompt.messageId === messageId);
|
||||
if (!target) throw new TimelineRewindTargetError(messageId);
|
||||
if (target.seqStart <= head.activeSegmentStartSeq) {
|
||||
throw new TimelineRewindSegmentBoundaryError(messageId);
|
||||
}
|
||||
const intent: TimelineRewindIntent = {
|
||||
id: randomUUID(),
|
||||
messageId,
|
||||
targetSeq: target.seqStart,
|
||||
};
|
||||
await this.backend.setRewind(scope, intent);
|
||||
await this.backendFor(scope).setRewind(scope, intent);
|
||||
return intent;
|
||||
});
|
||||
}
|
||||
@@ -405,7 +580,7 @@ export class AgentTimeline {
|
||||
const head = await this.requireHead(scope);
|
||||
if (head.rewind?.id !== intentId) return null;
|
||||
const intent = { ...head.rewind, cut };
|
||||
await this.backend.setRewind(scope, intent);
|
||||
await this.backendFor(scope).setRewind(scope, intent);
|
||||
return intent;
|
||||
});
|
||||
}
|
||||
@@ -414,7 +589,7 @@ export class AgentTimeline {
|
||||
abandonRewind(scope: TimelineScope, intentId: string): Promise<void> {
|
||||
return this.run(scope, async () => {
|
||||
const head = await this.requireHead(scope);
|
||||
if (head.rewind?.id === intentId) await this.backend.setRewind(scope, null);
|
||||
if (head.rewind?.id === intentId) await this.backendFor(scope).setRewind(scope, null);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -428,9 +603,14 @@ export class AgentTimeline {
|
||||
providerPromptIds: readonly string[],
|
||||
): Promise<TimelineRewindVerdict> {
|
||||
return this.run(scope, async () => {
|
||||
const intent = (await this.requireHead(scope)).rewind;
|
||||
const head = await this.requireHead(scope);
|
||||
const intent = head.rewind;
|
||||
if (intent?.id !== intentId) return { kind: "absent" };
|
||||
return judgeRewindEvidence(intent, await this.backend.prompts(scope), providerPromptIds);
|
||||
const segmentPrompts = activeSegmentPrompts(
|
||||
await this.prompts(scope),
|
||||
head.activeSegmentStartSeq,
|
||||
);
|
||||
return judgeRewindEvidence(intent, segmentPrompts, providerPromptIds);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -448,9 +628,15 @@ export class AgentTimeline {
|
||||
const intent = head.rewind;
|
||||
if (intent?.id !== intentId) return { kind: "absent" };
|
||||
if (!intent.cut) throw new Error("Cannot complete a rewind before its provider outcome");
|
||||
const retireFromSeq = resolveRetireFromSeq(intent, await this.backend.prompts(scope));
|
||||
if (retireFromSeq === null) throw new TimelineRewindBoundaryError(intent);
|
||||
const result = await this.backend.retire(scope, {
|
||||
const segmentPrompts = activeSegmentPrompts(
|
||||
await this.prompts(scope),
|
||||
head.activeSegmentStartSeq,
|
||||
);
|
||||
const retireFromSeq = resolveRetireFromSeq(intent, segmentPrompts);
|
||||
if (retireFromSeq === null || retireFromSeq <= head.activeSegmentStartSeq) {
|
||||
throw new TimelineRewindBoundaryError(intent);
|
||||
}
|
||||
const result = await this.backendFor(scope).retire(scope, {
|
||||
retireFromSeq,
|
||||
selectChildren: childrenSpawnedBy,
|
||||
});
|
||||
@@ -474,9 +660,20 @@ export class AgentTimeline {
|
||||
* Callers use it so an event published outside the timeline cannot overtake queued writes.
|
||||
*/
|
||||
settled(scope: TimelineScope): Promise<void> {
|
||||
// A closed timeline takes no operations, so the ones already queued are all there is.
|
||||
if (this.closed) return this.tails.get(scope.agentId) ?? Promise.resolve();
|
||||
return this.run(scope, settledOperation);
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses new operations with `TimelineClosedError` and resolves once every operation called
|
||||
* before it has finished. The daemon calls it before closing the store.
|
||||
*/
|
||||
async close(): Promise<void> {
|
||||
this.closed = true;
|
||||
await Promise.all(this.tails.values());
|
||||
}
|
||||
|
||||
/** Projected row count as of the last committed write, for diagnostics. */
|
||||
residentSize(scope: TimelineScope): number | null {
|
||||
return this.sizes.get(sizeKey(scope)) ?? null;
|
||||
@@ -486,7 +683,7 @@ export class AgentTimeline {
|
||||
scope: TimelineScope,
|
||||
entries: readonly TimelineEntry[],
|
||||
): Promise<TimelineCommit[]> {
|
||||
const { rows, head } = await this.backend.append(scope, entries.map(boundEntry));
|
||||
const { rows, head } = await this.backendFor(scope).append(scope, entries.map(boundEntry));
|
||||
this.track(scope, head);
|
||||
return rows.map((row) => ({
|
||||
row,
|
||||
@@ -496,17 +693,31 @@ export class AgentTimeline {
|
||||
}
|
||||
|
||||
private async requireHead(scope: TimelineScope): Promise<TimelineHead> {
|
||||
const head = await this.backend.head(scope);
|
||||
const head = await this.backendFor(scope).head(scope);
|
||||
if (!head) throw new UnknownTimelineError(scope);
|
||||
return head;
|
||||
}
|
||||
|
||||
private backendFor(scope: TimelineScope): AgentTimelineBackend {
|
||||
return this.memoryAgents.has(scope.agentId) ? this.memory : this.backend;
|
||||
}
|
||||
|
||||
private async prompts(scope: TimelineScope): Promise<TimelinePrompt[]> {
|
||||
return (await this.backendFor(scope).promptRows(scope)).map(toTimelinePrompt);
|
||||
}
|
||||
|
||||
/** An agent stays in memory until its history is deleted. */
|
||||
private retain(scope: TimelineScope, options: TimelineRetention): void {
|
||||
if (options.inMemory && scope.subagentId === undefined) this.memoryAgents.add(scope.agentId);
|
||||
}
|
||||
|
||||
private track(scope: TimelineScope, head: TimelineHead): TimelineHead {
|
||||
this.sizes.set(sizeKey(scope), head.size);
|
||||
return head;
|
||||
}
|
||||
|
||||
private run<T>(scope: TimelineScope, operation: () => T | Promise<T>): Promise<T> {
|
||||
if (this.closed) return Promise.reject(new TimelineClosedError());
|
||||
const key = scope.agentId;
|
||||
const previous = this.tails.get(key) ?? Promise.resolve();
|
||||
const result = previous.then(operation);
|
||||
@@ -607,20 +818,41 @@ function judgeRewindEvidence(
|
||||
};
|
||||
}
|
||||
|
||||
/** The active prompts belonging to the current provider segment. */
|
||||
function activeSegmentPrompts(
|
||||
prompts: readonly TimelinePrompt[],
|
||||
activeSegmentStartSeq: number,
|
||||
): TimelinePrompt[] {
|
||||
return activeSegmentStartSeq > 0
|
||||
? prompts.filter((prompt) => prompt.seqStart > activeSegmentStartSeq)
|
||||
: [...prompts];
|
||||
}
|
||||
|
||||
/** The listed children that retired tool calls spawned, and their descendants. */
|
||||
function childrenSpawnedBy(
|
||||
retiredRows: readonly ProjectedTimelineRow[],
|
||||
children: readonly TimelineChild[],
|
||||
): string[] {
|
||||
const toolCallIds = new Set(
|
||||
retiredRows.flatMap((row) => (row.item.type === "tool_call" ? [row.item.callId] : [])),
|
||||
);
|
||||
const retiredToolCalls: Array<{ callId: string; provider: string | undefined }> = [];
|
||||
for (const row of retiredRows) {
|
||||
if (row.item.type === "tool_call") {
|
||||
retiredToolCalls.push({ callId: row.item.callId, provider: row.provider });
|
||||
}
|
||||
}
|
||||
const listed = children.flatMap((child) =>
|
||||
!child.retired && child.descriptor ? [child.descriptor] : [],
|
||||
);
|
||||
const retired = new Set(
|
||||
listed
|
||||
.filter((child) => child.toolCallId !== null && toolCallIds.has(child.toolCallId))
|
||||
.filter(
|
||||
(child) =>
|
||||
child.toolCallId !== null &&
|
||||
retiredToolCalls.some(
|
||||
(call) =>
|
||||
call.callId === child.toolCallId &&
|
||||
(call.provider === undefined || call.provider === child.provider),
|
||||
),
|
||||
)
|
||||
.map((child) => child.id),
|
||||
);
|
||||
let grew = retired.size > 0;
|
||||
@@ -643,3 +875,13 @@ function sizeKey(scope: TimelineScope): string {
|
||||
function submittedPromptId(item: AgentTimelineItem): string | null {
|
||||
return item.type === "user_message" && item.clientMessageId ? item.clientMessageId : null;
|
||||
}
|
||||
|
||||
function toTimelinePrompt(row: ProjectedTimelineRow): TimelinePrompt {
|
||||
const item = row.item as Extract<AgentTimelineItem, { type: "user_message" }>;
|
||||
return {
|
||||
seqStart: row.seqStart,
|
||||
messageId: item.messageId,
|
||||
providerMessageId: row.providerMessageId,
|
||||
submitted: item.clientMessageId !== undefined,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
import type {
|
||||
AgentMetric,
|
||||
AgentPersistenceHandle,
|
||||
AgentProvider,
|
||||
AgentTimelineItem,
|
||||
ConversationRewindCut,
|
||||
ProviderSwitchContextSummary,
|
||||
} from "../../agent-sdk-types.js";
|
||||
import type { SerializableAgentConfig } from "../../agent-storage.js";
|
||||
import type {
|
||||
AgentTimelineFetchOptions,
|
||||
AgentTimelineFetchResult,
|
||||
@@ -19,9 +23,13 @@ export interface TimelineScope {
|
||||
|
||||
export interface TimelineEntry {
|
||||
item: AgentTimelineItem;
|
||||
/** The provider that wrote the entry. */
|
||||
provider?: AgentProvider;
|
||||
timestamp?: string;
|
||||
turnId?: string;
|
||||
providerMessageId?: string;
|
||||
providerPromptText?: string;
|
||||
rejected?: boolean;
|
||||
turnMetrics?: AgentMetric[];
|
||||
}
|
||||
|
||||
@@ -42,8 +50,33 @@ export interface TimelineHead {
|
||||
size: number;
|
||||
/** Rewinds applied since the history was created. */
|
||||
retirementCount: number;
|
||||
/** Seq of the latest active provider_switch marker, or 0 if never switched. */
|
||||
activeSegmentStartSeq: number;
|
||||
/** The rewind in progress, or one whose provider outcome is not settled yet. */
|
||||
rewind: TimelineRewindIntent | null;
|
||||
/** The provider switch in progress, or one whose record update is not settled yet. */
|
||||
providerSwitch: TimelineProviderSwitchIntent | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A provider switch between its preparation start and final settlement.
|
||||
* - `preparing`: target session is being swapped in; no marker is committed yet.
|
||||
* - `marker_committed`: the `provider_switch` marker is committed in SQLite and `StoredAgentRecord`
|
||||
* must reflect the target provider/config/persistence before the intent closes.
|
||||
*/
|
||||
export interface TimelineProviderSwitchIntent {
|
||||
id: string;
|
||||
/** The clientMessageId of the prompt that triggered this switch. */
|
||||
messageId: string;
|
||||
fromProvider: AgentProvider;
|
||||
fromPersistence: AgentPersistenceHandle | null;
|
||||
fromModel?: string | null;
|
||||
toProvider: AgentProvider;
|
||||
toConfig: SerializableAgentConfig;
|
||||
targetPersistence?: AgentPersistenceHandle | null;
|
||||
context: ProviderSwitchContextSummary;
|
||||
phase: "preparing" | "marker_committed";
|
||||
markerSeq?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -61,6 +94,7 @@ export interface TimelineRewindIntent {
|
||||
}
|
||||
|
||||
/** An active user prompt: what a rewind addresses. */
|
||||
/** What the timeline knows about an active prompt row; see `toTimelinePrompt`. */
|
||||
export interface TimelinePrompt {
|
||||
seqStart: number;
|
||||
messageId: string | undefined;
|
||||
@@ -99,6 +133,11 @@ export interface TimelineBackendRetireResult {
|
||||
head: TimelineHead;
|
||||
}
|
||||
|
||||
export interface TimelineBackendCommitProviderSwitchResult {
|
||||
row: AgentTimelineRow;
|
||||
head: TimelineHead;
|
||||
}
|
||||
|
||||
export type MaybePromise<T> = T | Promise<T>;
|
||||
|
||||
/**
|
||||
@@ -119,9 +158,24 @@ export interface AgentTimelineBackend {
|
||||
): MaybePromise<TimelineBackendAppendResult>;
|
||||
/** Whether a new entry would land on retired history (see `TimelineProjection.isRetired`). */
|
||||
isRetired(scope: TimelineScope, entry: TimelineEntry): MaybePromise<boolean>;
|
||||
/** Active user prompts in display order. */
|
||||
prompts(scope: TimelineScope): MaybePromise<TimelinePrompt[]>;
|
||||
/** Active user prompt rows in display order, read without the rest of the history. */
|
||||
promptRows(scope: TimelineScope): MaybePromise<ProjectedTimelineRow[]>;
|
||||
setRewind(scope: TimelineScope, rewind: TimelineRewindIntent | null): MaybePromise<TimelineHead>;
|
||||
setProviderSwitch(
|
||||
scope: TimelineScope,
|
||||
providerSwitch: TimelineProviderSwitchIntent | null,
|
||||
): MaybePromise<TimelineHead>;
|
||||
/**
|
||||
* Atomically appends the `provider_switch` marker, advances `activeSegmentStartSeq`, clears
|
||||
* live tool-call identities and retired keys for the scope, and updates the switch intent.
|
||||
*/
|
||||
commitProviderSwitch(
|
||||
scope: TimelineScope,
|
||||
input: {
|
||||
markerEntry: TimelineEntry;
|
||||
nextIntent: TimelineProviderSwitchIntent | null;
|
||||
},
|
||||
): MaybePromise<TimelineBackendCommitProviderSwitchResult>;
|
||||
/**
|
||||
* Allocates the next sequence number for a retirement of the active rows anchored at or after
|
||||
* `retireFromSeq`, marks the children `selectChildren` picks retired, and clears the rewind
|
||||
@@ -141,6 +195,7 @@ export interface AgentTimelineBackend {
|
||||
scope: TimelineScope,
|
||||
clientMessageId: string,
|
||||
providerMessageId: string,
|
||||
options?: { providerPromptText?: string },
|
||||
): MaybePromise<AgentTimelineRow | null>;
|
||||
/** Records a completed turn's metrics on its footer row. Null when the turn has none. */
|
||||
stampTurnMetrics(
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import { limitAgentTimelineItemContent } from "../../agent-timeline-content.js";
|
||||
import type {
|
||||
AgentTimelineFetchOptions,
|
||||
AgentTimelineFetchResult,
|
||||
} from "../../agent-timeline-store-types.js";
|
||||
import type {
|
||||
ProjectedTimelinePageOptions,
|
||||
ProjectedTimelinePageSelection,
|
||||
} from "../../timeline-projection.js";
|
||||
|
||||
const DEFAULT_TIMELINE_FETCH_LIMIT = 200;
|
||||
|
||||
export interface TimelinePageHistory {
|
||||
epoch: string;
|
||||
/** 0 before any commit. */
|
||||
minSeq: number;
|
||||
nextSeq: number;
|
||||
retirementCount: number;
|
||||
activeSegmentStartSeq: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* The fetch contract every backend shares: cursor validation, gap and stale-cursor resets, and the
|
||||
* served item budget. `selectPage` is the backend's projected page selection.
|
||||
*/
|
||||
export function fetchTimelinePage(input: {
|
||||
history: TimelinePageHistory;
|
||||
options: AgentTimelineFetchOptions;
|
||||
selectPage: (options: ProjectedTimelinePageOptions) => ProjectedTimelinePageSelection;
|
||||
}): AgentTimelineFetchResult {
|
||||
const { history, options } = input;
|
||||
const direction = options.direction ?? "tail";
|
||||
const cursor = options.cursor;
|
||||
const hasRows = history.minSeq !== 0;
|
||||
const window = {
|
||||
minSeq: history.minSeq,
|
||||
maxSeq: history.nextSeq - 1,
|
||||
nextSeq: history.nextSeq,
|
||||
};
|
||||
const staleCursor =
|
||||
cursor !== undefined &&
|
||||
(cursor.epoch !== history.epoch ||
|
||||
(cursor.retirementCount !== undefined && cursor.retirementCount !== history.retirementCount));
|
||||
// An after cursor is a gap when history it needs was dropped, or when it is ahead of the
|
||||
// history (lost commits, a restored database): left alone, the client would drop new rows.
|
||||
const gap =
|
||||
!staleCursor &&
|
||||
direction === "after" &&
|
||||
cursor !== undefined &&
|
||||
((hasRows && cursor.seq < history.minSeq - 1) || cursor.seq > window.maxSeq);
|
||||
const reset = staleCursor || gap;
|
||||
const page = input.selectPage({
|
||||
bounds: window,
|
||||
direction: reset ? "tail" : direction,
|
||||
cursorSeq: cursor?.seq,
|
||||
limit: options.limit ?? DEFAULT_TIMELINE_FETCH_LIMIT,
|
||||
wholeTurns: options.wholeTurns,
|
||||
});
|
||||
return {
|
||||
epoch: history.epoch,
|
||||
direction,
|
||||
reset,
|
||||
staleCursor,
|
||||
gap,
|
||||
window,
|
||||
hasOlder: page.hasOlder,
|
||||
hasNewer: page.hasNewer,
|
||||
startSeq: page.startSeq,
|
||||
endSeq: page.endSeq,
|
||||
// Stored rows are already within budget; this bounds assistant and reasoning merges.
|
||||
rows: page.entries.map((entry) =>
|
||||
Object.assign({ seq: entry.seqEnd }, entry, {
|
||||
item: limitAgentTimelineItemContent(entry.item),
|
||||
}),
|
||||
),
|
||||
retirements: page.retirements,
|
||||
retirementCount: history.retirementCount,
|
||||
activeSegmentStartSeq: history.activeSegmentStartSeq,
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { limitAgentTimelineItemContent } from "../../agent-timeline-content.js";
|
||||
import type { AgentMetric, AgentTimelineItem } from "../../agent-sdk-types.js";
|
||||
import type {
|
||||
AgentTimelineFetchOptions,
|
||||
@@ -11,17 +10,20 @@ import type { ProviderSubagentDescriptor } from "../../provider-subagents/store.
|
||||
import type {
|
||||
AgentTimelineBackend,
|
||||
TimelineBackendAppendResult,
|
||||
TimelineBackendCommitProviderSwitchResult,
|
||||
RetiredChildSelector,
|
||||
TimelineBackendRetireResult,
|
||||
TimelineChild,
|
||||
TimelineEntry,
|
||||
TimelineHead,
|
||||
TimelinePrompt,
|
||||
TimelineProviderSwitchIntent,
|
||||
TimelineRewindIntent,
|
||||
TimelineScope,
|
||||
TimelineSeed,
|
||||
} from "./backend.js";
|
||||
import { UnknownTimelineError } from "./backend.js";
|
||||
import { fetchTimelinePage } from "./fetch-page.js";
|
||||
import { buildSourceRow } from "./source-row.js";
|
||||
|
||||
interface MemoryTimelineState {
|
||||
epoch: string;
|
||||
@@ -32,13 +34,12 @@ interface MemoryTimelineState {
|
||||
retired: ProjectedTimelineRow[];
|
||||
retirementCount: number;
|
||||
rewind: TimelineRewindIntent | null;
|
||||
providerSwitch: TimelineProviderSwitchIntent | null;
|
||||
/** Child scopes only. */
|
||||
descriptor: ProviderSubagentDescriptor | null;
|
||||
childRetired: boolean;
|
||||
}
|
||||
|
||||
const DEFAULT_TIMELINE_FETCH_LIMIT = 200;
|
||||
|
||||
function scopeKey(scope: TimelineScope): string {
|
||||
return scope.subagentId === undefined
|
||||
? scope.agentId
|
||||
@@ -53,17 +54,6 @@ function cloneRow<T extends AgentTimelineRow>(row: T): T {
|
||||
return { ...row };
|
||||
}
|
||||
|
||||
function buildRow(entry: TimelineEntry, seq: number, timestamp: string): AgentTimelineRow {
|
||||
return {
|
||||
seq,
|
||||
timestamp: entry.timestamp ?? timestamp,
|
||||
item: entry.item,
|
||||
...(entry.turnId ? { turnId: entry.turnId } : {}),
|
||||
...(entry.providerMessageId ? { providerMessageId: entry.providerMessageId } : {}),
|
||||
...(entry.turnMetrics ? { turnMetrics: entry.turnMetrics } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Volatile backend: history lives in process memory and is lost when the daemon exits. */
|
||||
export class MemoryTimelineBackend implements AgentTimelineBackend {
|
||||
private readonly states = new Map<string, MemoryTimelineState>();
|
||||
@@ -73,7 +63,9 @@ export class MemoryTimelineBackend implements AgentTimelineBackend {
|
||||
const startSeq = seed.nextSeq ?? 1;
|
||||
const rows = seed.rows?.length
|
||||
? seed.rows.map(cloneRow)
|
||||
: (seed.entries ?? []).map((entry, index) => buildRow(entry, startSeq + index, timestamp));
|
||||
: (seed.entries ?? []).map((entry, index) =>
|
||||
buildSourceRow(entry, startSeq + index, timestamp),
|
||||
);
|
||||
const nextSeq = rows.reduce((next, row) => Math.max(next, row.seq + 1), startSeq);
|
||||
const projection = new TimelineProjection(rows);
|
||||
const state: MemoryTimelineState = {
|
||||
@@ -84,6 +76,7 @@ export class MemoryTimelineBackend implements AgentTimelineBackend {
|
||||
retired: [],
|
||||
retirementCount: 0,
|
||||
rewind: null,
|
||||
providerSwitch: null,
|
||||
descriptor: null,
|
||||
childRetired: false,
|
||||
};
|
||||
@@ -137,7 +130,9 @@ export class MemoryTimelineBackend implements AgentTimelineBackend {
|
||||
append(scope: TimelineScope, entries: readonly TimelineEntry[]): TimelineBackendAppendResult {
|
||||
const state = this.requireState(scope);
|
||||
const timestamp = new Date().toISOString();
|
||||
const rows = entries.map((entry, index) => buildRow(entry, state.nextSeq + index, timestamp));
|
||||
const rows = entries.map((entry, index) =>
|
||||
buildSourceRow(entry, state.nextSeq + index, timestamp),
|
||||
);
|
||||
for (const row of rows) {
|
||||
state.projection.append(row);
|
||||
state.nextSeq = row.seq + 1;
|
||||
@@ -150,18 +145,11 @@ export class MemoryTimelineBackend implements AgentTimelineBackend {
|
||||
return this.requireState(scope).projection.isRetired(entry);
|
||||
}
|
||||
|
||||
prompts(scope: TimelineScope): TimelinePrompt[] {
|
||||
const prompts: TimelinePrompt[] = [];
|
||||
for (const row of this.requireState(scope).projection.getRows()) {
|
||||
if (row.item.type !== "user_message") continue;
|
||||
prompts.push({
|
||||
seqStart: row.seqStart,
|
||||
messageId: row.item.messageId,
|
||||
providerMessageId: row.providerMessageId,
|
||||
submitted: row.item.clientMessageId !== undefined,
|
||||
});
|
||||
}
|
||||
return prompts;
|
||||
promptRows(scope: TimelineScope): ProjectedTimelineRow[] {
|
||||
return this.requireState(scope)
|
||||
.projection.getRows()
|
||||
.filter((row) => row.item.type === "user_message")
|
||||
.map(cloneRow);
|
||||
}
|
||||
|
||||
setRewind(scope: TimelineScope, rewind: TimelineRewindIntent | null): TimelineHead {
|
||||
@@ -170,6 +158,34 @@ export class MemoryTimelineBackend implements AgentTimelineBackend {
|
||||
return this.describe(state);
|
||||
}
|
||||
|
||||
setProviderSwitch(
|
||||
scope: TimelineScope,
|
||||
providerSwitch: TimelineProviderSwitchIntent | null,
|
||||
): TimelineHead {
|
||||
const state = this.requireState(scope);
|
||||
state.providerSwitch = providerSwitch ? structuredClone(providerSwitch) : null;
|
||||
return this.describe(state);
|
||||
}
|
||||
|
||||
commitProviderSwitch(
|
||||
scope: TimelineScope,
|
||||
input: {
|
||||
markerEntry: TimelineEntry;
|
||||
nextIntent: TimelineProviderSwitchIntent | null;
|
||||
},
|
||||
): TimelineBackendCommitProviderSwitchResult {
|
||||
const state = this.requireState(scope);
|
||||
const timestamp = new Date().toISOString();
|
||||
const row = buildSourceRow(input.markerEntry, state.nextSeq, timestamp);
|
||||
state.projection.append(row);
|
||||
state.nextSeq = row.seq + 1;
|
||||
if (state.minSeq === 0) state.minSeq = row.seq;
|
||||
state.providerSwitch = input.nextIntent
|
||||
? structuredClone({ ...input.nextIntent, markerSeq: row.seq })
|
||||
: null;
|
||||
return { row: cloneRow(row), head: this.describe(state) };
|
||||
}
|
||||
|
||||
retire(
|
||||
scope: TimelineScope,
|
||||
input: { retireFromSeq: number; selectChildren: RetiredChildSelector },
|
||||
@@ -204,10 +220,12 @@ export class MemoryTimelineBackend implements AgentTimelineBackend {
|
||||
scope: TimelineScope,
|
||||
clientMessageId: string,
|
||||
providerMessageId: string,
|
||||
options?: { providerPromptText?: string },
|
||||
): AgentTimelineRow | null {
|
||||
return this.requireState(scope).projection.enrichSubmittedUserMessage(
|
||||
clientMessageId,
|
||||
providerMessageId,
|
||||
options,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -233,48 +251,17 @@ export class MemoryTimelineBackend implements AgentTimelineBackend {
|
||||
|
||||
fetch(scope: TimelineScope, options: AgentTimelineFetchOptions): AgentTimelineFetchResult {
|
||||
const state = this.requireState(scope);
|
||||
const direction = options.direction ?? "tail";
|
||||
const cursor = options.cursor;
|
||||
const hasRows = state.minSeq !== 0;
|
||||
const window = { minSeq: state.minSeq, maxSeq: state.nextSeq - 1, nextSeq: state.nextSeq };
|
||||
const staleCursor =
|
||||
cursor !== undefined &&
|
||||
(cursor.epoch !== state.epoch ||
|
||||
(cursor.retirementCount !== undefined && cursor.retirementCount !== state.retirementCount));
|
||||
const gap =
|
||||
!staleCursor &&
|
||||
direction === "after" &&
|
||||
cursor !== undefined &&
|
||||
hasRows &&
|
||||
cursor.seq < state.minSeq - 1;
|
||||
const reset = staleCursor || gap;
|
||||
const page = state.projection.selectPage({
|
||||
bounds: window,
|
||||
direction: reset ? "tail" : direction,
|
||||
cursorSeq: cursor?.seq,
|
||||
limit: options.limit ?? DEFAULT_TIMELINE_FETCH_LIMIT,
|
||||
wholeTurns: options.wholeTurns,
|
||||
return fetchTimelinePage({
|
||||
history: {
|
||||
epoch: state.epoch,
|
||||
minSeq: state.minSeq,
|
||||
nextSeq: state.nextSeq,
|
||||
retirementCount: state.retirementCount,
|
||||
activeSegmentStartSeq: state.projection.getActiveSegmentStartSeq(),
|
||||
},
|
||||
options,
|
||||
selectPage: (page) => state.projection.selectPage(page),
|
||||
});
|
||||
return {
|
||||
epoch: state.epoch,
|
||||
direction,
|
||||
reset,
|
||||
staleCursor,
|
||||
gap,
|
||||
window,
|
||||
hasOlder: page.hasOlder,
|
||||
hasNewer: page.hasNewer,
|
||||
startSeq: page.startSeq,
|
||||
endSeq: page.endSeq,
|
||||
// Stored rows are already within budget; this bounds assistant and reasoning merges.
|
||||
rows: page.entries.map((entry) =>
|
||||
Object.assign({ seq: entry.seqEnd }, entry, {
|
||||
item: limitAgentTimelineItemContent(entry.item),
|
||||
}),
|
||||
),
|
||||
retirements: page.retirements,
|
||||
retirementCount: state.retirementCount,
|
||||
};
|
||||
}
|
||||
|
||||
readRows(scope: TimelineScope): ProjectedTimelineRow[] {
|
||||
@@ -296,7 +283,9 @@ export class MemoryTimelineBackend implements AgentTimelineBackend {
|
||||
seq: state.nextSeq - 1,
|
||||
size: state.projection.size,
|
||||
retirementCount: state.retirementCount,
|
||||
activeSegmentStartSeq: state.projection.getActiveSegmentStartSeq(),
|
||||
rewind: state.rewind ? { ...state.rewind } : null,
|
||||
providerSwitch: state.providerSwitch ? structuredClone(state.providerSwitch) : null,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -24,8 +24,16 @@ export function planProviderHistory(input: {
|
||||
rows: readonly ProjectedTimelineRow[];
|
||||
prompts: readonly TimelinePrompt[];
|
||||
provider: readonly TimelineEntry[];
|
||||
activeSegmentStartSeq?: number;
|
||||
}): ProviderHistoryPlan {
|
||||
const owned = ownedPrompts(input.rows, input.prompts);
|
||||
const segmentStart = input.activeSegmentStartSeq ?? 0;
|
||||
const segmentRows =
|
||||
segmentStart > 0 ? input.rows.filter((row) => row.seqStart > segmentStart) : input.rows;
|
||||
const segmentPrompts =
|
||||
segmentStart > 0
|
||||
? input.prompts.filter((prompt) => prompt.seqStart > segmentStart)
|
||||
: input.prompts;
|
||||
const owned = ownedPrompts(segmentRows, segmentPrompts);
|
||||
const provider = providerPrompts(input.provider);
|
||||
if ([...owned.prompts, ...provider].some((prompt) => prompt.id === undefined)) {
|
||||
return { kind: "diverged", reason: "A prompt has no provider id" };
|
||||
@@ -61,7 +69,10 @@ function ownedPrompts(
|
||||
if (!prompt) continue;
|
||||
trailingUndeliveredPrompt = prompt.submitted && !prompt.providerMessageId;
|
||||
if (!trailingUndeliveredPrompt) {
|
||||
acknowledged.push({ id: prompt.providerMessageId ?? prompt.messageId, text: row.item.text });
|
||||
acknowledged.push({
|
||||
id: prompt.providerMessageId ?? prompt.messageId,
|
||||
text: row.providerPromptText ?? row.item.text,
|
||||
});
|
||||
}
|
||||
}
|
||||
return { prompts: acknowledged, trailingUndeliveredPrompt };
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { AgentTimelineRow } from "../../agent-timeline-store-types.js";
|
||||
import type { TimelineEntry } from "./backend.js";
|
||||
|
||||
/** The source row an entry commits as, at `seq`. */
|
||||
export function buildSourceRow(
|
||||
entry: TimelineEntry,
|
||||
seq: number,
|
||||
timestamp: string,
|
||||
): AgentTimelineRow {
|
||||
return {
|
||||
seq,
|
||||
timestamp: entry.timestamp ?? timestamp,
|
||||
item: entry.item,
|
||||
...(entry.provider ? { provider: entry.provider } : {}),
|
||||
...(entry.turnId ? { turnId: entry.turnId } : {}),
|
||||
...(entry.providerMessageId ? { providerMessageId: entry.providerMessageId } : {}),
|
||||
...(entry.providerPromptText !== undefined
|
||||
? { providerPromptText: entry.providerPromptText }
|
||||
: {}),
|
||||
...(entry.rejected ? { rejected: true } : {}),
|
||||
...(entry.turnMetrics ? { turnMetrics: entry.turnMetrics } : {}),
|
||||
};
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,486 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { AgentTimelineItem, ProviderSwitchTimelineItem } from "../agent-sdk-types.js";
|
||||
import type { ProviderSubagentDescriptor } from "../provider-subagents/store.js";
|
||||
import {
|
||||
DatabaseSchemaTooNewError,
|
||||
openDaemonDatabase,
|
||||
type DaemonDatabase,
|
||||
type SchemaModule,
|
||||
} from "../../database/index.js";
|
||||
import { createTestLogger } from "../../../test-utils/test-logger.js";
|
||||
import { nextTestDatabasePath } from "../../test-utils/test-database-path.js";
|
||||
import {
|
||||
AgentTimeline,
|
||||
TimelineProviderSwitchPendingError,
|
||||
TimelineRewindPendingError,
|
||||
TimelineRewindSegmentBoundaryError,
|
||||
createStoredAgentTimeline,
|
||||
timelineSchema,
|
||||
type TimelineEntry,
|
||||
type TimelineProviderSwitchIntent,
|
||||
type TimelineScope,
|
||||
} from "./index.js";
|
||||
import { SqliteTimelineBackend } from "./internal/sqlite-backend.js";
|
||||
import { openTestTimelineDatabase, TIMELINE_CONTRACT_BACKENDS } from "./testing.js";
|
||||
|
||||
const scope: TimelineScope = { agentId: "agent-switch" };
|
||||
const TS = "2026-11-25T10:00:00.000Z";
|
||||
|
||||
function switchMarker(fromProvider = "claude", toProvider = "codex"): ProviderSwitchTimelineItem {
|
||||
return {
|
||||
type: "provider_switch",
|
||||
fromProvider,
|
||||
toProvider,
|
||||
fromModel: "claude-sonnet-4-6",
|
||||
toModel: "gpt-5.4",
|
||||
fromSessionId: "claude-sess-1",
|
||||
toSessionId: null,
|
||||
context: {
|
||||
includedItems: 2,
|
||||
truncated: false,
|
||||
charCount: 120,
|
||||
budgetChars: 100_000,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function switchIntent(
|
||||
overrides: Partial<TimelineProviderSwitchIntent> = {},
|
||||
): Omit<TimelineProviderSwitchIntent, "id" | "phase"> {
|
||||
return {
|
||||
messageId: "msg-switch-1",
|
||||
fromProvider: "claude",
|
||||
fromPersistence: { provider: "claude", sessionId: "claude-sess-1" },
|
||||
fromModel: "claude-sonnet-4-6",
|
||||
toProvider: "codex",
|
||||
toConfig: { model: "gpt-5.4", modeId: "auto" },
|
||||
targetPersistence: null,
|
||||
context: {
|
||||
includedItems: 2,
|
||||
truncated: false,
|
||||
charCount: 120,
|
||||
budgetChars: 100_000,
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function tool(callId: string, status: "running" | "completed", label = callId): AgentTimelineItem {
|
||||
return {
|
||||
type: "tool_call",
|
||||
callId,
|
||||
name: "shell",
|
||||
status,
|
||||
error: null,
|
||||
detail: { type: "plain_text", label },
|
||||
};
|
||||
}
|
||||
|
||||
function childDescriptor(
|
||||
id: string,
|
||||
provider: string,
|
||||
toolCallId: string,
|
||||
): ProviderSubagentDescriptor {
|
||||
return {
|
||||
id,
|
||||
parentAgentId: scope.agentId,
|
||||
parentSubagentId: null,
|
||||
provider,
|
||||
title: id,
|
||||
description: null,
|
||||
status: "completed",
|
||||
createdAt: TS,
|
||||
updatedAt: TS,
|
||||
toolCallId,
|
||||
cwd: null,
|
||||
subtitle: null,
|
||||
};
|
||||
}
|
||||
|
||||
function dumpTables(database: DaemonDatabase): Record<string, unknown[]> {
|
||||
return database.read((sql) => {
|
||||
const tables = sql
|
||||
.all<{ name: string }>(
|
||||
"SELECT name FROM sqlite_master WHERE type = 'table' AND name LIKE 'timeline_%' ORDER BY name",
|
||||
)
|
||||
.map((table) => table.name);
|
||||
return Object.fromEntries(tables.map((table) => [table, sql.all(`SELECT * FROM ${table}`)]));
|
||||
});
|
||||
}
|
||||
|
||||
describe.each(TIMELINE_CONTRACT_BACKENDS)(
|
||||
"provider switching timeline contract ($name)",
|
||||
({ create }) => {
|
||||
it("commits switch marker, scopes rewind to active segment, and protects pre-switch history on null retainedMessageId", async () => {
|
||||
const timeline = new AgentTimeline(create());
|
||||
await timeline.create(scope, { epoch: "ep-1" });
|
||||
|
||||
// Segment 1 (Claude)
|
||||
await timeline.ingest(scope, {
|
||||
provider: "claude",
|
||||
turnId: "t1",
|
||||
item: {
|
||||
type: "user_message",
|
||||
text: "First Claude prompt",
|
||||
messageId: "c1",
|
||||
clientMessageId: "c1",
|
||||
},
|
||||
});
|
||||
await timeline.attachProviderMessageId(scope, "c1", "claude-p1");
|
||||
await timeline.ingest(scope, {
|
||||
provider: "claude",
|
||||
turnId: "t1",
|
||||
item: { type: "assistant_message", text: "Claude answer" },
|
||||
});
|
||||
|
||||
const intent = await timeline.beginProviderSwitch(scope, switchIntent());
|
||||
expect((await timeline.describe(scope))?.providerSwitch?.phase).toBe("preparing");
|
||||
|
||||
// Rewind refused while switch intent is open
|
||||
await expect(timeline.beginRewind(scope, "c1")).rejects.toThrow(
|
||||
TimelineProviderSwitchPendingError,
|
||||
);
|
||||
|
||||
const committed = await timeline.commitProviderSwitch(scope, intent.id, {
|
||||
markerEntry: { provider: "codex", item: switchMarker("claude", "codex") },
|
||||
});
|
||||
expect(committed.kind).toBe("committed");
|
||||
if (committed.kind !== "committed") return;
|
||||
const markerSeq = committed.row.seq;
|
||||
|
||||
const headAfterCommit = await timeline.describe(scope);
|
||||
expect(headAfterCommit?.activeSegmentStartSeq).toBe(markerSeq);
|
||||
expect(headAfterCommit?.providerSwitch?.phase).toBe("marker_committed");
|
||||
expect(headAfterCommit?.providerSwitch?.markerSeq).toBe(markerSeq);
|
||||
|
||||
await timeline.completeProviderSwitch(scope, intent.id);
|
||||
expect((await timeline.describe(scope))?.providerSwitch).toBeNull();
|
||||
|
||||
// Segment 2 (Codex)
|
||||
await timeline.ingest(scope, {
|
||||
provider: "codex",
|
||||
turnId: "t1",
|
||||
providerPromptText:
|
||||
"<chat-history-summary>...</chat-history-summary>\n\nFirst Codex prompt",
|
||||
item: {
|
||||
type: "user_message",
|
||||
text: "First Codex prompt",
|
||||
messageId: "c2",
|
||||
clientMessageId: "c2",
|
||||
},
|
||||
});
|
||||
await timeline.attachProviderMessageId(scope, "c2", "codex-p1", {
|
||||
providerPromptText:
|
||||
"<chat-history-summary>...</chat-history-summary>\n\nFirst Codex prompt",
|
||||
});
|
||||
await timeline.ingest(scope, {
|
||||
provider: "codex",
|
||||
turnId: "t1",
|
||||
item: { type: "assistant_message", text: "Codex answer" },
|
||||
});
|
||||
|
||||
const page = await timeline.fetch(scope, { direction: "tail", limit: 20 });
|
||||
expect(page.activeSegmentStartSeq).toBe(markerSeq);
|
||||
|
||||
// Rewinding pre-switch prompt is refused
|
||||
await expect(timeline.beginRewind(scope, "c1")).rejects.toThrow(
|
||||
TimelineRewindSegmentBoundaryError,
|
||||
);
|
||||
|
||||
// Rewinding first post-switch prompt with retainedMessageId: null retires ONLY segment 2
|
||||
const rewind = await timeline.beginRewind(scope, "c2");
|
||||
await timeline.recordRewindCut(scope, rewind.id, { kind: "after", retainedMessageId: null });
|
||||
const completion = await timeline.completeRewind(scope, rewind.id);
|
||||
expect(completion.kind).toBe("retired");
|
||||
if (completion.kind !== "retired") return;
|
||||
expect(completion.retirement.retireFromSeq).toBeGreaterThan(markerSeq);
|
||||
|
||||
const remaining = await timeline.readRows(scope);
|
||||
expect(remaining.map((r) => r.item.type)).toEqual([
|
||||
"user_message",
|
||||
"assistant_message",
|
||||
"provider_switch",
|
||||
]);
|
||||
});
|
||||
|
||||
it("judges open rewind and reconciles provider history strictly within the active segment using providerPromptText", async () => {
|
||||
const timeline = new AgentTimeline(create());
|
||||
await timeline.create(scope, { epoch: "ep-1" });
|
||||
|
||||
// Segment 1 (Claude)
|
||||
await timeline.ingest(scope, {
|
||||
provider: "claude",
|
||||
item: {
|
||||
type: "user_message",
|
||||
text: "Claude prompt",
|
||||
messageId: "c1",
|
||||
clientMessageId: "c1",
|
||||
},
|
||||
});
|
||||
await timeline.attachProviderMessageId(scope, "c1", "claude-p1");
|
||||
|
||||
const intent = await timeline.beginProviderSwitch(scope, switchIntent());
|
||||
await timeline.commitProviderSwitch(scope, intent.id, {
|
||||
markerEntry: { provider: "codex", item: switchMarker("claude", "codex") },
|
||||
});
|
||||
await timeline.completeProviderSwitch(scope, intent.id);
|
||||
|
||||
// Segment 2 (Codex) with attachment-bearing handoff prompt + second prompt
|
||||
const handoffRendered =
|
||||
"<chat-history-summary>\nctx\n</chat-history-summary>\n\nSwitch prompt";
|
||||
await timeline.ingest(scope, {
|
||||
provider: "codex",
|
||||
providerPromptText: handoffRendered,
|
||||
item: {
|
||||
type: "user_message",
|
||||
text: "Switch prompt",
|
||||
messageId: "c2",
|
||||
clientMessageId: "c2",
|
||||
},
|
||||
});
|
||||
await timeline.attachProviderMessageId(scope, "c2", "codex-p1", {
|
||||
providerPromptText: handoffRendered,
|
||||
});
|
||||
await timeline.ingest(scope, {
|
||||
provider: "codex",
|
||||
item: { type: "assistant_message", text: "Codex reply 1" },
|
||||
});
|
||||
await timeline.ingest(scope, {
|
||||
provider: "codex",
|
||||
item: { type: "user_message", text: "Follow up", messageId: "c3", clientMessageId: "c3" },
|
||||
});
|
||||
await timeline.attachProviderMessageId(scope, "c3", "codex-p2");
|
||||
|
||||
// Reconcile against Codex native replay (which only has codex-p1 and codex-p2, plus a new turn)
|
||||
const providerReplay: TimelineEntry[] = [
|
||||
{
|
||||
provider: "codex",
|
||||
item: { type: "user_message", text: handoffRendered, messageId: "codex-p1" },
|
||||
},
|
||||
{ provider: "codex", item: { type: "assistant_message", text: "Codex reply 1" } },
|
||||
{
|
||||
provider: "codex",
|
||||
item: { type: "user_message", text: "Follow up", messageId: "codex-p2" },
|
||||
},
|
||||
{
|
||||
provider: "codex",
|
||||
item: { type: "user_message", text: "External turn", messageId: "codex-p3" },
|
||||
},
|
||||
{ provider: "codex", item: { type: "assistant_message", text: "External reply" } },
|
||||
];
|
||||
const reconciled = await timeline.reconcileProviderHistory(scope, providerReplay);
|
||||
expect(reconciled.kind).toBe("appended");
|
||||
|
||||
// Judge open rewind on codex-p2 using only Codex's native prompt IDs
|
||||
const rw = await timeline.beginRewind(scope, "c3");
|
||||
const unchanged = await timeline.judgeRewind(scope, rw.id, [
|
||||
"codex-p1",
|
||||
"codex-p2",
|
||||
"codex-p3",
|
||||
]);
|
||||
expect(unchanged).toEqual({ kind: "unchanged" });
|
||||
const applied = await timeline.judgeRewind(scope, rw.id, ["codex-p1"]);
|
||||
expect(applied).toEqual({
|
||||
kind: "applied",
|
||||
cut: { kind: "after", retainedMessageId: "codex-p1" },
|
||||
});
|
||||
|
||||
// Opening a provider switch while rewind is open is refused
|
||||
await expect(
|
||||
timeline.beginProviderSwitch(scope, switchIntent({ messageId: "msg-2" })),
|
||||
).rejects.toThrow(TimelineRewindPendingError);
|
||||
});
|
||||
|
||||
it("isolates tool call identities, retired keys, turn metrics, and provider children across segments", async () => {
|
||||
const timeline = new AgentTimeline(create());
|
||||
await timeline.create(scope, { epoch: "ep-1" });
|
||||
|
||||
// Segment 1 (Claude) with tool call_1 (active) and turn t1 + tool call_2 (retired)
|
||||
await timeline.ingest(scope, {
|
||||
provider: "claude",
|
||||
turnId: "t1",
|
||||
item: { type: "user_message", text: "Claude 1", messageId: "c1", clientMessageId: "c1" },
|
||||
});
|
||||
await timeline.attachProviderMessageId(scope, "c1", "claude-p1");
|
||||
await timeline.ingest(scope, {
|
||||
provider: "claude",
|
||||
turnId: "t1",
|
||||
item: tool("call_shared", "completed", "claude tool"),
|
||||
});
|
||||
await timeline.recordChild({ agentId: scope.agentId, subagentId: "claude-child-1" }, () =>
|
||||
childDescriptor("claude-child-1", "claude", "call_shared"),
|
||||
);
|
||||
await timeline.ingest(scope, {
|
||||
provider: "claude",
|
||||
turnId: "t1",
|
||||
item: { type: "assistant_message", text: "Claude 1 reply" },
|
||||
});
|
||||
|
||||
await timeline.ingest(scope, {
|
||||
provider: "claude",
|
||||
turnId: "t_retired",
|
||||
item: { type: "user_message", text: "Claude 2", messageId: "c2", clientMessageId: "c2" },
|
||||
});
|
||||
await timeline.attachProviderMessageId(scope, "c2", "claude-p2");
|
||||
await timeline.ingest(scope, {
|
||||
provider: "claude",
|
||||
turnId: "t_retired",
|
||||
item: tool("call_retired", "completed"),
|
||||
});
|
||||
// Retire Claude 2 so call_retired and t_retired are in retired keys
|
||||
const rw1 = await timeline.beginRewind(scope, "c2");
|
||||
await timeline.recordRewindCut(scope, rw1.id, { kind: "at_target" });
|
||||
await timeline.completeRewind(scope, rw1.id);
|
||||
|
||||
// Switch to Codex
|
||||
const intent = await timeline.beginProviderSwitch(scope, switchIntent());
|
||||
await timeline.commitProviderSwitch(scope, intent.id, {
|
||||
markerEntry: { provider: "codex", item: switchMarker("claude", "codex") },
|
||||
});
|
||||
await timeline.completeProviderSwitch(scope, intent.id);
|
||||
|
||||
// Segment 2 (Codex) reuses turnId "t_retired", callId "call_retired", and callId "call_shared"
|
||||
await timeline.ingest(scope, {
|
||||
provider: "codex",
|
||||
turnId: "t_retired",
|
||||
item: { type: "user_message", text: "Codex 1", messageId: "c3", clientMessageId: "c3" },
|
||||
});
|
||||
await timeline.attachProviderMessageId(scope, "c3", "codex-p1");
|
||||
const reusedRetired = await timeline.ingest(scope, {
|
||||
provider: "codex",
|
||||
turnId: "t_retired",
|
||||
item: tool("call_retired", "completed", "codex reused retired"),
|
||||
});
|
||||
expect(reusedRetired.kind).toBe("recorded");
|
||||
|
||||
const reusedActive = await timeline.ingest(scope, {
|
||||
provider: "codex",
|
||||
turnId: "t1",
|
||||
item: tool("call_shared", "completed", "codex tool"),
|
||||
});
|
||||
expect(reusedActive.kind).toBe("recorded");
|
||||
await timeline.ingest(scope, {
|
||||
provider: "codex",
|
||||
turnId: "t1",
|
||||
item: { type: "assistant_message", text: "Codex reply" },
|
||||
});
|
||||
|
||||
// Stamping turnMetrics for turnId "t1" stamps Codex's assistant reply, not Claude's
|
||||
const stamped = await timeline.stampTurnMetrics(scope, [{ label: "Tokens", value: "42" }], {
|
||||
turnId: "t1",
|
||||
});
|
||||
expect(stamped?.item).toEqual({ type: "assistant_message", text: "Codex reply" });
|
||||
|
||||
// Both Claude's and Codex's call_shared rows exist separately
|
||||
const rows = await timeline.readRows(scope);
|
||||
const sharedTools = rows.filter(
|
||||
(row) => row.item.type === "tool_call" && row.item.callId === "call_shared",
|
||||
);
|
||||
expect(sharedTools).toHaveLength(2);
|
||||
|
||||
// Rewinding Codex's turn with call_shared does NOT retire Claude's historical provider child
|
||||
const rw2 = await timeline.beginRewind(scope, "c3");
|
||||
await timeline.recordRewindCut(scope, rw2.id, { kind: "at_target" });
|
||||
await timeline.completeRewind(scope, rw2.id);
|
||||
const children = await timeline.listChildren(scope.agentId);
|
||||
expect(children).toEqual([
|
||||
expect.objectContaining({ subagentId: "claude-child-1", retired: false }),
|
||||
]);
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
describe("SQLite timeline migration v2 and durability", () => {
|
||||
it("migrates a v1 database in place and refuses downgrade to a v1 reader", async () => {
|
||||
const file = nextTestDatabasePath();
|
||||
const v1Schema: SchemaModule = {
|
||||
name: "timeline",
|
||||
migrations: [timelineSchema.migrations[0]!],
|
||||
};
|
||||
const dbV1 = openDaemonDatabase({
|
||||
path: file,
|
||||
modules: [v1Schema],
|
||||
logger: createTestLogger(),
|
||||
});
|
||||
// Seed a v1 scope row directly
|
||||
dbV1.write((sql) => {
|
||||
sql.run(
|
||||
"INSERT INTO timeline_scopes (agent_id, subagent_id, epoch, next_seq, min_seq, active_count, active_max_seq_end, retirement_count) VALUES (?, NULL, 'ep-v1', 1, 0, 0, 0, 0)",
|
||||
scope.agentId,
|
||||
);
|
||||
});
|
||||
dbV1.close();
|
||||
|
||||
// Open with v2 schema — upgrades cleanly
|
||||
const dbV2 = openDaemonDatabase({
|
||||
path: file,
|
||||
modules: [timelineSchema],
|
||||
logger: createTestLogger(),
|
||||
});
|
||||
const timeline = createStoredAgentTimeline(dbV2);
|
||||
const head = await timeline.describe(scope);
|
||||
expect(head).toMatchObject({
|
||||
epoch: "ep-v1",
|
||||
activeSegmentStartSeq: 0,
|
||||
providerSwitch: null,
|
||||
});
|
||||
const intent = await timeline.beginProviderSwitch(scope, switchIntent());
|
||||
await timeline.commitProviderSwitch(scope, intent.id, {
|
||||
markerEntry: { provider: "codex", item: switchMarker() },
|
||||
});
|
||||
await timeline.close();
|
||||
dbV2.close();
|
||||
|
||||
// Reopening with v2 preserves open intent + activeSegmentStartSeq
|
||||
const dbV2Reopen = openDaemonDatabase({
|
||||
path: file,
|
||||
modules: [timelineSchema],
|
||||
logger: createTestLogger(),
|
||||
});
|
||||
const reopened = createStoredAgentTimeline(dbV2Reopen);
|
||||
const reopenedHead = await reopened.describe(scope);
|
||||
expect(reopenedHead?.activeSegmentStartSeq).toBe(1);
|
||||
expect(reopenedHead?.providerSwitch?.phase).toBe("marker_committed");
|
||||
await reopened.close();
|
||||
dbV2Reopen.close();
|
||||
|
||||
// Reopening with v1 reader refuses with DatabaseSchemaTooNewError
|
||||
expect(() =>
|
||||
openDaemonDatabase({ path: file, modules: [v1Schema], logger: createTestLogger() }),
|
||||
).toThrow(DatabaseSchemaTooNewError);
|
||||
});
|
||||
|
||||
it("rolls back commitProviderSwitch atomically if a statement fails mid-transaction", () => {
|
||||
const database = openTestTimelineDatabase();
|
||||
const backend = new SqliteTimelineBackend(database);
|
||||
backend.create(scope, { epoch: "ep-rollback" });
|
||||
backend.append(scope, [
|
||||
{
|
||||
provider: "claude",
|
||||
item: { type: "user_message", text: "hi", messageId: "m1" },
|
||||
timestamp: TS,
|
||||
},
|
||||
]);
|
||||
const intent: TimelineProviderSwitchIntent = {
|
||||
id: "sw-1",
|
||||
phase: "preparing",
|
||||
...switchIntent(),
|
||||
};
|
||||
backend.setProviderSwitch(scope, intent);
|
||||
const before = dumpTables(database);
|
||||
database.write((sql) => {
|
||||
sql.exec(
|
||||
"CREATE TRIGGER fail_switch BEFORE INSERT ON timeline_source_ranges " +
|
||||
"BEGIN SELECT RAISE(ABORT, 'disk full'); END;",
|
||||
);
|
||||
});
|
||||
expect(() =>
|
||||
backend.commitProviderSwitch(scope, {
|
||||
markerEntry: { provider: "codex", item: switchMarker(), timestamp: TS },
|
||||
nextIntent: { ...intent, phase: "marker_committed", markerSeq: 2 },
|
||||
}),
|
||||
).toThrow(/disk full/);
|
||||
expect(dumpTables(database)).toEqual(before);
|
||||
database.close();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,498 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { AgentTimelineItem } from "../agent-sdk-types.js";
|
||||
import type { AgentTimelineFetchOptions } from "../agent-timeline-store-types.js";
|
||||
import type { ProviderSubagentDescriptor } from "../provider-subagents/store.js";
|
||||
import type { DaemonDatabase, ReadSql, WriteSql } from "../../database/index.js";
|
||||
import { MemoryTimelineBackend } from "./internal/memory-backend.js";
|
||||
import { SqliteTimelineBackend } from "./internal/sqlite-backend.js";
|
||||
import { nextTestDatabasePath } from "../../test-utils/test-database-path.js";
|
||||
import { DeferredTimelineBackend, openTestTimelineDatabase } from "./testing.js";
|
||||
import {
|
||||
AgentTimeline,
|
||||
TimelineClosedError,
|
||||
type TimelineEntry,
|
||||
type TimelineScope,
|
||||
} from "./index.js";
|
||||
|
||||
const scope: TimelineScope = { agentId: "agent" };
|
||||
const TIMESTAMP = "2026-11-25T10:00:00.000Z";
|
||||
|
||||
function entry(item: AgentTimelineItem, fields: Omit<TimelineEntry, "item"> = {}): TimelineEntry {
|
||||
return { item, timestamp: TIMESTAMP, ...fields };
|
||||
}
|
||||
|
||||
function tool(callId: string, status: "running" | "completed", label = callId): AgentTimelineItem {
|
||||
return {
|
||||
type: "tool_call",
|
||||
callId,
|
||||
name: "shell",
|
||||
status,
|
||||
error: null,
|
||||
detail: { type: "plain_text", label },
|
||||
};
|
||||
}
|
||||
|
||||
function descriptor(id: string, toolCallId: string | null): ProviderSubagentDescriptor {
|
||||
return {
|
||||
id,
|
||||
parentAgentId: "agent",
|
||||
parentSubagentId: null,
|
||||
provider: "claude",
|
||||
title: null,
|
||||
description: null,
|
||||
status: "running",
|
||||
createdAt: TIMESTAMP,
|
||||
updatedAt: TIMESTAMP,
|
||||
toolCallId,
|
||||
cwd: null,
|
||||
subtitle: null,
|
||||
};
|
||||
}
|
||||
|
||||
function seededRandom(seed: number): (bound: number) => number {
|
||||
let state = seed;
|
||||
return (bound) => {
|
||||
state = (Math.imul(state, 1664525) + 1013904223) >>> 0;
|
||||
return Math.floor((state / 0x1_0000_0000) * bound);
|
||||
};
|
||||
}
|
||||
|
||||
/** Every row of every timeline table, to compare stored state before and after a failed write. */
|
||||
function dumpTables(database: DaemonDatabase): Record<string, unknown[]> {
|
||||
return database.read((sql) => {
|
||||
const tables = sql
|
||||
.all<{ name: string }>(
|
||||
"SELECT name FROM sqlite_master WHERE type = 'table' AND name LIKE 'timeline_%' ORDER BY name",
|
||||
)
|
||||
.map((table) => table.name);
|
||||
return Object.fromEntries(tables.map((table) => [table, sql.all(`SELECT * FROM ${table}`)]));
|
||||
});
|
||||
}
|
||||
|
||||
/** Counts the rows the backend's queries return, to prove a read touches a bounded slice. */
|
||||
class CountingDatabase implements DaemonDatabase {
|
||||
rowsRead = 0;
|
||||
|
||||
constructor(private readonly inner: DaemonDatabase) {}
|
||||
|
||||
write<T>(fn: (sql: WriteSql) => T): T {
|
||||
return this.inner.write((sql) => fn({ ...this.counting(sql), run: sql.run, exec: sql.exec }));
|
||||
}
|
||||
|
||||
read<T>(fn: (sql: ReadSql) => T): T {
|
||||
return this.inner.read((sql) => fn(this.counting(sql)));
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.inner.close();
|
||||
}
|
||||
|
||||
private counting(sql: ReadSql): ReadSql {
|
||||
return {
|
||||
get: (query, ...params) => {
|
||||
const row = sql.get(query, ...params);
|
||||
if (row !== undefined) this.rowsRead += 1;
|
||||
return row as never;
|
||||
},
|
||||
all: (query, ...params) => {
|
||||
const rows = sql.all(query, ...params);
|
||||
this.rowsRead += rows.length;
|
||||
return rows as never;
|
||||
},
|
||||
iterate: <T>(query: string, ...params: Parameters<ReadSql["get"]>[1][]) => {
|
||||
const rows = sql.iterate<T>(query, ...params);
|
||||
const count = () => (this.rowsRead += 1);
|
||||
return {
|
||||
*[Symbol.iterator]() {
|
||||
for (const row of rows) {
|
||||
count();
|
||||
yield row;
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
describe("SQLite timeline backend against the memory backend", () => {
|
||||
it("stores the same history and serves the same pages on seeded randomized timelines", () => {
|
||||
const random = seededRandom(0x5eed_0001);
|
||||
for (let scenario = 0; scenario < 40; scenario++) {
|
||||
const memory = new MemoryTimelineBackend();
|
||||
const sqlite = new SqliteTimelineBackend(openTestTimelineDatabase());
|
||||
const backends = [memory, sqlite] as const;
|
||||
for (const backend of backends) backend.create(scope, { epoch: "e" });
|
||||
let turn = 0;
|
||||
for (let step = 0; step < 120; step++) {
|
||||
const roll = random(20);
|
||||
const identity = String(random(6));
|
||||
const text = `${scenario}-${step}`;
|
||||
if (roll === 0) {
|
||||
const prompts = memory.promptRows(scope);
|
||||
if (prompts.length > 0) {
|
||||
const retireFromSeq = prompts[random(prompts.length)].seqStart;
|
||||
const results = backends.map((backend) =>
|
||||
backend.retire(scope, { retireFromSeq, selectChildren: () => [] }),
|
||||
);
|
||||
expect(results[1]).toEqual(results[0]);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (roll === 1) {
|
||||
const turnId = random(2) === 0 ? String(turn) : undefined;
|
||||
const metrics = [{ name: "tokens", value: step }] as never;
|
||||
const results = backends.map((backend) =>
|
||||
backend.stampTurnMetrics(scope, metrics, turnId === undefined ? {} : { turnId }),
|
||||
);
|
||||
expect(results[1]).toEqual(results[0]);
|
||||
continue;
|
||||
}
|
||||
if (roll === 2) {
|
||||
const clientMessageId = `client-${random(step + 1)}`;
|
||||
const results = backends.map((backend) =>
|
||||
backend.attachProviderMessageId(scope, clientMessageId, `provider-${step}`),
|
||||
);
|
||||
expect(results[1]).toEqual(results[0]);
|
||||
continue;
|
||||
}
|
||||
if (random(8) === 0) turn += 1;
|
||||
const items: AgentTimelineItem[] = [
|
||||
{ type: "user_message", text, messageId: `m-${step}`, clientMessageId: `client-${step}` },
|
||||
{ type: "user_message", text, messageId: `m-${step}` },
|
||||
{ type: "assistant_message", text },
|
||||
{ type: "assistant_message", text, messageId: identity },
|
||||
{ type: "reasoning", text },
|
||||
tool(identity, random(2) === 0 ? "running" : "completed", text),
|
||||
{
|
||||
type: "plugin",
|
||||
id: identity,
|
||||
pluginId: "test",
|
||||
kind: "state",
|
||||
version: 1,
|
||||
data: { text },
|
||||
},
|
||||
];
|
||||
const next = entry(items[random(items.length)], { turnId: String(turn) });
|
||||
const retired = backends.map((backend) => backend.isRetired(scope, next));
|
||||
expect(retired[1]).toBe(retired[0]);
|
||||
const results = backends.map((backend) => backend.append(scope, [next]));
|
||||
expect(results[1]).toEqual(results[0]);
|
||||
}
|
||||
expectSameHistory(memory, sqlite);
|
||||
// Seeding from projected rows, as an import does, keeps both in step too.
|
||||
const rows = memory.readRows(scope);
|
||||
for (const backend of backends) backend.create({ agentId: "seeded" }, { rows, epoch: "e" });
|
||||
expectSameHistory(memory, sqlite, { agentId: "seeded" });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
function expectSameHistory(
|
||||
memory: MemoryTimelineBackend,
|
||||
sqlite: SqliteTimelineBackend,
|
||||
target: TimelineScope = scope,
|
||||
): void {
|
||||
expect(sqlite.head(target)).toEqual(memory.head(target));
|
||||
expect(sqlite.readRows(target)).toEqual(memory.readRows(target));
|
||||
expect(sqlite.retiredRows(target)).toEqual(memory.retiredRows(target));
|
||||
expect(sqlite.promptRows(target)).toEqual(memory.promptRows(target));
|
||||
expect(sqlite.lastItem(target)).toEqual(memory.lastItem(target));
|
||||
expect(sqlite.lastAssistantMessage(target)).toEqual(memory.lastAssistantMessage(target));
|
||||
const maxSeq = memory.head(target)!.seq;
|
||||
for (const direction of ["tail", "before", "after"] as const) {
|
||||
for (const wholeTurns of [false, true]) {
|
||||
for (const limit of [0, 1, 3, 10]) {
|
||||
for (const cursorSeq of [0, 1, Math.floor(maxSeq / 3), Math.floor(maxSeq / 2), maxSeq]) {
|
||||
const options: AgentTimelineFetchOptions = {
|
||||
direction,
|
||||
wholeTurns,
|
||||
limit,
|
||||
cursor: { epoch: "e", seq: cursorSeq },
|
||||
};
|
||||
expect({ options, page: sqlite.fetch(target, options) }).toEqual({
|
||||
options,
|
||||
page: memory.fetch(target, options),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
describe("SQLite timeline durability", () => {
|
||||
it("keeps rows, turns, metrics, provider ids, rewinds, and children across a restart", async () => {
|
||||
const file = nextTestDatabasePath();
|
||||
let database = openTestTimelineDatabase(file);
|
||||
let timeline = new AgentTimeline(new SqliteTimelineBackend(database));
|
||||
await timeline.create(scope, { epoch: "e" });
|
||||
await timeline.ingest(
|
||||
scope,
|
||||
entry(
|
||||
{ type: "user_message", text: "first", messageId: "m1", clientMessageId: "c1" },
|
||||
{ turnId: "t1" },
|
||||
),
|
||||
);
|
||||
await timeline.attachProviderMessageId(scope, "c1", "p1");
|
||||
await timeline.append(scope, [
|
||||
entry({ type: "assistant_message", text: "Hel" }, { turnId: "t1" }),
|
||||
entry({ type: "assistant_message", text: "lo" }, { turnId: "t1" }),
|
||||
entry(tool("spawn", "running"), { turnId: "t1" }),
|
||||
]);
|
||||
await timeline.stampTurnMetrics(scope, [{ name: "tokens", value: 3 }] as never, {
|
||||
turnId: "t1",
|
||||
});
|
||||
await timeline.append(scope, [
|
||||
entry({ type: "user_message", text: "second", messageId: "m2" }, { turnId: "t2" }),
|
||||
entry({ type: "assistant_message", text: "Done" }, { turnId: "t2" }),
|
||||
]);
|
||||
const child: TimelineScope = { agentId: "agent", subagentId: "child" };
|
||||
await timeline.recordChild(child, () => descriptor("child", "spawn"));
|
||||
await timeline.recordChildEntries(child, [entry({ type: "assistant_message", text: "kid" })]);
|
||||
const intent = await timeline.beginRewind(scope, "m1");
|
||||
await timeline.recordRewindCut(scope, intent.id, { kind: "at_target" });
|
||||
const rowsBefore = await timeline.readRows(scope);
|
||||
const headBefore = await timeline.describe(scope);
|
||||
await timeline.close();
|
||||
database.close();
|
||||
|
||||
database = openTestTimelineDatabase(file);
|
||||
timeline = new AgentTimeline(new SqliteTimelineBackend(database));
|
||||
expect(await timeline.describe(scope)).toEqual(headBefore);
|
||||
expect(headBefore?.rewind).toMatchObject({ id: intent.id, cut: { kind: "at_target" } });
|
||||
const rowsAfter = await timeline.readRows(scope);
|
||||
expect(rowsAfter).toEqual(rowsBefore);
|
||||
expect(rowsAfter.map((row) => row.turnId)).toEqual(["t1", "t1", "t1", "t2", "t2"]);
|
||||
expect(rowsAfter[0].providerMessageId).toBe("p1");
|
||||
expect(rowsAfter[1]).toMatchObject({
|
||||
item: { text: "Hello" },
|
||||
turnMetrics: [{ name: "tokens", value: 3 }],
|
||||
});
|
||||
// Turn ids survive, so a whole-turns tail still stops at the last turn (#10030).
|
||||
const lastTurn = await timeline.fetch(scope, { direction: "tail", limit: 1, wholeTurns: true });
|
||||
expect(lastTurn.rows.map((row) => row.turnId)).toEqual(["t2", "t2"]);
|
||||
expect(await timeline.listChildren("agent")).toEqual([
|
||||
{ subagentId: "child", descriptor: descriptor("child", "spawn"), retired: false },
|
||||
]);
|
||||
expect((await timeline.readRows(child)).map((row) => row.item)).toEqual([
|
||||
{ type: "assistant_message", text: "kid" },
|
||||
]);
|
||||
|
||||
// The rewind opened before the restart completes after it.
|
||||
const completion = await timeline.completeRewind(scope, intent.id);
|
||||
expect(completion).toMatchObject({ kind: "retired", retiredChildIds: ["child"] });
|
||||
await timeline.close();
|
||||
database.close();
|
||||
|
||||
database = openTestTimelineDatabase(file);
|
||||
const backend = new SqliteTimelineBackend(database);
|
||||
timeline = new AgentTimeline(backend);
|
||||
expect(await timeline.readRows(scope)).toEqual([]);
|
||||
expect(backend.retiredRows(scope)).toEqual(rowsBefore);
|
||||
expect(await timeline.describe(scope)).toMatchObject({ retirementCount: 1, rewind: null });
|
||||
expect(await timeline.listChildren("agent")).toMatchObject([
|
||||
{ subagentId: "child", retired: true },
|
||||
]);
|
||||
// Late output of a retired tool call is still dropped.
|
||||
expect(await timeline.ingest(scope, entry(tool("spawn", "completed")))).toEqual({
|
||||
kind: "dropped",
|
||||
});
|
||||
const tail = await timeline.fetch(scope, { direction: "tail" });
|
||||
expect(tail.retirements).toEqual([{ seq: 7, retireFromSeq: 1 }]);
|
||||
await timeline.close();
|
||||
database.close();
|
||||
});
|
||||
|
||||
it("finishes queued writes on close, then refuses new ones", async () => {
|
||||
const file = nextTestDatabasePath();
|
||||
let database = openTestTimelineDatabase(file);
|
||||
const timeline = new AgentTimeline(
|
||||
new DeferredTimelineBackend(new SqliteTimelineBackend(database)),
|
||||
);
|
||||
await timeline.create(scope, { epoch: "e" });
|
||||
const writes = ["a", "b", "c"].map((text) =>
|
||||
timeline.append(scope, [entry({ type: "user_message", text })]),
|
||||
);
|
||||
await timeline.close();
|
||||
await expect(
|
||||
timeline.append(scope, [entry({ type: "user_message", text: "late" })]),
|
||||
).rejects.toBeInstanceOf(TimelineClosedError);
|
||||
// Nothing is left to wait for, so code that orders itself behind the timeline still runs.
|
||||
await expect(timeline.settled(scope)).resolves.toBeUndefined();
|
||||
await Promise.all(writes);
|
||||
database.close();
|
||||
|
||||
database = openTestTimelineDatabase(file);
|
||||
const rows = new SqliteTimelineBackend(database).readRows(scope);
|
||||
expect(rows.map((row) => row.item)).toMatchObject([
|
||||
{ text: "a" },
|
||||
{ text: "b" },
|
||||
{ text: "c" },
|
||||
]);
|
||||
database.close();
|
||||
});
|
||||
});
|
||||
|
||||
describe("SQLite timeline write failures", () => {
|
||||
function failOn(database: DaemonDatabase, table: string): void {
|
||||
database.write((sql) =>
|
||||
sql.exec(
|
||||
`CREATE TRIGGER fail_${table} BEFORE INSERT ON ${table} ` +
|
||||
"BEGIN SELECT RAISE(ABORT, 'disk full'); END",
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
it("leaves no part of a failed append", () => {
|
||||
const database = openTestTimelineDatabase();
|
||||
const backend = new SqliteTimelineBackend(database);
|
||||
backend.create(scope, { epoch: "e" });
|
||||
backend.append(scope, [entry({ type: "user_message", text: "kept" })]);
|
||||
const before = dumpTables(database);
|
||||
failOn(database, "timeline_text");
|
||||
// The prompt is written before the reply's text fails.
|
||||
expect(() =>
|
||||
backend.append(scope, [
|
||||
entry({ type: "user_message", text: "lost" }),
|
||||
entry({ type: "assistant_message", text: "lost" }),
|
||||
]),
|
||||
).toThrow(/disk full/);
|
||||
expect(dumpTables(database)).toEqual(before);
|
||||
expect(backend.head(scope)).toMatchObject({ seq: 1, size: 1 });
|
||||
database.close();
|
||||
});
|
||||
|
||||
it("leaves no part of a failed retirement", () => {
|
||||
const database = openTestTimelineDatabase();
|
||||
const backend = new SqliteTimelineBackend(database);
|
||||
backend.create(scope, { epoch: "e" });
|
||||
backend.append(scope, [
|
||||
entry({ type: "user_message", text: "one", messageId: "m1" }, { turnId: "t1" }),
|
||||
entry(tool("call", "running"), { turnId: "t1" }),
|
||||
]);
|
||||
backend.setChild({ agentId: "agent", subagentId: "child" }, descriptor("child", "call"));
|
||||
backend.setRewind(scope, { id: "r", messageId: "m1", targetSeq: 1 });
|
||||
const before = dumpTables(database);
|
||||
failOn(database, "timeline_retirements");
|
||||
// Rows, keys, ranges, and the child are written before the retirement fails.
|
||||
expect(() =>
|
||||
backend.retire(scope, { retireFromSeq: 1, selectChildren: () => ["child"] }),
|
||||
).toThrow(/disk full/);
|
||||
expect(dumpTables(database)).toEqual(before);
|
||||
expect(backend.isRetired(scope, entry(tool("call", "completed")))).toBe(false);
|
||||
database.close();
|
||||
});
|
||||
});
|
||||
|
||||
describe("SQLite timeline reads", () => {
|
||||
function longHistory(): { database: CountingDatabase; backend: SqliteTimelineBackend } {
|
||||
const database = new CountingDatabase(openTestTimelineDatabase());
|
||||
const backend = new SqliteTimelineBackend(database);
|
||||
backend.create(scope, { epoch: "e" });
|
||||
for (let batch = 0; batch < 50; batch++) {
|
||||
const entries: TimelineEntry[] = [];
|
||||
for (let index = 0; index < 10; index++) {
|
||||
const turnId = `t${batch * 10 + index}`;
|
||||
entries.push(
|
||||
entry({ type: "user_message", text: turnId, messageId: turnId }, { turnId }),
|
||||
entry(tool(`${turnId}-call`, "completed"), { turnId }),
|
||||
entry({ type: "assistant_message", text: "a" }, { turnId }),
|
||||
entry({ type: "assistant_message", text: "b" }, { turnId }),
|
||||
);
|
||||
}
|
||||
backend.append(scope, entries);
|
||||
}
|
||||
return { database, backend };
|
||||
}
|
||||
|
||||
it("reads a bounded slice of a long history for a page", () => {
|
||||
const { database, backend } = longHistory();
|
||||
expect(backend.head(scope)).toMatchObject({ seq: 2000, size: 1500 });
|
||||
const pages: AgentTimelineFetchOptions[] = [
|
||||
{ direction: "tail", limit: 20 },
|
||||
{ direction: "tail", limit: 20, wholeTurns: true },
|
||||
{ direction: "before", limit: 20, cursor: { epoch: "e", seq: 1000 } },
|
||||
{ direction: "before", limit: 20, cursor: { epoch: "e", seq: 1000 }, wholeTurns: true },
|
||||
{ direction: "after", limit: 20, cursor: { epoch: "e", seq: 1000 } },
|
||||
];
|
||||
for (const options of pages) {
|
||||
database.rowsRead = 0;
|
||||
expect(backend.fetch(scope, options).rows.length).toBeGreaterThanOrEqual(20);
|
||||
expect(database.rowsRead, JSON.stringify(options)).toBeLessThan(150);
|
||||
}
|
||||
// The chat outline lists every prompt; it reads none of the 1,000 other rows.
|
||||
database.rowsRead = 0;
|
||||
expect(backend.promptRows(scope)).toHaveLength(500);
|
||||
expect(database.rowsRead).toBeLessThanOrEqual(501);
|
||||
for (const read of [
|
||||
() => backend.head(scope),
|
||||
() => backend.lastItem(scope),
|
||||
() => backend.lastAssistantMessage(scope),
|
||||
() => backend.isRetired(scope, entry(tool("t3-call", "completed"))),
|
||||
() => backend.findSubmittedPrompt(scope, "absent"),
|
||||
() => backend.stampTurnMetrics(scope, [], { turnId: "t499" }),
|
||||
]) {
|
||||
database.rowsRead = 0;
|
||||
read();
|
||||
expect(database.rowsRead).toBeLessThan(20);
|
||||
}
|
||||
database.close();
|
||||
});
|
||||
|
||||
it("writes a streamed chunk without rewriting the message's earlier text", () => {
|
||||
const database = openTestTimelineDatabase();
|
||||
const backend = new SqliteTimelineBackend(database);
|
||||
backend.create(scope, { epoch: "e" });
|
||||
const storedRowSize = () =>
|
||||
database.read(
|
||||
(sql) => sql.get<{ size: number }>("SELECT length(row) AS size FROM timeline_rows")!.size,
|
||||
);
|
||||
for (let chunk = 0; chunk < 100; chunk++) {
|
||||
backend.append(scope, [entry({ type: "assistant_message", text: "x".repeat(1000) })]);
|
||||
}
|
||||
// The row holds only its metadata; the 100,000 characters of text are chunks beside it.
|
||||
expect(storedRowSize()).toBeLessThan(300);
|
||||
expect(backend.lastAssistantMessage(scope)).toHaveLength(100_000);
|
||||
database.close();
|
||||
});
|
||||
|
||||
it("reads back streamed text exactly, including a NUL and a pair split across chunks", () => {
|
||||
const file = nextTestDatabasePath();
|
||||
const chunks = ["before\0after ", "\ud83d", "\ude00 end"];
|
||||
const writer = openTestTimelineDatabase(file);
|
||||
const written = new SqliteTimelineBackend(writer);
|
||||
written.create(scope, { epoch: "e" });
|
||||
for (const text of chunks) {
|
||||
written.append(scope, [entry({ type: "assistant_message", text })]);
|
||||
}
|
||||
writer.close();
|
||||
|
||||
const reopened = new SqliteTimelineBackend(openTestTimelineDatabase(file));
|
||||
expect(reopened.readRows(scope).map((row) => row.item)).toEqual([
|
||||
{ type: "assistant_message", text: chunks.join("") },
|
||||
]);
|
||||
});
|
||||
|
||||
it("reads the chat outline's prompts and cursor without a tool's interleaved rows", async () => {
|
||||
const database = new CountingDatabase(openTestTimelineDatabase());
|
||||
const timeline = new AgentTimeline(new SqliteTimelineBackend(database));
|
||||
await timeline.create(scope, { epoch: "e" });
|
||||
// The tool row spans everything between its start and its update, so a one-row tail page
|
||||
// covers all 200 tool rows in between.
|
||||
const entries: TimelineEntry[] = [
|
||||
entry({ type: "user_message", text: "run it", messageId: "p1" }),
|
||||
entry(tool("long", "running")),
|
||||
];
|
||||
for (let index = 0; index < 200; index++) entries.push(entry(tool(`t${index}`, "completed")));
|
||||
entries.push(entry(tool("long", "completed")));
|
||||
await timeline.append(scope, entries);
|
||||
|
||||
database.rowsRead = 0;
|
||||
const outline = await timeline.readPrompts(scope);
|
||||
expect(outline.head).toMatchObject({ epoch: "e", retirementCount: 0 });
|
||||
expect(outline.rows.map((row) => row.item)).toEqual([entries[0]!.item]);
|
||||
expect(database.rowsRead).toBeLessThan(5);
|
||||
await timeline.close();
|
||||
database.close();
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,8 @@
|
||||
import { setImmediate as nextTurn } from "node:timers/promises";
|
||||
import { onTestFinished } from "vitest";
|
||||
import { createTestLogger } from "../../../test-utils/test-logger.js";
|
||||
import { nextTestDatabasePath } from "../../test-utils/test-database-path.js";
|
||||
import { openDaemonDatabase, type DaemonDatabase } from "../../database/index.js";
|
||||
import type { AgentMetric, AgentTimelineItem } from "../agent-sdk-types.js";
|
||||
import type {
|
||||
AgentTimelineFetchOptions,
|
||||
@@ -12,16 +16,18 @@ import type {
|
||||
MaybePromise,
|
||||
RetiredChildSelector,
|
||||
TimelineBackendAppendResult,
|
||||
TimelineBackendCommitProviderSwitchResult,
|
||||
TimelineBackendRetireResult,
|
||||
TimelineChild,
|
||||
TimelineEntry,
|
||||
TimelineHead,
|
||||
TimelinePrompt,
|
||||
TimelineProviderSwitchIntent,
|
||||
TimelineRewindIntent,
|
||||
TimelineScope,
|
||||
TimelineSeed,
|
||||
} from "./internal/backend.js";
|
||||
import { MemoryTimelineBackend } from "./internal/memory-backend.js";
|
||||
import { SqliteTimelineBackend, timelineSchema } from "./internal/sqlite-backend.js";
|
||||
|
||||
/**
|
||||
* Testing entry point of the timeline module. Production code imports `./index.js`.
|
||||
@@ -39,18 +45,37 @@ export interface InspectableTimelineBackend extends AgentTimelineBackend {
|
||||
export const TIMELINE_CONTRACT_BACKENDS: ReadonlyArray<{
|
||||
name: string;
|
||||
create: () => InspectableTimelineBackend;
|
||||
}> = [{ name: "memory", create: () => new MemoryTimelineBackend() }];
|
||||
}> = [
|
||||
{ name: "memory", create: () => new MemoryTimelineBackend() },
|
||||
{ name: "sqlite", create: () => new SqliteTimelineBackend(openTestTimelineDatabase()) },
|
||||
];
|
||||
|
||||
/**
|
||||
* Opens a fresh file-backed timeline database, closed when the calling test finishes, in a
|
||||
* directory removed when the process exits. Pass the path of an earlier database to reopen it, as
|
||||
* a daemon restart does.
|
||||
*/
|
||||
export function openTestTimelineDatabase(file?: string): DaemonDatabase {
|
||||
const database = openDaemonDatabase({
|
||||
path: file ?? nextTestDatabasePath(),
|
||||
modules: [timelineSchema],
|
||||
logger: createTestLogger(),
|
||||
});
|
||||
onTestFinished(() => database.close());
|
||||
return database;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps a backend: defers every call by a turn of the event loop, the shape of an I/O-backed
|
||||
* store, records the committed appends and whole-history reads, and fails the next append or
|
||||
* retirement on request.
|
||||
* store, records the committed appends and whole-history reads, and fails the next append,
|
||||
* retirement, or metrics stamp on request.
|
||||
*/
|
||||
export class DeferredTimelineBackend implements AgentTimelineBackend {
|
||||
readonly appends: TimelineEntry[][] = [];
|
||||
readRowsCalls = 0;
|
||||
failNextAppend = false;
|
||||
failNextRetire = false;
|
||||
failNextStampTurnMetrics = false;
|
||||
|
||||
constructor(private readonly inner: InspectableTimelineBackend = new MemoryTimelineBackend()) {}
|
||||
|
||||
@@ -85,12 +110,27 @@ export class DeferredTimelineBackend implements AgentTimelineBackend {
|
||||
isRetired(scope: TimelineScope, entry: TimelineEntry): Promise<boolean> {
|
||||
return this.defer(() => this.inner.isRetired(scope, entry));
|
||||
}
|
||||
prompts(scope: TimelineScope): Promise<TimelinePrompt[]> {
|
||||
return this.defer(() => this.inner.prompts(scope));
|
||||
promptRows(scope: TimelineScope): Promise<ProjectedTimelineRow[]> {
|
||||
return this.defer(() => this.inner.promptRows(scope));
|
||||
}
|
||||
setRewind(scope: TimelineScope, rewind: TimelineRewindIntent | null): Promise<TimelineHead> {
|
||||
return this.defer(() => this.inner.setRewind(scope, rewind));
|
||||
}
|
||||
setProviderSwitch(
|
||||
scope: TimelineScope,
|
||||
providerSwitch: TimelineProviderSwitchIntent | null,
|
||||
): Promise<TimelineHead> {
|
||||
return this.defer(() => this.inner.setProviderSwitch(scope, providerSwitch));
|
||||
}
|
||||
commitProviderSwitch(
|
||||
scope: TimelineScope,
|
||||
input: {
|
||||
markerEntry: TimelineEntry;
|
||||
nextIntent: TimelineProviderSwitchIntent | null;
|
||||
},
|
||||
): Promise<TimelineBackendCommitProviderSwitchResult> {
|
||||
return this.defer(() => this.inner.commitProviderSwitch(scope, input));
|
||||
}
|
||||
children(agentId: string): Promise<TimelineChild[]> {
|
||||
return this.defer(() => this.inner.children(agentId));
|
||||
}
|
||||
@@ -120,9 +160,10 @@ export class DeferredTimelineBackend implements AgentTimelineBackend {
|
||||
scope: TimelineScope,
|
||||
clientMessageId: string,
|
||||
providerMessageId: string,
|
||||
options?: { providerPromptText?: string },
|
||||
): Promise<AgentTimelineRow | null> {
|
||||
return this.defer(() =>
|
||||
this.inner.attachProviderMessageId(scope, clientMessageId, providerMessageId),
|
||||
this.inner.attachProviderMessageId(scope, clientMessageId, providerMessageId, options),
|
||||
);
|
||||
}
|
||||
stampTurnMetrics(
|
||||
@@ -130,7 +171,13 @@ export class DeferredTimelineBackend implements AgentTimelineBackend {
|
||||
metrics: AgentMetric[],
|
||||
options?: { turnId?: string },
|
||||
): Promise<ProjectedTimelineRow | null> {
|
||||
return this.defer(() => this.inner.stampTurnMetrics(scope, metrics, options));
|
||||
return this.defer(() => {
|
||||
if (this.failNextStampTurnMetrics) {
|
||||
this.failNextStampTurnMetrics = false;
|
||||
throw new Error("disk full");
|
||||
}
|
||||
return this.inner.stampTurnMetrics(scope, metrics, options);
|
||||
});
|
||||
}
|
||||
findSubmittedPrompt(
|
||||
scope: TimelineScope,
|
||||
|
||||
@@ -23,6 +23,7 @@ const INBOUND_PERMISSION = {
|
||||
"agent.background_work.list.request": "workspace.read",
|
||||
"agent.background_work.stop.request": ["workspace.write", "hub.execute"],
|
||||
"agent.provider_subagents.timeline.get.request": "workspace.read",
|
||||
"agent.provider.switch.request": "workspace.write",
|
||||
"agent.rewind.request": "workspace.write",
|
||||
"agent.skills.get_status.request": "daemon.read",
|
||||
"agent.skills.import_legacy_selection.request": "daemon.manage",
|
||||
@@ -270,6 +271,7 @@ const OUTBOUND_PERMISSION = {
|
||||
"agent.background_work.list.response": "workspace.read",
|
||||
"agent.background_work.stop.response": ["workspace.write", "hub.execute"],
|
||||
"agent.background_work.update": "workspace.read",
|
||||
"agent.provider.switch.response": "workspace.write",
|
||||
"agent.rewind.response": "workspace.write",
|
||||
"agent.skills.get_status.response": "daemon.read",
|
||||
"agent.skills.import_legacy_selection.response": "daemon.manage",
|
||||
|
||||
@@ -7,7 +7,7 @@ import type { Query } from "@anthropic-ai/claude-agent-sdk";
|
||||
import { ClaudeAgentClient } from "./agent/providers/claude/agent.js";
|
||||
import http from "node:http";
|
||||
import path from "node:path";
|
||||
import { access, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { access, chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import pino from "pino";
|
||||
import { afterEach, describe, expect, test, vi } from "vitest";
|
||||
import { WebSocket } from "ws";
|
||||
@@ -22,7 +22,7 @@ import {
|
||||
createPersistedWorkspaceRecord,
|
||||
} from "./workspace-registry.js";
|
||||
import { AgentStorage, type StoredAgentRecord } from "./agent/agent-storage.js";
|
||||
import { ensureAgentLoaded } from "./agent/agent-loading.js";
|
||||
import { ensureAgentLoaded, loadAgentHistory } from "./agent/agent-loading.js";
|
||||
import { AgentManagerShuttingDownError } from "./agent/agent-manager.js";
|
||||
import { hashDaemonPassword } from "./auth.js";
|
||||
import { generateLocalPairingOffer } from "./pairing-offer.js";
|
||||
@@ -94,63 +94,57 @@ describe("paseo daemon bootstrap", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps timeline activity in memory and removes obsolete timeline files at startup", async () => {
|
||||
const paseoHomeRoot = await mkdtemp(path.join(os.tmpdir(), "paseo-timeline-cleanup-"));
|
||||
test("stores timelines in paseo.db and serves them after a restart without loading the agent", async () => {
|
||||
const paseoHomeRoot = await mkdtemp(path.join(os.tmpdir(), "paseo-timeline-restart-"));
|
||||
const paseoHome = path.join(paseoHomeRoot, ".paseo");
|
||||
const obsoleteTimelineDirectory = path.join(paseoHome, "agent-timelines");
|
||||
const agentCwd = await mkdtemp(path.join(os.tmpdir(), "paseo-timeline-agent-"));
|
||||
await mkdir(obsoleteTimelineDirectory, { recursive: true });
|
||||
await writeFile(path.join(obsoleteTimelineDirectory, "obsolete.json"), "{}\n", "utf-8");
|
||||
|
||||
const daemonHandle = await createTestPaseoDaemon({ paseoHomeRoot, cleanup: false });
|
||||
try {
|
||||
await expect(access(obsoleteTimelineDirectory)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
const first = await createTestPaseoDaemon({ paseoHomeRoot, cleanup: false });
|
||||
let agentId: string;
|
||||
try {
|
||||
await expect(access(obsoleteTimelineDirectory)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
const agent = await first.daemon.agentManager.createAgent(
|
||||
{ provider: "codex", cwd: agentCwd },
|
||||
undefined,
|
||||
{ workspaceId: undefined },
|
||||
);
|
||||
agentId = agent.id;
|
||||
await first.daemon.agentManager.appendTimelineItem(agent.id, {
|
||||
type: "assistant_message",
|
||||
text: "kept across the restart",
|
||||
});
|
||||
await first.daemon.agentManager.flush();
|
||||
} finally {
|
||||
await first.close();
|
||||
}
|
||||
await access(path.join(paseoHome, "paseo.db"));
|
||||
|
||||
const agent = await daemonHandle.daemon.agentManager.createAgent(
|
||||
{ provider: "codex", cwd: agentCwd },
|
||||
undefined,
|
||||
{ workspaceId: undefined },
|
||||
);
|
||||
await daemonHandle.daemon.agentManager.appendTimelineItem(agent.id, {
|
||||
type: "assistant_message",
|
||||
text: "timeline stays in memory",
|
||||
});
|
||||
await daemonHandle.daemon.agentManager.flush();
|
||||
|
||||
await expect(access(obsoleteTimelineDirectory)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
const second = await createTestPaseoDaemon({ paseoHomeRoot, cleanup: false });
|
||||
try {
|
||||
const { agentManager, agentStorage } = second.daemon;
|
||||
const source = await loadAgentHistory(agentId, {
|
||||
agentManager,
|
||||
agentStorage,
|
||||
logger: pino({ level: "silent" }),
|
||||
purpose: "history",
|
||||
});
|
||||
expect(source.kind).toBe("stored");
|
||||
const page = await agentManager.fetchTimeline(agentId, { direction: "tail" });
|
||||
expect(page.rows.map((row) => row.item)).toContainEqual({
|
||||
type: "assistant_message",
|
||||
text: "kept across the restart",
|
||||
});
|
||||
expect(agentManager.getAgent(agentId)).toBeNull();
|
||||
} finally {
|
||||
await second.close();
|
||||
}
|
||||
} finally {
|
||||
await daemonHandle.close();
|
||||
await Promise.all([
|
||||
rm(paseoHomeRoot, { recursive: true, force: true }),
|
||||
rm(agentCwd, { recursive: true, force: true }),
|
||||
]);
|
||||
}
|
||||
});
|
||||
|
||||
test("does not create a timeline directory for live timeline activity", async () => {
|
||||
const paseoHomeRoot = await mkdtemp(path.join(os.tmpdir(), "paseo-timeline-memory-"));
|
||||
const agentCwd = await mkdtemp(path.join(os.tmpdir(), "paseo-timeline-agent-"));
|
||||
const daemonHandle = await createTestPaseoDaemon({ paseoHomeRoot, cleanup: false });
|
||||
const timelineDirectory = path.join(daemonHandle.paseoHome, "agent-timelines");
|
||||
try {
|
||||
const agent = await daemonHandle.daemon.agentManager.createAgent(
|
||||
{ provider: "codex", cwd: agentCwd },
|
||||
undefined,
|
||||
{ workspaceId: undefined },
|
||||
);
|
||||
await daemonHandle.daemon.agentManager.appendTimelineItem(agent.id, {
|
||||
type: "assistant_message",
|
||||
text: "timeline stays in memory",
|
||||
});
|
||||
await daemonHandle.daemon.agentManager.flush();
|
||||
|
||||
await expect(access(timelineDirectory)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
} finally {
|
||||
await daemonHandle.close();
|
||||
await Promise.all([
|
||||
rm(paseoHomeRoot, { recursive: true, force: true }),
|
||||
rm(agentCwd, { recursive: true, force: true }),
|
||||
]);
|
||||
// Windows can hold a closed daemon's directory handles briefly, as in `removeDirs`.
|
||||
const retry = { recursive: true, force: true, maxRetries: 3, retryDelay: 100 };
|
||||
await Promise.all([rm(paseoHomeRoot, retry), rm(agentCwd, retry)]);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -441,6 +435,62 @@ describe("paseo daemon bootstrap", () => {
|
||||
}
|
||||
});
|
||||
|
||||
// SQLite removes paseo.db's WAL file when the last connection closes cleanly.
|
||||
test("closes paseo.db when the daemon fails to start", async () => {
|
||||
const paseoHomeRoot = await mkdtemp(path.join(os.tmpdir(), "paseo-failed-start-"));
|
||||
const paseoHome = path.join(paseoHomeRoot, ".paseo");
|
||||
// A directory where the keypair file belongs makes construction throw after paseo.db opens.
|
||||
const keyPairPath = path.join(paseoHome, "daemon-keypair.json");
|
||||
await mkdir(path.join(keyPairPath, "blocked"), { recursive: true });
|
||||
const config: PaseoDaemonConfig = {
|
||||
listen: "127.0.0.1:0",
|
||||
paseoHome,
|
||||
corsAllowedOrigins: [],
|
||||
hostnames: true,
|
||||
mcpEnabled: false,
|
||||
mcpDebug: false,
|
||||
agentClients: createTestAgentClients(),
|
||||
agentStoragePath: path.join(paseoHome, "agents"),
|
||||
relayEnabled: false,
|
||||
appBaseUrl: "https://app.paseo.sh",
|
||||
openai: undefined,
|
||||
speech: undefined,
|
||||
};
|
||||
try {
|
||||
await expect(
|
||||
createPaseoDaemon(config, pino({ level: "silent" }), {
|
||||
builtinPlugins: new BuiltinPluginLoader(undefined, []),
|
||||
lazyTerminalWorker: true,
|
||||
}),
|
||||
).rejects.toThrow();
|
||||
await access(path.join(paseoHome, "paseo.db"));
|
||||
await expect(access(path.join(paseoHome, "paseo.db-wal"))).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
} finally {
|
||||
// The keypair loader narrows the directory's mode to a private file's.
|
||||
await chmod(keyPairPath, 0o700);
|
||||
await rm(paseoHomeRoot, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("closes paseo.db when an earlier shutdown step fails", async () => {
|
||||
const daemonHandle = await createTestPaseoDaemon();
|
||||
const credentialPath = path.join(daemonHandle.paseoHome, "local-credential");
|
||||
try {
|
||||
// A directory where the local credential belongs makes the first shutdown step throw.
|
||||
await rm(credentialPath, { force: true });
|
||||
await mkdir(path.join(credentialPath, "blocked"), { recursive: true });
|
||||
await expect(daemonHandle.daemon.stop()).rejects.toThrow();
|
||||
await expect(access(path.join(daemonHandle.paseoHome, "paseo.db-wal"))).rejects.toMatchObject(
|
||||
{ code: "ENOENT" },
|
||||
);
|
||||
} finally {
|
||||
await rm(credentialPath, { recursive: true, force: true });
|
||||
await daemonHandle.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("rolls back daemon listener when standalone service proxy startup fails", async () => {
|
||||
const occupiedServer = http.createServer((_req, res) => {
|
||||
res.end("occupied");
|
||||
|
||||
@@ -14,9 +14,13 @@ import { describeHookWorkspace } from "./plugins/lifecycle/index.js";
|
||||
import express from "express";
|
||||
import { createServer as createHTTPServer, type IncomingMessage, type ServerResponse } from "http";
|
||||
import { constants, existsSync, unlinkSync } from "fs";
|
||||
import { open, rm, stat } from "fs/promises";
|
||||
import { mkdir, open, rm, stat } from "fs/promises";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { getCachedHostMachineKind, primeHostMachineKind } from "./host-machine-kind.js";
|
||||
import {
|
||||
getCachedHostMachineKind,
|
||||
primeHostMachineKind,
|
||||
type HostMachineKind,
|
||||
} from "./host-machine-kind.js";
|
||||
import { getHostName } from "./host-name.js";
|
||||
import path from "node:path";
|
||||
import { createMcpHandler } from "@modelcontextprotocol/server";
|
||||
@@ -149,6 +153,12 @@ import type { RequestedSpeechProviders } from "./speech/speech-types.js";
|
||||
import { createSpeechService } from "./speech/speech-runtime.js";
|
||||
import { createSpeechSettingsOwner } from "./speech/speech-settings.js";
|
||||
import { AgentManager } from "./agent/agent-manager.js";
|
||||
import {
|
||||
createStoredAgentTimeline,
|
||||
timelineSchema,
|
||||
type AgentTimeline,
|
||||
} from "./agent/timeline/index.js";
|
||||
import { openDaemonDatabase, type DaemonDatabase } from "./database/index.js";
|
||||
import { AgentStorage } from "./agent/agent-storage.js";
|
||||
import { attachAgentStoragePersistence } from "./persistence-hooks.js";
|
||||
import { createAgentMcpServer } from "./agent/mcp-server.js";
|
||||
@@ -650,6 +660,47 @@ export async function createPaseoDaemon(
|
||||
"Failed to remove obsolete agent timeline data",
|
||||
);
|
||||
});
|
||||
await mkdir(config.paseoHome, { recursive: true });
|
||||
const database = openDaemonDatabase({
|
||||
path: path.join(config.paseoHome, "paseo.db"),
|
||||
modules: [timelineSchema],
|
||||
logger: rootLogger.child({ module: "database" }),
|
||||
});
|
||||
const timeline = createStoredAgentTimeline(database);
|
||||
try {
|
||||
return await assemblePaseoDaemon({
|
||||
config,
|
||||
logger,
|
||||
dependencies,
|
||||
hostMachineKindReady,
|
||||
database,
|
||||
timeline,
|
||||
});
|
||||
} catch (error) {
|
||||
await timeline.close();
|
||||
database.close();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/** What `createPaseoDaemon` opens before assembling the daemon around it. */
|
||||
interface PaseoDaemonAssembly {
|
||||
config: PaseoDaemonConfig;
|
||||
logger: Logger;
|
||||
dependencies: PaseoDaemonDependencies;
|
||||
hostMachineKindReady: Promise<HostMachineKind | null>;
|
||||
database: DaemonDatabase;
|
||||
timeline: AgentTimeline;
|
||||
}
|
||||
|
||||
async function assemblePaseoDaemon({
|
||||
config,
|
||||
logger,
|
||||
dependencies,
|
||||
hostMachineKindReady,
|
||||
database,
|
||||
timeline,
|
||||
}: PaseoDaemonAssembly): Promise<PaseoDaemon> {
|
||||
const bootstrapStart = performance.now();
|
||||
const elapsed = () => `${(performance.now() - bootstrapStart).toFixed(0)}ms`;
|
||||
const daemonVersion = config.daemonVersion ?? resolveDaemonVersion(import.meta.url);
|
||||
@@ -1055,6 +1106,7 @@ export async function createPaseoDaemon(
|
||||
clients: initialAgentManagerState.clients,
|
||||
providerDefinitions: initialAgentManagerState.providerDefinitions,
|
||||
registry: agentStorage,
|
||||
timeline,
|
||||
appendSystemPrompt: config.appendSystemPrompt,
|
||||
onWorkspaceStateMayHaveChanged: ({ cwd }) => {
|
||||
workspaceGitService.onWorkspaceStateMayHaveChanged(cwd);
|
||||
@@ -2059,99 +2111,110 @@ export async function createPaseoDaemon(
|
||||
httpServer.closeAllConnections();
|
||||
await new Promise<void>((resolve) => httpServer.close(() => resolve()));
|
||||
}
|
||||
await timeline.close();
|
||||
database.close();
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
const stop = async (options?: { keepTerminals?: boolean }) => {
|
||||
const keepTerminals = options?.keepTerminals === true;
|
||||
let terminalShutdownError: unknown = null;
|
||||
localCredential = null;
|
||||
await deleteLocalCredential(config.paseoHome);
|
||||
// Stop tracking plugin provider registrations before anything tears plugins
|
||||
// down, so plugin shutdown cannot withdraw a provider from under an agent
|
||||
// that is still open. Plugins themselves are stopped once every session
|
||||
// they serve has been closed, further down.
|
||||
unsubscribePluginProviders();
|
||||
await hubRelationships.stop();
|
||||
workspaceReconciliation.dispose();
|
||||
scriptHealthMonitor.stop();
|
||||
unsubscribeIdleRuntimeCleanup();
|
||||
await idleRuntimeCleanup.close();
|
||||
// Freeze both ingress and registration before taking the agent closure snapshot.
|
||||
wsServer?.prepareForShutdown();
|
||||
await changeRequestWatches.close();
|
||||
await finishSubscriptions.close();
|
||||
await wsServer?.agentMessages.close();
|
||||
agentManager.prepareForShutdown();
|
||||
await restartRecovery.captureRunningAgents();
|
||||
await closeAllAgents(logger, agentManager);
|
||||
await withTimeout({
|
||||
promise: pluginRuntime.drainEvents(),
|
||||
timeoutMs: AGENT_CLOSE_TIMEOUT_MS,
|
||||
label: "drain plugin lifecycle events",
|
||||
}).catch((error) => logger.warn({ err: error }, "Plugin lifecycle events did not finish"));
|
||||
let shutdownFlushTimedOut = false;
|
||||
await withTimeout({
|
||||
promise: agentManager.flushForShutdown(),
|
||||
timeoutMs: AGENT_CLOSE_TIMEOUT_MS,
|
||||
label: "flush agent shutdown tasks",
|
||||
}).catch((error) => {
|
||||
shutdownFlushTimedOut = true;
|
||||
logger.warn({ err: error }, "Agent shutdown tasks did not finish before provider shutdown");
|
||||
});
|
||||
detachAgentStoragePersistence();
|
||||
await agentStorage.flush().catch(() => undefined);
|
||||
await agentProviderRuntime.shutdown();
|
||||
if (shutdownFlushTimedOut) {
|
||||
try {
|
||||
const keepTerminals = options?.keepTerminals === true;
|
||||
let terminalShutdownError: unknown = null;
|
||||
localCredential = null;
|
||||
await deleteLocalCredential(config.paseoHome);
|
||||
// Stop tracking plugin provider registrations before anything tears plugins
|
||||
// down, so plugin shutdown cannot withdraw a provider from under an agent
|
||||
// that is still open. Plugins themselves are stopped once every session
|
||||
// they serve has been closed, further down.
|
||||
unsubscribePluginProviders();
|
||||
await hubRelationships.stop();
|
||||
workspaceReconciliation.dispose();
|
||||
scriptHealthMonitor.stop();
|
||||
unsubscribeIdleRuntimeCleanup();
|
||||
await idleRuntimeCleanup.close();
|
||||
// Freeze both ingress and registration before taking the agent closure snapshot.
|
||||
wsServer?.prepareForShutdown();
|
||||
await changeRequestWatches.close();
|
||||
await finishSubscriptions.close();
|
||||
await wsServer?.agentMessages.close();
|
||||
agentManager.prepareForShutdown();
|
||||
await restartRecovery.captureRunningAgents();
|
||||
await closeAllAgents(logger, agentManager);
|
||||
await withTimeout({
|
||||
promise: pluginRuntime.drainEvents(),
|
||||
timeoutMs: AGENT_CLOSE_TIMEOUT_MS,
|
||||
label: "drain plugin lifecycle events",
|
||||
}).catch((error) => logger.warn({ err: error }, "Plugin lifecycle events did not finish"));
|
||||
let shutdownFlushTimedOut = false;
|
||||
await withTimeout({
|
||||
promise: agentManager.flushForShutdown(),
|
||||
timeoutMs: AGENT_CLOSE_TIMEOUT_MS,
|
||||
label: "flush agent shutdown tasks after provider shutdown",
|
||||
}).catch((error) =>
|
||||
logger.warn({ err: error }, "Agent shutdown tasks did not finish after provider shutdown"),
|
||||
);
|
||||
label: "flush agent shutdown tasks",
|
||||
}).catch((error) => {
|
||||
shutdownFlushTimedOut = true;
|
||||
logger.warn({ err: error }, "Agent shutdown tasks did not finish before provider shutdown");
|
||||
});
|
||||
detachAgentStoragePersistence();
|
||||
await agentStorage.flush().catch(() => undefined);
|
||||
}
|
||||
await pluginRuntime.stopAllPlugins();
|
||||
try {
|
||||
if (keepTerminals) {
|
||||
await terminalManager.detach();
|
||||
logger.info("Terminals left running for the next daemon");
|
||||
} else {
|
||||
await terminalManager.closeTerminals();
|
||||
await agentProviderRuntime.shutdown();
|
||||
if (shutdownFlushTimedOut) {
|
||||
await withTimeout({
|
||||
promise: agentManager.flushForShutdown(),
|
||||
timeoutMs: AGENT_CLOSE_TIMEOUT_MS,
|
||||
label: "flush agent shutdown tasks after provider shutdown",
|
||||
}).catch((error) =>
|
||||
logger.warn(
|
||||
{ err: error },
|
||||
"Agent shutdown tasks did not finish after provider shutdown",
|
||||
),
|
||||
);
|
||||
await agentStorage.flush().catch(() => undefined);
|
||||
}
|
||||
} catch (error) {
|
||||
// Finish the rest of the shutdown, then report it: the supervisor and `daemon stop`
|
||||
// retry the cleanup from the record the reaper kept.
|
||||
terminalShutdownError = error;
|
||||
logger.error({ err: error }, "Terminal shutdown failed");
|
||||
}
|
||||
await speechService.stop();
|
||||
await scheduleService.stop().catch(() => undefined);
|
||||
await relayRuntime?.stop().catch(() => undefined);
|
||||
if (wsServer) {
|
||||
await wsServer.close();
|
||||
}
|
||||
forgeResolver.dispose();
|
||||
await serviceProxy.stopStandalone();
|
||||
// Force-drop remaining sockets so httpServer.close() resolves promptly.
|
||||
// We've already closed wsServer (which sent ws-layer close frames) and
|
||||
// stopped every other service, so anything still attached is a TCP
|
||||
// socket whose higher-level shutdown hasn't fully released it (e.g.
|
||||
// upgraded WS sockets in the closing handshake, or HTTP keep-alive
|
||||
// sockets in CLOSE_WAIT). closeIdleConnections() does not catch
|
||||
// upgraded sockets, so we use closeAllConnections() here.
|
||||
httpServer.closeAllConnections();
|
||||
await new Promise<void>((resolve) => {
|
||||
httpServer.close(() => resolve());
|
||||
});
|
||||
// Clean up socket files
|
||||
if (listenTarget.type === "socket" && existsSync(listenTarget.path)) {
|
||||
unlinkSync(listenTarget.path);
|
||||
}
|
||||
if (terminalShutdownError) {
|
||||
throw terminalShutdownError;
|
||||
await pluginRuntime.stopAllPlugins();
|
||||
try {
|
||||
if (keepTerminals) {
|
||||
await terminalManager.detach();
|
||||
logger.info("Terminals left running for the next daemon");
|
||||
} else {
|
||||
await terminalManager.closeTerminals();
|
||||
}
|
||||
} catch (error) {
|
||||
// Finish the rest of the shutdown, then report it: the supervisor and `daemon stop`
|
||||
// retry the cleanup from the record the reaper kept.
|
||||
terminalShutdownError = error;
|
||||
logger.error({ err: error }, "Terminal shutdown failed");
|
||||
}
|
||||
await speechService.stop();
|
||||
await scheduleService.stop().catch(() => undefined);
|
||||
await relayRuntime?.stop().catch(() => undefined);
|
||||
if (wsServer) {
|
||||
await wsServer.close();
|
||||
}
|
||||
forgeResolver.dispose();
|
||||
await serviceProxy.stopStandalone();
|
||||
// Force-drop remaining sockets so httpServer.close() resolves promptly.
|
||||
// We've already closed wsServer (which sent ws-layer close frames) and
|
||||
// stopped every other service, so anything still attached is a TCP
|
||||
// socket whose higher-level shutdown hasn't fully released it (e.g.
|
||||
// upgraded WS sockets in the closing handshake, or HTTP keep-alive
|
||||
// sockets in CLOSE_WAIT). closeIdleConnections() does not catch
|
||||
// upgraded sockets, so we use closeAllConnections() here.
|
||||
httpServer.closeAllConnections();
|
||||
await new Promise<void>((resolve) => {
|
||||
httpServer.close(() => resolve());
|
||||
});
|
||||
// Clean up socket files
|
||||
if (listenTarget.type === "socket" && existsSync(listenTarget.path)) {
|
||||
unlinkSync(listenTarget.path);
|
||||
}
|
||||
if (terminalShutdownError) {
|
||||
throw terminalShutdownError;
|
||||
}
|
||||
} finally {
|
||||
// A failed shutdown step must not leave paseo.db open for the next daemon.
|
||||
await timeline.close();
|
||||
database.close();
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -25,7 +25,9 @@ afterEach(async () => {
|
||||
await client.close();
|
||||
await sdk.close();
|
||||
await daemon.close();
|
||||
await rm(cwd, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
|
||||
// Windows releases a stopped script's working directory after the process exits; rm's
|
||||
// retries wait up to about 5 s for it.
|
||||
await rm(cwd, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
||||
});
|
||||
|
||||
test("SDK and workspace handles preserve ownership and actual process directories", async () => {
|
||||
|
||||
@@ -0,0 +1,368 @@
|
||||
import { mkdtempSync, rmSync, statSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { createTestLogger } from "../../test-utils/test-logger.js";
|
||||
import {
|
||||
DatabaseClosedError,
|
||||
DatabaseOpenError,
|
||||
DatabaseSchemaTooNewError,
|
||||
openDaemonDatabase,
|
||||
type DaemonDatabase,
|
||||
type ReadSql,
|
||||
type SchemaModule,
|
||||
type WriteSql,
|
||||
} from "./index.js";
|
||||
import { WalCheckpointer } from "./internal/wal-checkpointer.js";
|
||||
|
||||
let directory: string;
|
||||
let databasePath: string;
|
||||
const opened: DaemonDatabase[] = [];
|
||||
|
||||
beforeEach(() => {
|
||||
directory = mkdtempSync(path.join(tmpdir(), "paseo-database-"));
|
||||
databasePath = path.join(directory, "paseo.db");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
for (const database of opened.splice(0)) database.close();
|
||||
rmSync(directory, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function open(modules: readonly SchemaModule[]): DaemonDatabase {
|
||||
const database = openDaemonDatabase({ path: databasePath, modules, logger: createTestLogger() });
|
||||
opened.push(database);
|
||||
return database;
|
||||
}
|
||||
|
||||
function reopen(database: DaemonDatabase, modules: readonly SchemaModule[]): DaemonDatabase {
|
||||
database.close();
|
||||
return open(modules);
|
||||
}
|
||||
|
||||
const notes: SchemaModule = {
|
||||
name: "notes",
|
||||
migrations: [
|
||||
{
|
||||
up: (sql) =>
|
||||
sql.exec("CREATE TABLE notes_items (id INTEGER PRIMARY KEY, text TEXT NOT NULL)"),
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
function count(database: DaemonDatabase, table: string): number {
|
||||
return database.read((sql) => sql.get<{ n: number }>(`SELECT count(*) AS n FROM ${table}`)!.n);
|
||||
}
|
||||
|
||||
function tableNames(database: DaemonDatabase): string[] {
|
||||
return database.read((sql) =>
|
||||
sql
|
||||
.all<{ name: string }>("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name")
|
||||
.map((row) => row.name),
|
||||
);
|
||||
}
|
||||
|
||||
function versions(database: DaemonDatabase) {
|
||||
return database.read((sql) =>
|
||||
sql.all<{ module: string; version: number; min_reader_version: number }>(
|
||||
"SELECT module, version, min_reader_version FROM schema_versions ORDER BY module",
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
describe("opening the daemon database", () => {
|
||||
it("creates the file in WAL mode with foreign keys on", () => {
|
||||
const database = open([notes]);
|
||||
expect(
|
||||
database.read((sql) => ({
|
||||
journal: sql.get<{ journal_mode: string }>("PRAGMA journal_mode")!.journal_mode,
|
||||
foreignKeys: sql.get<{ foreign_keys: number }>("PRAGMA foreign_keys")!.foreign_keys,
|
||||
synchronous: sql.get<{ synchronous: number }>("PRAGMA synchronous")!.synchronous,
|
||||
})),
|
||||
).toEqual({ journal: "wal", foreignKeys: 1, synchronous: 1 });
|
||||
expect(versions(database)).toEqual([{ module: "notes", version: 1, min_reader_version: 1 }]);
|
||||
});
|
||||
|
||||
it("keeps committed rows across a reopen and runs no migration twice", () => {
|
||||
let database = open([notes]);
|
||||
database.write((sql) => sql.run("INSERT INTO notes_items (text) VALUES (?)", "kept"));
|
||||
database = reopen(database, [notes]);
|
||||
expect(database.read((sql) => sql.all("SELECT text FROM notes_items"))).toEqual([
|
||||
{ text: "kept" },
|
||||
]);
|
||||
expect(versions(database)).toEqual([{ module: "notes", version: 1, min_reader_version: 1 }]);
|
||||
});
|
||||
|
||||
it("runs only the pending migrations of a module that gained some", () => {
|
||||
let database = open([notes]);
|
||||
database.write((sql) => sql.run("INSERT INTO notes_items (text) VALUES ('a')"));
|
||||
database = reopen(database, [
|
||||
{
|
||||
name: "notes",
|
||||
migrations: [
|
||||
...notes.migrations,
|
||||
{ up: (sql) => sql.exec("ALTER TABLE notes_items ADD COLUMN pinned INTEGER") },
|
||||
],
|
||||
},
|
||||
]);
|
||||
expect(database.read((sql) => sql.all("SELECT text, pinned FROM notes_items"))).toEqual([
|
||||
{ text: "a", pinned: null },
|
||||
]);
|
||||
expect(versions(database)).toEqual([{ module: "notes", version: 2, min_reader_version: 1 }]);
|
||||
});
|
||||
|
||||
it("migrates several modules independently", () => {
|
||||
const tags: SchemaModule = {
|
||||
name: "tags",
|
||||
migrations: [{ up: (sql) => sql.exec("CREATE TABLE tags_items (name TEXT)") }],
|
||||
};
|
||||
let database = open([notes]);
|
||||
database = reopen(database, [notes, tags]);
|
||||
expect(tableNames(database)).toEqual(["notes_items", "schema_versions", "tags_items"]);
|
||||
expect(versions(database).map((row) => [row.module, row.version])).toEqual([
|
||||
["notes", 1],
|
||||
["tags", 1],
|
||||
]);
|
||||
});
|
||||
|
||||
it("rolls every migration back when one fails, so the next open retries from the same state", () => {
|
||||
const failing: SchemaModule = {
|
||||
name: "notes",
|
||||
migrations: [
|
||||
...notes.migrations,
|
||||
{
|
||||
up: (sql) => {
|
||||
sql.exec("CREATE TABLE notes_extra (id INTEGER)");
|
||||
throw new Error("migration bug");
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
expect(() =>
|
||||
openDaemonDatabase({ path: databasePath, modules: [failing], logger: createTestLogger() }),
|
||||
).toThrow(DatabaseOpenError);
|
||||
const database = open([]);
|
||||
expect(tableNames(database)).toEqual(["schema_versions"]);
|
||||
});
|
||||
|
||||
it("opens a database a newer daemon changed additively, and ignores stores it does not know", () => {
|
||||
const newer: SchemaModule = {
|
||||
name: "notes",
|
||||
migrations: [
|
||||
...notes.migrations,
|
||||
{ up: (sql) => sql.exec("ALTER TABLE notes_items ADD COLUMN pinned INTEGER") },
|
||||
],
|
||||
};
|
||||
const unknownStore: SchemaModule = {
|
||||
name: "future",
|
||||
migrations: [{ up: (sql) => sql.exec("CREATE TABLE future_items (id INTEGER)") }],
|
||||
};
|
||||
let database = open([newer, unknownStore]);
|
||||
database.write((sql) => sql.run("INSERT INTO notes_items (text, pinned) VALUES ('a', 1)"));
|
||||
database = reopen(database, [notes]);
|
||||
expect(database.read((sql) => sql.all("SELECT text FROM notes_items"))).toEqual([
|
||||
{ text: "a" },
|
||||
]);
|
||||
expect(versions(database)).toEqual([
|
||||
{ module: "future", version: 1, min_reader_version: 1 },
|
||||
{ module: "notes", version: 2, min_reader_version: 1 },
|
||||
]);
|
||||
});
|
||||
|
||||
it("refuses a database a newer daemon changed in a way this daemon cannot read", () => {
|
||||
const breaking: SchemaModule = {
|
||||
name: "notes",
|
||||
migrations: [
|
||||
...notes.migrations,
|
||||
{ up: (sql) => sql.exec("DROP TABLE notes_items"), breaking: true },
|
||||
],
|
||||
};
|
||||
open([breaking]).close();
|
||||
opened.length = 0;
|
||||
let error: unknown;
|
||||
try {
|
||||
openDaemonDatabase({ path: databasePath, modules: [notes], logger: createTestLogger() });
|
||||
} catch (thrown) {
|
||||
error = thrown;
|
||||
}
|
||||
expect(error).toBeInstanceOf(DatabaseSchemaTooNewError);
|
||||
expect(error).toMatchObject({ module: "notes", minReaderVersion: 2, knownVersion: 1 });
|
||||
expect((error as Error).message).toContain(databasePath);
|
||||
});
|
||||
|
||||
it("fails with the path when the file is not a database", () => {
|
||||
const corrupt = path.join(directory, "corrupt.db");
|
||||
writeFileSync(corrupt, "this is not a sqlite file, it is some text long enough to be read");
|
||||
let error: unknown;
|
||||
try {
|
||||
openDaemonDatabase({ path: corrupt, modules: [notes], logger: createTestLogger() });
|
||||
} catch (thrown) {
|
||||
error = thrown;
|
||||
}
|
||||
expect(error).toBeInstanceOf(DatabaseOpenError);
|
||||
expect((error as Error).message).toContain(corrupt);
|
||||
});
|
||||
});
|
||||
|
||||
function insert(sql: WriteSql, text: string): void {
|
||||
sql.run("INSERT INTO notes_items (text) VALUES (?)", text);
|
||||
}
|
||||
|
||||
function insertThenThrow(sql: WriteSql, text: string): never {
|
||||
insert(sql, text);
|
||||
throw new Error(`failed after ${text}`);
|
||||
}
|
||||
|
||||
function texts(database: DaemonDatabase): string[] {
|
||||
return database.read((sql) =>
|
||||
sql.all<{ text: string }>("SELECT text FROM notes_items ORDER BY id").map((row) => row.text),
|
||||
);
|
||||
}
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"keeps the database and its WAL files private to the user, including a file created readable",
|
||||
() => {
|
||||
const umask = process.umask(0o022);
|
||||
try {
|
||||
writeFileSync(databasePath, "", { mode: 0o644 });
|
||||
const database = open([notes]);
|
||||
database.write((sql) => insert(sql, "secret"));
|
||||
for (const file of [databasePath, `${databasePath}-wal`, `${databasePath}-shm`]) {
|
||||
expect({ file, mode: statSync(file).mode & 0o777 }).toEqual({ file, mode: 0o600 });
|
||||
}
|
||||
} finally {
|
||||
process.umask(umask);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("rolls a write back when its callback throws", () => {
|
||||
const database = open([notes]);
|
||||
expect(() => database.write((sql) => insertThenThrow(sql, "lost"))).toThrow("failed after lost");
|
||||
expect(count(database, "notes_items")).toBe(0);
|
||||
});
|
||||
|
||||
it("rolls back only a nested write that throws", () => {
|
||||
const database = open([notes]);
|
||||
const writeOuter = (sql: WriteSql) => {
|
||||
insert(sql, "outer");
|
||||
expect(() => database.write((inner) => insertThenThrow(inner, "inner"))).toThrow(
|
||||
"failed after inner",
|
||||
);
|
||||
database.write((inner) => insert(inner, "second"));
|
||||
};
|
||||
database.write(writeOuter);
|
||||
expect(texts(database)).toEqual(["outer", "second"]);
|
||||
});
|
||||
|
||||
it("joins a read nested in a write, which sees the write's uncommitted rows", () => {
|
||||
const database = open([notes]);
|
||||
database.write((sql) => {
|
||||
insert(sql, "pending");
|
||||
expect(count(database, "notes_items")).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
it("refuses a write inside a read", () => {
|
||||
const database = open([notes]);
|
||||
const writeInsideRead = () => database.write((sql) => insert(sql, "late"));
|
||||
expect(() => database.read(writeInsideRead)).toThrow(/inside a read/);
|
||||
});
|
||||
|
||||
it("refuses an asynchronous callback and rolls its work back", () => {
|
||||
const database = open([notes]);
|
||||
const writeAsync = async (sql: WriteSql) => insert(sql, "async");
|
||||
expect(() => database.write(writeAsync)).toThrow(/synchronous/);
|
||||
expect(count(database, "notes_items")).toBe(0);
|
||||
});
|
||||
|
||||
it("invalidates a handle once its callback returns", () => {
|
||||
const database = open([notes]);
|
||||
let leaked: WriteSql | undefined;
|
||||
database.write((sql) => {
|
||||
leaked = sql;
|
||||
});
|
||||
expect(() => insert(leaked!, "late")).toThrow(/after its transaction/);
|
||||
expect(count(database, "notes_items")).toBe(0);
|
||||
});
|
||||
|
||||
it("closes an unfinished iterator before the transaction ends", () => {
|
||||
const database = open([notes]);
|
||||
database.write((sql) => ["a", "b", "c"].forEach((text) => insert(sql, text)));
|
||||
let rest: Iterator<unknown> | undefined;
|
||||
const first = database.read((sql) => {
|
||||
const iterator = sql.iterate("SELECT text FROM notes_items ORDER BY id")[Symbol.iterator]();
|
||||
rest = iterator;
|
||||
return iterator.next().value;
|
||||
});
|
||||
expect(first).toEqual({ text: "a" });
|
||||
expect(() => rest!.next()).toThrow(/after its transaction/);
|
||||
// A statement left open makes schema changes fail with "database table is locked".
|
||||
database.write((sql) => sql.exec("DROP TABLE notes_items"));
|
||||
expect(tableNames(database)).toEqual(["schema_versions"]);
|
||||
});
|
||||
|
||||
it("refuses to reuse a statement that an unfinished iterator holds", () => {
|
||||
const database = open([notes]);
|
||||
database.write((sql) => insert(sql, "a"));
|
||||
const query = "SELECT text FROM notes_items";
|
||||
const reuse = (sql: ReadSql) => {
|
||||
sql.iterate(query)[Symbol.iterator]().next();
|
||||
expect(() => sql.all(query)).toThrow(/already iterating/);
|
||||
};
|
||||
database.read(reuse);
|
||||
});
|
||||
|
||||
it("checkpoints the WAL off the daemon thread, never during a write", async () => {
|
||||
const database = open([notes]);
|
||||
expect(
|
||||
database.read((sql) => sql.get<{ wal_autocheckpoint: number }>("PRAGMA wal_autocheckpoint")),
|
||||
).toEqual({ wal_autocheckpoint: 0 });
|
||||
const fileSize = () => statSync(databasePath).size;
|
||||
const before = fileSize();
|
||||
const writeBatch = (sql: WriteSql) => {
|
||||
for (let row = 0; row < 50; row++) insert(sql, "x".repeat(1000));
|
||||
};
|
||||
for (let batch = 0; batch < 20; batch++) database.write(writeBatch);
|
||||
// Writes go to the WAL. Only a checkpoint copies them into the database file.
|
||||
await vi.waitFor(() => expect(fileSize()).toBeGreaterThan(before + 500_000), {
|
||||
timeout: 10_000,
|
||||
interval: 50,
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects every call after close", () => {
|
||||
const database = open([notes]);
|
||||
database.close();
|
||||
expect(() => database.read((sql) => sql.all("SELECT 1"))).toThrow(DatabaseClosedError);
|
||||
expect(() => database.close()).not.toThrow();
|
||||
});
|
||||
|
||||
describe("the WAL checkpointer", () => {
|
||||
it("stops and closes its connection when asked, without reporting an exit", () => {
|
||||
open([notes]).write((sql) => insert(sql, "a"));
|
||||
let exited = false;
|
||||
const checkpointer = new WalCheckpointer({
|
||||
path: databasePath,
|
||||
logger: createTestLogger(),
|
||||
onExit: () => {
|
||||
exited = true;
|
||||
},
|
||||
});
|
||||
expect(checkpointer.stop()).toBe(true);
|
||||
expect(exited).toBe(false);
|
||||
});
|
||||
|
||||
it("reports a worker that ends on its own, so the database can checkpoint itself again", async () => {
|
||||
let exited = false;
|
||||
const checkpointer = new WalCheckpointer({
|
||||
path: path.join(directory, "missing", "paseo.db"),
|
||||
logger: createTestLogger(),
|
||||
onExit: () => {
|
||||
exited = true;
|
||||
},
|
||||
});
|
||||
await vi.waitFor(() => expect(exited).toBe(true), { timeout: 10_000, interval: 20 });
|
||||
expect(checkpointer.stop()).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
export {
|
||||
DatabaseClosedError,
|
||||
DatabaseOpenError,
|
||||
DatabaseSchemaTooNewError,
|
||||
openDaemonDatabase,
|
||||
type DaemonDatabase,
|
||||
type Migration,
|
||||
type ReadSql,
|
||||
type SchemaModule,
|
||||
type SqlValue,
|
||||
type WriteSql,
|
||||
} from "./internal/daemon-database.js";
|
||||
@@ -0,0 +1,426 @@
|
||||
import type { DatabaseSync, SQLInputValue, StatementSync } from "node:sqlite";
|
||||
import type { Logger } from "pino";
|
||||
import { ensurePrivateFile } from "../../private-files.js";
|
||||
import { WalCheckpointer } from "./wal-checkpointer.js";
|
||||
|
||||
export type SqlValue = SQLInputValue;
|
||||
|
||||
/** Queries available inside `DaemonDatabase.read`. A handle is valid only inside its callback. */
|
||||
export interface ReadSql {
|
||||
get<T>(sql: string, ...params: SqlValue[]): T | undefined;
|
||||
all<T>(sql: string, ...params: SqlValue[]): T[];
|
||||
/** Lazy rows. An unfinished iteration is closed when the callback returns. */
|
||||
iterate<T>(sql: string, ...params: SqlValue[]): Iterable<T>;
|
||||
}
|
||||
|
||||
/** Queries available inside `DaemonDatabase.write`. */
|
||||
export interface WriteSql extends ReadSql {
|
||||
run(sql: string, ...params: SqlValue[]): { changes: number };
|
||||
/** Runs one or more statements without caching them, for schema changes. */
|
||||
exec(sql: string): void;
|
||||
}
|
||||
|
||||
export interface Migration {
|
||||
up(sql: WriteSql): void;
|
||||
/**
|
||||
* The change leaves the schema unreadable for a daemon that knows only the earlier migrations,
|
||||
* for example a dropped or renamed column. Additive changes leave this unset.
|
||||
*/
|
||||
breaking?: boolean;
|
||||
}
|
||||
|
||||
/** A store's schema: its tables, named with the store's prefix, and their migrations in order. */
|
||||
export interface SchemaModule {
|
||||
name: string;
|
||||
/** Append-only. The module's version is the number of migrations applied. */
|
||||
migrations: readonly Migration[];
|
||||
}
|
||||
|
||||
/**
|
||||
* The daemon's SQLite database. Calls are synchronous and run on the caller's thread, so
|
||||
* transactions never interleave. A callback must not be asynchronous: a transaction never spans
|
||||
* an `await`.
|
||||
*/
|
||||
export interface DaemonDatabase {
|
||||
/** One write transaction. A throw rolls it back. Nested in a write, it is a savepoint. */
|
||||
write<T>(fn: (sql: WriteSql) => T): T;
|
||||
/** One consistent read. Nested in a read or write, it joins the outer transaction. */
|
||||
read<T>(fn: (sql: ReadSql) => T): T;
|
||||
/** Checkpoints the WAL and closes the file. Later calls throw `DatabaseClosedError`. */
|
||||
close(): void;
|
||||
}
|
||||
|
||||
export class DatabaseClosedError extends Error {
|
||||
constructor() {
|
||||
super("The daemon database is closed");
|
||||
this.name = "DatabaseClosedError";
|
||||
}
|
||||
}
|
||||
|
||||
/** The database cannot be used: `node:sqlite` is missing, or the file cannot be opened or migrated. */
|
||||
export class DatabaseOpenError extends Error {
|
||||
constructor(
|
||||
readonly path: string,
|
||||
cause: unknown,
|
||||
) {
|
||||
super(`Cannot open the Paseo database at ${path}: ${describeError(cause)}`, { cause });
|
||||
this.name = "DatabaseOpenError";
|
||||
}
|
||||
}
|
||||
|
||||
/** A newer daemon changed a store's schema in a way this daemon cannot read. */
|
||||
export class DatabaseSchemaTooNewError extends Error {
|
||||
constructor(
|
||||
readonly path: string,
|
||||
readonly module: string,
|
||||
readonly minReaderVersion: number,
|
||||
readonly knownVersion: number,
|
||||
) {
|
||||
super(
|
||||
`The Paseo database at ${path} was changed by a newer Paseo: store '${module}' needs ` +
|
||||
`schema version ${minReaderVersion}, this daemon knows version ${knownVersion}. ` +
|
||||
"Update Paseo to use it.",
|
||||
);
|
||||
this.name = "DatabaseSchemaTooNewError";
|
||||
}
|
||||
}
|
||||
|
||||
const BUSY_TIMEOUT_MS = 1000;
|
||||
const JOURNAL_SIZE_LIMIT_BYTES = 64 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* Opens the database at `path`, creating the file when absent in a directory that must exist, and
|
||||
* brings every module's schema up to date in one transaction. Throws `DatabaseOpenError` or `DatabaseSchemaTooNewError`.
|
||||
*/
|
||||
export function openDaemonDatabase(input: {
|
||||
path: string;
|
||||
modules: readonly SchemaModule[];
|
||||
logger: Logger;
|
||||
}): DaemonDatabase {
|
||||
let connection: DatabaseSync | undefined;
|
||||
try {
|
||||
const sqlite = loadSqlite();
|
||||
connection = new sqlite.DatabaseSync(input.path, { timeout: BUSY_TIMEOUT_MS });
|
||||
assertSupported(connection);
|
||||
// The file holds every prompt and reply. SQLite gives the WAL and shared-memory files it
|
||||
// creates the database file's mode; files left by an earlier open are fixed here.
|
||||
if (input.path !== ":memory:") {
|
||||
for (const file of [input.path, `${input.path}-wal`, `${input.path}-shm`]) {
|
||||
ensurePrivateFile(file);
|
||||
}
|
||||
}
|
||||
connection.exec(
|
||||
[
|
||||
"PRAGMA journal_mode = WAL",
|
||||
"PRAGMA synchronous = NORMAL",
|
||||
"PRAGMA foreign_keys = ON",
|
||||
`PRAGMA journal_size_limit = ${JOURNAL_SIZE_LIMIT_BYTES}`,
|
||||
].join(";"),
|
||||
);
|
||||
const database = new SqliteDaemonDatabase(connection, input.logger);
|
||||
migrate(database, input.path, input.modules);
|
||||
if (input.path !== ":memory:") database.checkpointOffThread(input.path);
|
||||
return database;
|
||||
} catch (error) {
|
||||
connection?.close();
|
||||
if (error instanceof DatabaseSchemaTooNewError) throw error;
|
||||
throw new DatabaseOpenError(input.path, error);
|
||||
}
|
||||
}
|
||||
|
||||
function loadSqlite(): typeof import("node:sqlite") {
|
||||
// Loaded on open, not imported: Node 22 warns that the module is experimental when it loads, and
|
||||
// CLI commands import this package without opening a database.
|
||||
// Node before 20.16 has no getBuiltinModule; the engines field does not stop a global install.
|
||||
const sqlite =
|
||||
typeof process.getBuiltinModule === "function"
|
||||
? process.getBuiltinModule("node:sqlite")
|
||||
: undefined;
|
||||
if (!sqlite) {
|
||||
throw new Error(`node:sqlite is unavailable in Node ${process.versions.node}; use >= 22.16`);
|
||||
}
|
||||
return sqlite;
|
||||
}
|
||||
|
||||
/** Node 22.13 has node:sqlite without `isTransaction`, which rollback needs. */
|
||||
function assertSupported(connection: DatabaseSync): void {
|
||||
if (typeof connection.isTransaction !== "boolean") {
|
||||
throw new Error(`node:sqlite in Node ${process.versions.node} is too old; use >= 22.16`);
|
||||
}
|
||||
}
|
||||
|
||||
function migrate(database: DaemonDatabase, file: string, modules: readonly SchemaModule[]): void {
|
||||
database.write((sql) => {
|
||||
sql.exec(
|
||||
"CREATE TABLE IF NOT EXISTS schema_versions (" +
|
||||
"module TEXT PRIMARY KEY, version INTEGER NOT NULL, min_reader_version INTEGER NOT NULL)",
|
||||
);
|
||||
const names = new Set<string>();
|
||||
for (const module of modules) {
|
||||
if (names.has(module.name)) throw new Error(`Schema module '${module.name}' is listed twice`);
|
||||
names.add(module.name);
|
||||
migrateModule(sql, file, module);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
interface StoredVersion {
|
||||
version: number;
|
||||
min_reader_version: number;
|
||||
}
|
||||
|
||||
function migrateModule(sql: WriteSql, file: string, module: SchemaModule): void {
|
||||
const known = module.migrations.length;
|
||||
const stored = sql.get<StoredVersion>(
|
||||
"SELECT version, min_reader_version FROM schema_versions WHERE module = ?",
|
||||
module.name,
|
||||
);
|
||||
if (stored && stored.min_reader_version > known) {
|
||||
throw new DatabaseSchemaTooNewError(file, module.name, stored.min_reader_version, known);
|
||||
}
|
||||
const from = stored?.version ?? 0;
|
||||
if (from >= known) return;
|
||||
// The first migration creates the store, so no daemon that predates it can read the store.
|
||||
let minReaderVersion = Math.max(stored?.min_reader_version ?? 0, 1);
|
||||
for (let index = from; index < known; index++) {
|
||||
const migration = module.migrations[index];
|
||||
migration.up(sql);
|
||||
if (migration.breaking) minReaderVersion = index + 1;
|
||||
}
|
||||
sql.run(
|
||||
"INSERT INTO schema_versions (module, version, min_reader_version) VALUES (?, ?, ?) " +
|
||||
"ON CONFLICT (module) DO UPDATE SET version = excluded.version, " +
|
||||
"min_reader_version = excluded.min_reader_version",
|
||||
module.name,
|
||||
known,
|
||||
minReaderVersion,
|
||||
);
|
||||
}
|
||||
|
||||
type TransactionState = "none" | "read" | "write";
|
||||
|
||||
/** Who checkpoints the WAL: SQLite on each commit, a worker not yet started, or the worker. */
|
||||
type CheckpointerState =
|
||||
| { kind: "on_thread" }
|
||||
| { kind: "pending"; path: string }
|
||||
| { kind: "worker"; worker: WalCheckpointer };
|
||||
|
||||
const SQLITE_DEFAULT_AUTOCHECKPOINT_PAGES = 1000;
|
||||
|
||||
interface OpenIteration {
|
||||
close(): void;
|
||||
}
|
||||
|
||||
class SqliteDaemonDatabase implements DaemonDatabase {
|
||||
private state: TransactionState = "none";
|
||||
private savepoints = 0;
|
||||
private closed = false;
|
||||
private readonly statements = new Map<string, StatementSync>();
|
||||
private readonly iterating = new Set<StatementSync>();
|
||||
private checkpointer: CheckpointerState = { kind: "on_thread" };
|
||||
|
||||
constructor(
|
||||
private readonly connection: DatabaseSync,
|
||||
private readonly logger: Logger,
|
||||
) {}
|
||||
|
||||
write<T>(fn: (sql: WriteSql) => T): T {
|
||||
this.assertOpen();
|
||||
if (this.state === "read") throw new Error("Cannot write inside a read transaction");
|
||||
if (this.state === "write") return this.savepoint(fn);
|
||||
return this.transaction("write", "BEGIN IMMEDIATE", fn);
|
||||
}
|
||||
|
||||
read<T>(fn: (sql: ReadSql) => T): T {
|
||||
this.assertOpen();
|
||||
if (this.state !== "none") return this.scoped(fn);
|
||||
return this.transaction("read", "BEGIN", fn);
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves WAL checkpoints to a worker thread, started by the first committed write, so a
|
||||
* read-only open starts no thread. Until then SQLite's auto-checkpoint stays off.
|
||||
*/
|
||||
checkpointOffThread(file: string): void {
|
||||
this.connection.exec("PRAGMA wal_autocheckpoint = 0");
|
||||
this.checkpointer = { kind: "pending", path: file };
|
||||
}
|
||||
|
||||
close(): void {
|
||||
if (this.closed) return;
|
||||
if (this.state !== "none") throw new Error("Cannot close the database inside a transaction");
|
||||
this.closed = true;
|
||||
if (this.checkpointer.kind === "worker" && !this.checkpointer.worker.stop()) {
|
||||
this.logger.warn("Database WAL checkpointer did not stop before close");
|
||||
}
|
||||
try {
|
||||
const result = this.connection.prepare("PRAGMA wal_checkpoint(TRUNCATE)").get() as
|
||||
| { busy: number }
|
||||
| undefined;
|
||||
if (result?.busy) this.logger.warn("Database WAL checkpoint was blocked by another reader");
|
||||
} catch (error) {
|
||||
this.logger.warn({ err: error }, "Database WAL checkpoint failed before close");
|
||||
}
|
||||
this.statements.clear();
|
||||
this.connection.close();
|
||||
}
|
||||
|
||||
private transaction<T>(state: TransactionState, begin: string, fn: (sql: WriteSql) => T): T {
|
||||
this.connection.exec(begin);
|
||||
this.state = state;
|
||||
try {
|
||||
const result = this.scoped(fn);
|
||||
this.connection.exec("COMMIT");
|
||||
if (state === "write") this.startPendingCheckpointer();
|
||||
return result;
|
||||
} catch (error) {
|
||||
if (this.connection.isTransaction) this.connection.exec("ROLLBACK");
|
||||
throw error;
|
||||
} finally {
|
||||
this.state = "none";
|
||||
}
|
||||
}
|
||||
|
||||
private savepoint<T>(fn: (sql: WriteSql) => T): T {
|
||||
const name = `paseo_${++this.savepoints}`;
|
||||
this.connection.exec(`SAVEPOINT ${name}`);
|
||||
try {
|
||||
const result = this.scoped(fn);
|
||||
this.connection.exec(`RELEASE ${name}`);
|
||||
return result;
|
||||
} catch (error) {
|
||||
this.connection.exec(`ROLLBACK TO ${name}`);
|
||||
this.connection.exec(`RELEASE ${name}`);
|
||||
throw error;
|
||||
} finally {
|
||||
this.savepoints--;
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs `fn` with a handle that stops working, and closes its iterations, when `fn` returns. */
|
||||
private scoped<T>(fn: (sql: WriteSql) => T): T {
|
||||
let valid = true;
|
||||
const iterations = new Set<OpenIteration>();
|
||||
const assertValid = () => {
|
||||
if (!valid) throw new Error("A database handle was used after its transaction ended");
|
||||
};
|
||||
const statement = (sql: string) => {
|
||||
assertValid();
|
||||
const prepared = this.statement(sql);
|
||||
if (this.iterating.has(prepared)) {
|
||||
throw new Error(`A statement is already iterating: ${sql}`);
|
||||
}
|
||||
return prepared;
|
||||
};
|
||||
const handle: WriteSql = {
|
||||
get: <R>(sql: string, ...params: SqlValue[]) =>
|
||||
statement(sql).get(...params) as R | undefined,
|
||||
all: <R>(sql: string, ...params: SqlValue[]) => statement(sql).all(...params) as R[],
|
||||
iterate: <R>(sql: string, ...params: SqlValue[]) =>
|
||||
this.iterate<R>(statement(sql), params, iterations, assertValid),
|
||||
run: (sql: string, ...params: SqlValue[]) => ({
|
||||
changes: Number(statement(sql).run(...params).changes),
|
||||
}),
|
||||
exec: (sql: string) => {
|
||||
assertValid();
|
||||
this.connection.exec(sql);
|
||||
},
|
||||
};
|
||||
try {
|
||||
const result = fn(handle);
|
||||
if (isThenable(result)) {
|
||||
throw new Error("A database transaction callback must be synchronous");
|
||||
}
|
||||
return result;
|
||||
} finally {
|
||||
valid = false;
|
||||
for (const iteration of iterations) iteration.close();
|
||||
}
|
||||
}
|
||||
|
||||
private iterate<R>(
|
||||
prepared: StatementSync,
|
||||
params: SqlValue[],
|
||||
iterations: Set<OpenIteration>,
|
||||
assertValid: () => void,
|
||||
): Iterable<R> {
|
||||
const rows = prepared.iterate(...params);
|
||||
let done = false;
|
||||
const iteration: OpenIteration = {
|
||||
close: () => {
|
||||
if (done) return;
|
||||
done = true;
|
||||
this.iterating.delete(prepared);
|
||||
iterations.delete(iteration);
|
||||
rows.return?.();
|
||||
},
|
||||
};
|
||||
this.iterating.add(prepared);
|
||||
iterations.add(iteration);
|
||||
const iterator: Iterator<R> = {
|
||||
next: () => {
|
||||
assertValid();
|
||||
if (done) return { done: true, value: undefined };
|
||||
const next = rows.next();
|
||||
if (next.done) iteration.close();
|
||||
return next.done
|
||||
? { done: true, value: undefined }
|
||||
: { done: false, value: next.value as R };
|
||||
},
|
||||
return: () => {
|
||||
iteration.close();
|
||||
return { done: true, value: undefined };
|
||||
},
|
||||
};
|
||||
return { [Symbol.iterator]: () => iterator };
|
||||
}
|
||||
|
||||
/** Runs after a write commits, so it never throws: the write has already happened. */
|
||||
private startPendingCheckpointer(): void {
|
||||
if (this.checkpointer.kind !== "pending") return;
|
||||
try {
|
||||
const worker = new WalCheckpointer({
|
||||
path: this.checkpointer.path,
|
||||
logger: this.logger,
|
||||
onExit: () => this.checkpointOnThread(),
|
||||
});
|
||||
this.checkpointer = { kind: "worker", worker };
|
||||
} catch (error) {
|
||||
this.logger.warn({ err: error }, "Database WAL checkpointer did not start");
|
||||
this.checkpointOnThread();
|
||||
}
|
||||
}
|
||||
|
||||
/** The worker ended on its own: let SQLite checkpoint again, so the WAL stays bounded. */
|
||||
private checkpointOnThread(): void {
|
||||
if (this.closed) return;
|
||||
this.logger.warn("Database WAL checkpointer exited; checkpointing on the daemon thread");
|
||||
this.checkpointer = { kind: "on_thread" };
|
||||
this.connection.exec(`PRAGMA wal_autocheckpoint = ${SQLITE_DEFAULT_AUTOCHECKPOINT_PAGES}`);
|
||||
}
|
||||
|
||||
private statement(sql: string): StatementSync {
|
||||
let prepared = this.statements.get(sql);
|
||||
if (!prepared) {
|
||||
prepared = this.connection.prepare(sql);
|
||||
this.statements.set(sql, prepared);
|
||||
}
|
||||
return prepared;
|
||||
}
|
||||
|
||||
private assertOpen(): void {
|
||||
if (this.closed) throw new DatabaseClosedError();
|
||||
}
|
||||
}
|
||||
|
||||
function isThenable(value: unknown): boolean {
|
||||
return (
|
||||
typeof value === "object" &&
|
||||
value !== null &&
|
||||
typeof (value as { then?: unknown }).then === "function"
|
||||
);
|
||||
}
|
||||
|
||||
function describeError(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { Worker } from "node:worker_threads";
|
||||
import type { Logger } from "pino";
|
||||
|
||||
const CHECKPOINT_INTERVAL_MS = 1000;
|
||||
const STOP_TIMEOUT_MS = 2000;
|
||||
|
||||
const RUNNING = 0;
|
||||
const STOPPING = 1;
|
||||
const STOPPED = 1;
|
||||
|
||||
/**
|
||||
* Runs in the worker. It sleeps on the shared state, so `stop` wakes it at once, and needs no
|
||||
* event loop: a checkpoint is one synchronous call.
|
||||
*/
|
||||
const WORKER_SOURCE = `
|
||||
const { parentPort, workerData } = require("node:worker_threads");
|
||||
const state = new Int32Array(workerData.state);
|
||||
let connection;
|
||||
try {
|
||||
connection = new (process.getBuiltinModule("node:sqlite").DatabaseSync)(workerData.path);
|
||||
while (Atomics.wait(state, 0, ${RUNNING}, workerData.intervalMs) === "timed-out") {
|
||||
try {
|
||||
connection.prepare("PRAGMA wal_checkpoint(PASSIVE)").get();
|
||||
} catch (error) {
|
||||
parentPort.postMessage(String(error && error.message ? error.message : error));
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
parentPort.postMessage(String(error && error.message ? error.message : error));
|
||||
} finally {
|
||||
try { connection && connection.close(); } catch {}
|
||||
Atomics.store(state, 1, ${STOPPED});
|
||||
Atomics.notify(state, 1);
|
||||
}
|
||||
`;
|
||||
|
||||
/**
|
||||
* Copies committed WAL pages into the database file from a worker thread. A checkpoint syncs the
|
||||
* file to disk, which takes up to a hundred milliseconds; on the daemon thread it would stall the
|
||||
* event loop on whichever write crossed SQLite's auto-checkpoint threshold. A passive checkpoint
|
||||
* takes no lock a writer needs, so it runs alongside the daemon's writes.
|
||||
*/
|
||||
export class WalCheckpointer {
|
||||
private readonly state = new Int32Array(new SharedArrayBuffer(8));
|
||||
private readonly worker: Worker;
|
||||
private stopped = false;
|
||||
|
||||
/** `onExit` runs when the worker ends before `stop`, so checkpoints have stopped. */
|
||||
constructor(input: { path: string; logger: Logger; onExit: () => void }) {
|
||||
const { logger } = input;
|
||||
this.worker = new Worker(WORKER_SOURCE, {
|
||||
eval: true,
|
||||
workerData: {
|
||||
path: input.path,
|
||||
state: this.state.buffer,
|
||||
intervalMs: CHECKPOINT_INTERVAL_MS,
|
||||
},
|
||||
// Node 22 prints an experimental warning when the worker loads node:sqlite; the daemon
|
||||
// already printed it once.
|
||||
stderr: true,
|
||||
});
|
||||
this.worker.stderr.resume();
|
||||
this.worker.on("message", (message: string) => {
|
||||
logger.warn({ error: message }, "Database WAL checkpoint failed");
|
||||
});
|
||||
this.worker.on("error", (error) => {
|
||||
logger.warn({ err: error }, "Database WAL checkpointer failed");
|
||||
});
|
||||
this.worker.on("exit", () => {
|
||||
if (!this.stopped) input.onExit();
|
||||
});
|
||||
this.worker.unref();
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the worker, blocking until it has closed its connection, for at most two seconds. False
|
||||
* when it had not closed by then; it is terminated either way.
|
||||
*/
|
||||
stop(): boolean {
|
||||
if (this.stopped) return true;
|
||||
this.stopped = true;
|
||||
Atomics.store(this.state, 0, STOPPING);
|
||||
Atomics.notify(this.state, 0);
|
||||
const closed = Atomics.wait(this.state, 1, 0, STOP_TIMEOUT_MS) !== "timed-out";
|
||||
void this.worker.terminate();
|
||||
return closed;
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,10 @@
|
||||
import { MockLoadTestAgentClient } from "./agent/providers/mock-load-test-agent.js";
|
||||
import { createPaseoApi } from "@getpaseo/client";
|
||||
import type { AgentManager } from "./agent/agent-manager.js";
|
||||
import { AgentStorage } from "./agent/agent-storage.js";
|
||||
import { createTestLogger } from "../test-utils/test-logger.js";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { DatabaseSync } from "node:sqlite";
|
||||
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { expect, test } from "vitest";
|
||||
@@ -1423,6 +1426,42 @@ test("archive and delete replies retain their historical names and reach only th
|
||||
}
|
||||
});
|
||||
|
||||
test("a delete that cannot remove the agent's history fails and leaves the agent usable", async () => {
|
||||
const daemon = await createTestPaseoDaemon({ mcpEnabled: false });
|
||||
const admin = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
|
||||
// A second connection to the daemon's database makes the history delete fail.
|
||||
const database = new DatabaseSync(path.join(daemon.paseoHome, "paseo.db"));
|
||||
try {
|
||||
await admin.connect();
|
||||
const agent = await admin.createAgent({ provider: "codex", cwd: daemon.staticDir });
|
||||
database.exec(`CREATE TRIGGER refuse_history_delete BEFORE DELETE ON timeline_scopes
|
||||
BEGIN SELECT RAISE(ABORT, 'disk I/O error'); END`);
|
||||
|
||||
await expect(admin.deleteAgent(agent.id)).rejects.toThrow("disk I/O error");
|
||||
const afterFailure = await admin.fetchAgents();
|
||||
expect(afterFailure.entries.map((entry) => entry.agent.id)).toEqual([agent.id]);
|
||||
|
||||
await admin.updateAgent(agent.id, { name: "After the failed delete" });
|
||||
// A fresh reader of the agent directory sees only what reached disk.
|
||||
const stored = await new AgentStorage(
|
||||
path.join(daemon.paseoHome, "agents"),
|
||||
createTestLogger(),
|
||||
).get(agent.id);
|
||||
expect(stored?.title).toBe("After the failed delete");
|
||||
|
||||
database.exec("DROP TRIGGER refuse_history_delete");
|
||||
await admin.deleteAgent(agent.id);
|
||||
expect((await admin.fetchAgents()).entries).toEqual([]);
|
||||
expect(
|
||||
database.prepare("SELECT agent_id FROM timeline_scopes WHERE agent_id = ?").all(agent.id),
|
||||
).toEqual([]);
|
||||
} finally {
|
||||
database.close();
|
||||
await admin.close();
|
||||
await daemon.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("Hub bootstrap sends its server ID before the producer's synchronous snapshot", async () => {
|
||||
const daemon = await createTestPaseoDaemon({ mcpEnabled: false });
|
||||
const admin = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
|
||||
|
||||
@@ -0,0 +1,846 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, describe, expect, it, onTestFinished } from "vitest";
|
||||
import { CLIENT_CAPS } from "@getpaseo/protocol/client-capabilities";
|
||||
import type { SessionOutboundMessage } from "@getpaseo/protocol/messages";
|
||||
import {
|
||||
AgentProviderSwitchError,
|
||||
DaemonClient,
|
||||
type WebSocketLike,
|
||||
} from "@getpaseo/client/internal/daemon-client";
|
||||
import { WebSocket } from "ws";
|
||||
import { createTestPaseoDaemon, type TestPaseoDaemon } from "./test-utils/paseo-daemon.js";
|
||||
import type {
|
||||
AgentClient,
|
||||
AgentPersistenceHandle,
|
||||
AgentPromptInput,
|
||||
AgentProvider,
|
||||
AgentRunOptions,
|
||||
AgentRunResult,
|
||||
AgentSession,
|
||||
AgentSessionConfig,
|
||||
AgentStreamEvent,
|
||||
} from "./agent/agent-sdk-types.js";
|
||||
import { renderProviderPromptText } from "./agent/provider-switch/index.js";
|
||||
|
||||
const CAPS = {
|
||||
supportsStreaming: true,
|
||||
supportsSessionPersistence: true,
|
||||
supportsDynamicModes: false,
|
||||
supportsMcpServers: true,
|
||||
supportsReasoningStream: false,
|
||||
supportsToolInvocations: true,
|
||||
supportsRewindConversation: true,
|
||||
supportsRewindFiles: false,
|
||||
supportsRewindBoth: false,
|
||||
} as const;
|
||||
|
||||
class E2EFakeSession implements AgentSession {
|
||||
readonly capabilities = CAPS;
|
||||
readonly receivedPrompts: AgentPromptInput[] = [];
|
||||
readonly setModelCalls: Array<string | null> = [];
|
||||
closed = false;
|
||||
private listeners = new Set<(event: AgentStreamEvent) => void>();
|
||||
private turnCount = 0;
|
||||
|
||||
constructor(
|
||||
readonly id: string,
|
||||
readonly provider: AgentProvider,
|
||||
private persistence: AgentPersistenceHandle | null,
|
||||
private readonly onStartTurn?: () => void,
|
||||
private readonly getTurnCompletionGate?: () => Promise<void> | null,
|
||||
) {}
|
||||
|
||||
subscribe(listener: (event: AgentStreamEvent) => void): () => void {
|
||||
this.listeners.add(listener);
|
||||
return () => this.listeners.delete(listener);
|
||||
}
|
||||
|
||||
async startTurn(
|
||||
prompt: AgentPromptInput,
|
||||
options?: AgentRunOptions,
|
||||
): Promise<{ turnId: string }> {
|
||||
this.receivedPrompts.push(prompt);
|
||||
this.onStartTurn?.();
|
||||
this.turnCount += 1;
|
||||
const turnId = `${this.provider}-t${this.turnCount}`;
|
||||
const msgId = `${this.provider}-m${this.turnCount}`;
|
||||
const rendered = renderProviderPromptText(prompt);
|
||||
const completionGate = this.getTurnCompletionGate?.() ?? null;
|
||||
const replyNumber = this.turnCount;
|
||||
const emitCompletion = () => {
|
||||
if (this.closed) return;
|
||||
for (const listener of this.listeners) {
|
||||
if (options?.clientMessageId) {
|
||||
listener({
|
||||
type: "timeline",
|
||||
provider: this.provider,
|
||||
turnId,
|
||||
item: {
|
||||
type: "user_message",
|
||||
text: rendered,
|
||||
messageId: msgId,
|
||||
clientMessageId: options.clientMessageId,
|
||||
},
|
||||
});
|
||||
}
|
||||
listener({
|
||||
type: "timeline",
|
||||
provider: this.provider,
|
||||
turnId,
|
||||
item: {
|
||||
type: "assistant_message",
|
||||
text: `${this.provider} reply ${replyNumber}`,
|
||||
},
|
||||
});
|
||||
listener({ type: "turn_completed", provider: this.provider, turnId });
|
||||
}
|
||||
};
|
||||
if (completionGate) {
|
||||
void completionGate.then(emitCompletion);
|
||||
} else {
|
||||
queueMicrotask(emitCompletion);
|
||||
}
|
||||
return { turnId };
|
||||
}
|
||||
|
||||
async run(prompt: AgentPromptInput, options?: AgentRunOptions): Promise<AgentRunResult> {
|
||||
await this.startTurn(prompt, options);
|
||||
return { sessionId: this.id, finalText: "", timeline: [] };
|
||||
}
|
||||
async *stream(): AsyncGenerator<AgentStreamEvent> {}
|
||||
async *streamHistory(): AsyncGenerator<AgentStreamEvent> {}
|
||||
async interrupt(): Promise<void> {}
|
||||
async getAvailableModes() {
|
||||
return [];
|
||||
}
|
||||
async getCurrentMode() {
|
||||
return null;
|
||||
}
|
||||
async setMode() {}
|
||||
async setModel(modelId: string | null) {
|
||||
this.setModelCalls.push(modelId);
|
||||
return modelId ? { model: modelId } : undefined;
|
||||
}
|
||||
async getRuntimeInfo() {
|
||||
return { provider: this.provider, sessionId: this.persistence?.sessionId ?? null };
|
||||
}
|
||||
describePersistence(): AgentPersistenceHandle | null {
|
||||
return this.persistence;
|
||||
}
|
||||
async close(): Promise<void> {
|
||||
this.closed = true;
|
||||
}
|
||||
async revertConversation(): Promise<{ kind: "at_target" }> {
|
||||
return { kind: "at_target" };
|
||||
}
|
||||
}
|
||||
|
||||
class E2EFakeClient implements AgentClient {
|
||||
readonly capabilities = CAPS;
|
||||
readonly sessions: E2EFakeSession[] = [];
|
||||
failNextCreate: Error | null = null;
|
||||
failNextTurn: Error | null = null;
|
||||
availabilityGate: Promise<void> | null = null;
|
||||
onAvailabilityCheckStarted: (() => void) | null = null;
|
||||
createSessionGate: Promise<void> | null = null;
|
||||
onCreateSessionStarted: (() => void) | null = null;
|
||||
turnCompletionGate: Promise<void> | null = null;
|
||||
onTurnStarted: (() => void) | null = null;
|
||||
|
||||
constructor(
|
||||
readonly provider: AgentProvider,
|
||||
private readonly initialPersistenceNull = false,
|
||||
) {}
|
||||
|
||||
async isAvailable(): Promise<boolean> {
|
||||
this.onAvailabilityCheckStarted?.();
|
||||
if (this.availabilityGate) {
|
||||
const gate = this.availabilityGate;
|
||||
this.availabilityGate = null;
|
||||
await gate;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
async fetchCatalog() {
|
||||
return { models: [], modes: [] };
|
||||
}
|
||||
async createSession(_config: AgentSessionConfig): Promise<AgentSession> {
|
||||
this.onCreateSessionStarted?.();
|
||||
if (this.createSessionGate) {
|
||||
const gate = this.createSessionGate;
|
||||
this.createSessionGate = null;
|
||||
await gate;
|
||||
}
|
||||
if (this.failNextCreate) {
|
||||
const err = this.failNextCreate;
|
||||
this.failNextCreate = null;
|
||||
throw err;
|
||||
}
|
||||
const id = `${this.provider}-s${this.sessions.length + 1}`;
|
||||
const session = new E2EFakeSession(
|
||||
id,
|
||||
this.provider,
|
||||
this.initialPersistenceNull ? null : { provider: this.provider, sessionId: id },
|
||||
() => {
|
||||
if (this.failNextTurn) {
|
||||
const err = this.failNextTurn;
|
||||
this.failNextTurn = null;
|
||||
throw err;
|
||||
}
|
||||
this.onTurnStarted?.();
|
||||
},
|
||||
() => this.turnCompletionGate,
|
||||
);
|
||||
this.sessions.push(session);
|
||||
return session;
|
||||
}
|
||||
async resumeSession(handle: AgentPersistenceHandle): Promise<AgentSession> {
|
||||
const session = new E2EFakeSession(
|
||||
handle.sessionId,
|
||||
this.provider,
|
||||
handle,
|
||||
() => this.onTurnStarted?.(),
|
||||
() => this.turnCompletionGate,
|
||||
);
|
||||
this.sessions.push(session);
|
||||
return session;
|
||||
}
|
||||
}
|
||||
|
||||
async function connectClient(
|
||||
url: string,
|
||||
capabilities?: Record<string, boolean>,
|
||||
): Promise<{ client: DaemonClient; messages: SessionOutboundMessage[] }> {
|
||||
const messages: SessionOutboundMessage[] = [];
|
||||
const client = new DaemonClient({
|
||||
url,
|
||||
clientId: randomUUID(),
|
||||
webSocketFactory: (wsUrl) => new WebSocket(wsUrl) as unknown as WebSocketLike,
|
||||
reconnect: { enabled: false },
|
||||
...(capabilities ? { capabilities } : {}),
|
||||
});
|
||||
client.subscribeRawMessages((msg) => {
|
||||
messages.push(msg);
|
||||
});
|
||||
await client.connect();
|
||||
onTestFinished(async () => {
|
||||
await client.close().catch(() => undefined);
|
||||
});
|
||||
return { client, messages };
|
||||
}
|
||||
|
||||
describe("Provider switching WebSocket RPC, receipts, and capability gating", () => {
|
||||
let daemon: TestPaseoDaemon | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
await daemon?.close();
|
||||
daemon = null;
|
||||
});
|
||||
|
||||
it("handles switch RPC, idempotent retry, post-commit start failure, and gates provider_switch items for legacy clients", async () => {
|
||||
const cwd = mkdtempSync(join(tmpdir(), "paseo-e2e-switch-"));
|
||||
onTestFinished(() => rmSync(cwd, { recursive: true, force: true }));
|
||||
|
||||
const claude = new E2EFakeClient("claude");
|
||||
const codex = new E2EFakeClient("codex", true);
|
||||
daemon = await createTestPaseoDaemon({
|
||||
agentClients: { claude, codex },
|
||||
});
|
||||
|
||||
const wsUrl = `ws://127.0.0.1:${daemon.port}/ws`;
|
||||
const modern = await connectClient(wsUrl);
|
||||
const legacy = await connectClient(wsUrl, {
|
||||
[CLIENT_CAPS.timelineProviderSwitches]: false,
|
||||
[CLIENT_CAPS.timelineRewindOperations]: true,
|
||||
[CLIENT_CAPS.selectiveAgentTimeline]: true,
|
||||
});
|
||||
|
||||
// Server advertises providerSwitching feature
|
||||
const serverInfoMsg = modern.messages.find(
|
||||
(m) => m.type === "status" && m.payload.status === "server_info",
|
||||
);
|
||||
expect(
|
||||
serverInfoMsg &&
|
||||
serverInfoMsg.type === "status" &&
|
||||
serverInfoMsg.payload.status === "server_info"
|
||||
? serverInfoMsg.payload.features?.providerSwitching
|
||||
: undefined,
|
||||
).toBe(true);
|
||||
|
||||
const agent = await modern.client.createAgent({ provider: "claude", cwd });
|
||||
await modern.client.sendMessage(agent.id, "First message on Claude", undefined, {
|
||||
messageId: "msg-c1",
|
||||
});
|
||||
|
||||
// Wait briefly for turn 1 to settle
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
|
||||
// Pre-commit failure MUST NOT leave a pending receipt, so retrying the same messageId succeeds!
|
||||
codex.failNextCreate = new Error("Codex failed to open session");
|
||||
await expect(
|
||||
modern.client.switchAgentProvider(agent.id, {
|
||||
provider: "codex",
|
||||
text: "Continue on Codex",
|
||||
messageId: "msg-sw-1",
|
||||
}),
|
||||
).rejects.toThrow("Codex failed to open session");
|
||||
|
||||
// Switch from Claude to Codex via RPC reusing the exact same messageId
|
||||
const switched = await modern.client.switchAgentProvider(agent.id, {
|
||||
provider: "codex",
|
||||
text: "Continue on Codex",
|
||||
messageId: "msg-sw-1",
|
||||
});
|
||||
expect(switched.agent?.provider).toBe("codex");
|
||||
expect(switched.agent?.id).toBe(agent.id);
|
||||
|
||||
// Wait for Codex turn 1 to settle
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
|
||||
// Idempotent retry with same messageId + same payload succeeds and returns current agent without creating a 2nd session
|
||||
const retried = await modern.client.switchAgentProvider(agent.id, {
|
||||
provider: "codex",
|
||||
text: "Continue on Codex",
|
||||
messageId: "msg-sw-1",
|
||||
});
|
||||
expect(retried.agent?.provider).toBe("codex");
|
||||
expect(codex.sessions).toHaveLength(1);
|
||||
|
||||
// Modern client sees provider_switch item + activeSegmentStartSeq > 0
|
||||
const modernPage = await modern.client.fetchAgentTimeline(agent.id, {
|
||||
direction: "tail",
|
||||
limit: 50,
|
||||
});
|
||||
expect(modernPage.activeSegmentStartSeq).toBeGreaterThan(0);
|
||||
expect(modernPage.entries.some((e) => e.item.type === "provider_switch")).toBe(true);
|
||||
// Ensure providerPromptText is NEVER leaked on wire entries
|
||||
for (const entry of modernPage.entries) {
|
||||
expect("providerPromptText" in entry).toBe(false);
|
||||
}
|
||||
|
||||
// Legacy client WITHOUT timeline_provider_switches NEVER receives provider_switch items!
|
||||
const legacyPage = await legacy.client.fetchAgentTimeline(agent.id, {
|
||||
direction: "tail",
|
||||
limit: 50,
|
||||
});
|
||||
expect(legacyPage.entries.some((e) => e.item.type === "provider_switch")).toBe(false);
|
||||
expect(legacyPage.entries.filter((e) => e.item.type === "user_message")).toHaveLength(2);
|
||||
|
||||
// Post-commit start failure: switch back to Claude, but fail turn 1 startTurn
|
||||
claude.failNextTurn = new Error("Claude rate limited on turn 1");
|
||||
let caught: unknown;
|
||||
try {
|
||||
await modern.client.switchAgentProvider(agent.id, {
|
||||
provider: "claude",
|
||||
text: "Back to Claude",
|
||||
messageId: "msg-sw-2",
|
||||
});
|
||||
} catch (error) {
|
||||
caught = error;
|
||||
}
|
||||
expect(caught).toBeInstanceOf(AgentProviderSwitchError);
|
||||
const switchErr = caught as AgentProviderSwitchError;
|
||||
expect(switchErr.message).toContain("Claude rate limited on turn 1");
|
||||
// Response MUST include committed Claude agent snapshot so UI updates live provider and lets user retry normally!
|
||||
expect(switchErr.agent?.provider).toBe("claude");
|
||||
expect(switchErr.agent?.id).toBe(agent.id);
|
||||
});
|
||||
|
||||
it("delivers the original switch request after a restart between switch commit and dispatch, and keeps archived switched chats archived when resuming a prior native handle", async () => {
|
||||
const cwd = mkdtempSync(join(tmpdir(), "paseo-provider-switch-recovery-e2e-"));
|
||||
onTestFinished(() => rmSync(cwd, { recursive: true, force: true }));
|
||||
|
||||
const claude = new E2EFakeClient("claude");
|
||||
const codex = new E2EFakeClient("codex", true);
|
||||
daemon = await createTestPaseoDaemon({
|
||||
agentClients: { claude, codex },
|
||||
});
|
||||
|
||||
const url = `ws://127.0.0.1:${daemon.port}/ws`;
|
||||
const clientConn = await connectClient(url);
|
||||
|
||||
// 1. Create Claude chat and save its native persistence handle.
|
||||
const created = await clientConn.client.createAgent({ provider: "claude", cwd });
|
||||
await clientConn.client.sendMessage(created.id, "First Claude turn", undefined, {
|
||||
messageId: "msg-r1",
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
const storedBefore = await daemon.daemon.agentStorage.get(created.id);
|
||||
expect(storedBefore?.persistence).toBeTruthy();
|
||||
const savedClaudeHandle = storedBefore!.persistence!;
|
||||
|
||||
// 2. Simulate switch committed to SQLite + storage BEFORE MessageReceipts wrote pending / before dispatch,
|
||||
// followed by daemon closing the live agent (restart boundary).
|
||||
await daemon.daemon.agentManager.switchAgentProvider(created.id, {
|
||||
toProvider: "codex",
|
||||
prompt: "Deliver after restart",
|
||||
messageId: "msg-r-sw",
|
||||
});
|
||||
await daemon.daemon.agentManager.closeAgent(created.id);
|
||||
|
||||
// Client replays the EXACT SAME switchAgentProvider request after restart -> must succeed
|
||||
// without "already using provider" and without adding a second provider_switch marker!
|
||||
const replayed = await clientConn.client.switchAgentProvider(created.id, {
|
||||
provider: "codex",
|
||||
text: "Deliver after restart",
|
||||
messageId: "msg-r-sw",
|
||||
});
|
||||
expect(replayed.agent?.provider).toBe("codex");
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
|
||||
const timeline = await clientConn.client.fetchAgentTimeline(created.id, {
|
||||
direction: "tail",
|
||||
limit: 50,
|
||||
});
|
||||
expect(timeline.entries.filter((e) => e.item.type === "provider_switch")).toHaveLength(1);
|
||||
expect(
|
||||
timeline.entries.some(
|
||||
(e) => e.item.type === "user_message" && e.item.text === "Deliver after restart",
|
||||
),
|
||||
).toBe(true);
|
||||
|
||||
// 3. Archive the switched Codex chat, then resume the saved prior Claude handle ->
|
||||
// must NOT unarchive the separate Codex chat!
|
||||
await clientConn.client.archiveAgent(created.id);
|
||||
const archivedBeforeResume = await daemon.daemon.agentStorage.get(created.id);
|
||||
expect(archivedBeforeResume?.archivedAt).toBeTruthy();
|
||||
|
||||
const resumedClaude = await clientConn.client.resumeAgent(
|
||||
{
|
||||
provider: savedClaudeHandle.provider,
|
||||
sessionId: savedClaudeHandle.sessionId,
|
||||
},
|
||||
{ cwd },
|
||||
);
|
||||
expect(resumedClaude.id).not.toBe(created.id);
|
||||
expect(resumedClaude.provider).toBe("claude");
|
||||
|
||||
const codexRecordAfterResume = await daemon.daemon.agentStorage.get(created.id);
|
||||
expect(codexRecordAfterResume?.archivedAt).toBeTruthy();
|
||||
});
|
||||
|
||||
it("rejects an overlapping provider switch from a second client instead of cutting off the first switch's running turn", async () => {
|
||||
const cwd = mkdtempSync(join(tmpdir(), "paseo-provider-switch-overlap-e2e-"));
|
||||
onTestFinished(() => rmSync(cwd, { recursive: true, force: true }));
|
||||
|
||||
const claude = new E2EFakeClient("claude");
|
||||
const codex = new E2EFakeClient("codex", true);
|
||||
const copilot = new E2EFakeClient("copilot");
|
||||
daemon = await createTestPaseoDaemon({
|
||||
agentClients: { claude, codex, copilot },
|
||||
});
|
||||
|
||||
const url = `ws://127.0.0.1:${daemon.port}/ws`;
|
||||
const client1 = await connectClient(url);
|
||||
const client2 = await connectClient(url);
|
||||
|
||||
const agent = await client1.client.createAgent({ provider: "claude", cwd });
|
||||
await client1.client.sendMessage(agent.id, "Initial Claude prompt", undefined, {
|
||||
messageId: "msg-ov-1",
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
|
||||
let resolveCodexCreate!: () => void;
|
||||
codex.createSessionGate = new Promise<void>((resolve) => {
|
||||
resolveCodexCreate = resolve;
|
||||
});
|
||||
let resolveCodexCreateStarted!: () => void;
|
||||
const codexCreateStarted = new Promise<void>((resolve) => {
|
||||
resolveCodexCreateStarted = resolve;
|
||||
});
|
||||
codex.onCreateSessionStarted = resolveCodexCreateStarted;
|
||||
|
||||
let resolveCodexTurn!: () => void;
|
||||
codex.turnCompletionGate = new Promise<void>((resolve) => {
|
||||
resolveCodexTurn = resolve;
|
||||
});
|
||||
|
||||
const firstSwitch = client1.client.switchAgentProvider(agent.id, {
|
||||
provider: "codex",
|
||||
text: "Continue on Codex",
|
||||
messageId: "msg-ov-codex",
|
||||
});
|
||||
await codexCreateStarted;
|
||||
|
||||
// Second client requests a competing switch to Copilot while Client 1's switch is still running.
|
||||
const secondSwitch = client2.client.switchAgentProvider(agent.id, {
|
||||
provider: "copilot",
|
||||
text: "Switch to Copilot instead",
|
||||
messageId: "msg-ov-copilot",
|
||||
});
|
||||
// Give the WebSocket message a tick to queue behind Client 1's switch.
|
||||
await new Promise((resolve) => setTimeout(resolve, 30));
|
||||
|
||||
// Release Codex session startup; Codex turn 1 starts and remains running until we release it.
|
||||
resolveCodexCreate();
|
||||
|
||||
const [firstOutcome, secondOutcome] = await Promise.allSettled([firstSwitch, secondSwitch]);
|
||||
expect(firstOutcome.status).toBe("fulfilled");
|
||||
if (firstOutcome.status === "fulfilled") {
|
||||
expect(firstOutcome.value.agent?.provider).toBe("codex");
|
||||
}
|
||||
expect(secondOutcome.status).toBe("rejected");
|
||||
if (secondOutcome.status === "rejected") {
|
||||
expect(String(secondOutcome.reason)).toMatch(/running/i);
|
||||
}
|
||||
|
||||
// Codex session must NOT have been closed mid-turn and Copilot must NOT have opened a session.
|
||||
expect(codex.sessions).toHaveLength(1);
|
||||
expect(codex.sessions[0].closed).toBe(false);
|
||||
expect(copilot.sessions).toHaveLength(0);
|
||||
|
||||
// Let Codex turn 1 complete and verify its reply persisted cleanly.
|
||||
resolveCodexTurn();
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
|
||||
const timeline = await client1.client.fetchAgentTimeline(agent.id, {
|
||||
direction: "tail",
|
||||
limit: 50,
|
||||
});
|
||||
expect(timeline.entries.filter((e) => e.item.type === "provider_switch")).toHaveLength(1);
|
||||
expect(
|
||||
timeline.entries.some(
|
||||
(e) => e.item.type === "assistant_message" && e.item.text === "codex reply 1",
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("aborts a provider switch cleanly when a concurrent plain message starts a turn during target session creation", async () => {
|
||||
const cwd = mkdtempSync(join(tmpdir(), "paseo-provider-switch-plain-race-e2e-"));
|
||||
onTestFinished(() => rmSync(cwd, { recursive: true, force: true }));
|
||||
|
||||
const claude = new E2EFakeClient("claude");
|
||||
const codex = new E2EFakeClient("codex", true);
|
||||
daemon = await createTestPaseoDaemon({
|
||||
agentClients: { claude, codex },
|
||||
});
|
||||
|
||||
const url = `ws://127.0.0.1:${daemon.port}/ws`;
|
||||
const client1 = await connectClient(url);
|
||||
const client2 = await connectClient(url);
|
||||
|
||||
const agent = await client1.client.createAgent({ provider: "claude", cwd });
|
||||
await client1.client.sendMessage(agent.id, "First Claude turn", undefined, {
|
||||
messageId: "msg-pr-1",
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
|
||||
let resolveCodexCreate!: () => void;
|
||||
codex.createSessionGate = new Promise<void>((resolve) => {
|
||||
resolveCodexCreate = resolve;
|
||||
});
|
||||
let resolveCodexCreateStarted!: () => void;
|
||||
const codexCreateStarted = new Promise<void>((resolve) => {
|
||||
resolveCodexCreateStarted = resolve;
|
||||
});
|
||||
codex.onCreateSessionStarted = resolveCodexCreateStarted;
|
||||
|
||||
let resolveClaudeTurn!: () => void;
|
||||
claude.turnCompletionGate = new Promise<void>((resolve) => {
|
||||
resolveClaudeTurn = resolve;
|
||||
});
|
||||
let resolveClaudeTurnStarted!: () => void;
|
||||
const claudeTurnStarted = new Promise<void>((resolve) => {
|
||||
resolveClaudeTurnStarted = resolve;
|
||||
});
|
||||
claude.onTurnStarted = resolveClaudeTurnStarted;
|
||||
|
||||
const switchPromise = client1.client.switchAgentProvider(agent.id, {
|
||||
provider: "codex",
|
||||
text: "Switch to Codex",
|
||||
messageId: "msg-pr-sw",
|
||||
});
|
||||
await codexCreateStarted;
|
||||
|
||||
// Start a direct foreground turn on the live Claude session while Codex createSession is awaiting.
|
||||
const directStream = daemon.daemon.agentManager.streamAgent(agent.id, "Stay on Claude", {
|
||||
clientMessageId: "msg-pr-stay",
|
||||
});
|
||||
const drainDirectStream = (async () => {
|
||||
for await (const _event of directStream) {
|
||||
// drain to completion
|
||||
}
|
||||
})();
|
||||
await claudeTurnStarted;
|
||||
|
||||
// Now let Codex session creation finish while Claude's turn is actively running.
|
||||
resolveCodexCreate();
|
||||
|
||||
await expect(switchPromise).rejects.toThrow(/running/i);
|
||||
expect(claude.sessions[0].closed).toBe(false);
|
||||
expect(codex.sessions).toHaveLength(1);
|
||||
expect(codex.sessions[0].closed).toBe(true);
|
||||
|
||||
resolveClaudeTurn();
|
||||
await drainDirectStream;
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
|
||||
const timeline = await client2.client.fetchAgentTimeline(agent.id, {
|
||||
direction: "tail",
|
||||
limit: 50,
|
||||
});
|
||||
expect(timeline.entries.filter((e) => e.item.type === "provider_switch")).toHaveLength(0);
|
||||
expect(
|
||||
timeline.entries.some(
|
||||
(e) => e.item.type === "assistant_message" && e.item.text === "claude reply 2",
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("excludes turns rewound during target session startup from the switch handoff", async () => {
|
||||
const cwd = mkdtempSync(join(tmpdir(), "paseo-provider-switch-rewind-race-e2e-"));
|
||||
onTestFinished(() => rmSync(cwd, { recursive: true, force: true }));
|
||||
|
||||
const claude = new E2EFakeClient("claude");
|
||||
const codex = new E2EFakeClient("codex", true);
|
||||
daemon = await createTestPaseoDaemon({
|
||||
agentClients: { claude, codex },
|
||||
});
|
||||
|
||||
const url = `ws://127.0.0.1:${daemon.port}/ws`;
|
||||
const client1 = await connectClient(url);
|
||||
const client2 = await connectClient(url);
|
||||
|
||||
const agent = await client1.client.createAgent({ provider: "claude", cwd });
|
||||
await client1.client.sendMessage(agent.id, "Keep this requirement", undefined, {
|
||||
messageId: "msg-rw-1",
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
await client1.client.sendMessage(agent.id, "Discard this requirement", undefined, {
|
||||
messageId: "msg-rw-2",
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
|
||||
const beforeRewind = await client1.client.fetchAgentTimeline(agent.id, {
|
||||
direction: "tail",
|
||||
limit: 50,
|
||||
});
|
||||
const discardRow = beforeRewind.entries.find(
|
||||
(e) => e.item.type === "user_message" && e.item.text === "Discard this requirement",
|
||||
);
|
||||
expect(discardRow?.item.type).toBe("user_message");
|
||||
const discardMessageId =
|
||||
discardRow?.item.type === "user_message" ? discardRow.item.messageId : undefined;
|
||||
expect(discardMessageId).toBeTruthy();
|
||||
|
||||
let resolveCodexCreate!: () => void;
|
||||
codex.createSessionGate = new Promise<void>((resolve) => {
|
||||
resolveCodexCreate = resolve;
|
||||
});
|
||||
let resolveCodexCreateStarted!: () => void;
|
||||
const codexCreateStarted = new Promise<void>((resolve) => {
|
||||
resolveCodexCreateStarted = resolve;
|
||||
});
|
||||
codex.onCreateSessionStarted = resolveCodexCreateStarted;
|
||||
|
||||
// Client 1 begins switching to Codex; target startup pauses.
|
||||
const switchPromise = client1.client.switchAgentProvider(agent.id, {
|
||||
provider: "codex",
|
||||
text: "Continue on Codex",
|
||||
messageId: "msg-rw-sw",
|
||||
});
|
||||
await codexCreateStarted;
|
||||
|
||||
try {
|
||||
// Client 2 rewinds the second Claude turn while Codex is still opening.
|
||||
const rewindResp = await client2.client.rewindAgent(
|
||||
agent.id,
|
||||
discardMessageId!,
|
||||
"conversation",
|
||||
);
|
||||
expect(rewindResp.ok).toBe(true);
|
||||
} finally {
|
||||
// Always release Codex session startup so daemon teardown never hangs on failure.
|
||||
resolveCodexCreate();
|
||||
}
|
||||
const switched = await switchPromise;
|
||||
expect(switched.agent?.provider).toBe("codex");
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
|
||||
// Codex's first prompt handoff MUST contain the kept turn and MUST NOT contain the rewound turn.
|
||||
expect(codex.sessions).toHaveLength(1);
|
||||
const firstCodexPrompt = renderProviderPromptText(codex.sessions[0].receivedPrompts[0]);
|
||||
expect(firstCodexPrompt).toContain("Keep this requirement");
|
||||
expect(firstCodexPrompt).not.toContain("Discard this requirement");
|
||||
});
|
||||
|
||||
it("rejects stale expectedProvider model edits that arrive during a provider switch instead of applying them to the new provider", async () => {
|
||||
const cwd = mkdtempSync(join(tmpdir(), "paseo-provider-switch-expected-provider-e2e-"));
|
||||
onTestFinished(() => rmSync(cwd, { recursive: true, force: true }));
|
||||
|
||||
const claude = new E2EFakeClient("claude");
|
||||
const codex = new E2EFakeClient("codex", true);
|
||||
daemon = await createTestPaseoDaemon({
|
||||
agentClients: { claude, codex },
|
||||
});
|
||||
|
||||
const url = `ws://127.0.0.1:${daemon.port}/ws`;
|
||||
const client1 = await connectClient(url);
|
||||
const client2 = await connectClient(url);
|
||||
|
||||
const agent = await client1.client.createAgent({ provider: "claude", cwd });
|
||||
await client1.client.sendMessage(agent.id, "Start on Claude", undefined, {
|
||||
messageId: "msg-ep-1",
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
|
||||
let resolveCodexAvail!: () => void;
|
||||
codex.availabilityGate = new Promise<void>((resolve) => {
|
||||
resolveCodexAvail = resolve;
|
||||
});
|
||||
let resolveCodexAvailStarted!: () => void;
|
||||
const codexAvailStarted = new Promise<void>((resolve) => {
|
||||
resolveCodexAvailStarted = resolve;
|
||||
});
|
||||
codex.onAvailabilityCheckStarted = resolveCodexAvailStarted;
|
||||
|
||||
let resolveCodexCreate!: () => void;
|
||||
codex.createSessionGate = new Promise<void>((resolve) => {
|
||||
resolveCodexCreate = resolve;
|
||||
});
|
||||
let resolveCodexCreateStarted!: () => void;
|
||||
const codexCreateStarted = new Promise<void>((resolve) => {
|
||||
resolveCodexCreateStarted = resolve;
|
||||
});
|
||||
codex.onCreateSessionStarted = resolveCodexCreateStarted;
|
||||
|
||||
const switchPromise = client1.client.switchAgentProvider(agent.id, {
|
||||
provider: "codex",
|
||||
text: "Switch to Codex",
|
||||
messageId: "msg-ep-sw",
|
||||
});
|
||||
await codexAvailStarted;
|
||||
|
||||
// An older client omitting expectedProvider during the availability check MUST also reject.
|
||||
const legacyDuringAvail = client2.client.setAgentModel(agent.id, "claude-opus-avail").then(
|
||||
() => ({ status: "fulfilled" as const }),
|
||||
(error: unknown) => ({ status: "rejected" as const, error }),
|
||||
);
|
||||
await new Promise((resolve) => setTimeout(resolve, 30));
|
||||
resolveCodexAvail();
|
||||
await codexCreateStarted;
|
||||
|
||||
// Both a current client sending expectedProvider: "claude" AND an older client omitting
|
||||
// expectedProvider MUST reject during the switch instead of applying "claude-opus" to Codex.
|
||||
const staleModelEdit = client2.client
|
||||
.setAgentModel(agent.id, "claude-opus", { expectedProvider: "claude" })
|
||||
.then(
|
||||
() => ({ status: "fulfilled" as const }),
|
||||
(error: unknown) => ({ status: "rejected" as const, error }),
|
||||
);
|
||||
const legacyModelEdit = client2.client.setAgentModel(agent.id, "claude-opus-legacy").then(
|
||||
() => ({ status: "fulfilled" as const }),
|
||||
(error: unknown) => ({ status: "rejected" as const, error }),
|
||||
);
|
||||
await new Promise((resolve) => setTimeout(resolve, 30));
|
||||
|
||||
resolveCodexCreate();
|
||||
const [switched, availEditOutcome, staleEditOutcome, legacyEditOutcome] = await Promise.all([
|
||||
switchPromise,
|
||||
legacyDuringAvail,
|
||||
staleModelEdit,
|
||||
legacyModelEdit,
|
||||
]);
|
||||
expect(switched.agent?.provider).toBe("codex");
|
||||
|
||||
// All three stale Claude model edits MUST reject instead of applying to Codex!
|
||||
expect(availEditOutcome.status).toBe("rejected");
|
||||
if (availEditOutcome.status === "rejected") {
|
||||
expect(String(availEditOutcome.error)).toMatch(/switching providers/i);
|
||||
}
|
||||
expect(staleEditOutcome.status).toBe("rejected");
|
||||
if (staleEditOutcome.status === "rejected") {
|
||||
expect(String(staleEditOutcome.error)).toMatch(/provider 'claude'.*now using 'codex'/i);
|
||||
}
|
||||
expect(legacyEditOutcome.status).toBe("rejected");
|
||||
if (legacyEditOutcome.status === "rejected") {
|
||||
expect(String(legacyEditOutcome.error)).toMatch(/switching providers/i);
|
||||
}
|
||||
expect(codex.sessions).toHaveLength(1);
|
||||
expect(codex.sessions[0].setModelCalls).toEqual([]);
|
||||
|
||||
// Once the switch completes, both expectedProvider: "codex" and legacy edits (omitting expectedProvider) succeed.
|
||||
await client1.client.setAgentModel(agent.id, "gpt-5.4", { expectedProvider: "codex" });
|
||||
await client2.client.setAgentModel(agent.id, "gpt-5.4-mini");
|
||||
expect(codex.sessions[0].setModelCalls).toEqual(["gpt-5.4", "gpt-5.4-mini"]);
|
||||
});
|
||||
|
||||
it("keeps waitForFinish following a provider switch started while the target session is still opening", async () => {
|
||||
const cwd = mkdtempSync(join(tmpdir(), "paseo-provider-switch-wait-startup-e2e-"));
|
||||
onTestFinished(() => rmSync(cwd, { recursive: true, force: true }));
|
||||
|
||||
const claude = new E2EFakeClient("claude");
|
||||
const codex = new E2EFakeClient("codex", true);
|
||||
daemon = await createTestPaseoDaemon({
|
||||
agentClients: { claude, codex },
|
||||
});
|
||||
|
||||
const url = `ws://127.0.0.1:${daemon.port}/ws`;
|
||||
const client1 = await connectClient(url);
|
||||
const client2 = await connectClient(url);
|
||||
|
||||
const agent = await client1.client.createAgent({ provider: "claude", cwd });
|
||||
await client1.client.sendMessage(agent.id, "First Claude turn", undefined, {
|
||||
messageId: "msg-ws-1",
|
||||
});
|
||||
const firstFinish = await client2.client.waitForFinish(agent.id, 10_000);
|
||||
expect(firstFinish.status).toBe("idle");
|
||||
expect(firstFinish.lastMessage).toBe("claude reply 1");
|
||||
|
||||
let resolveCodexCreate!: () => void;
|
||||
codex.createSessionGate = new Promise<void>((resolve) => {
|
||||
resolveCodexCreate = resolve;
|
||||
});
|
||||
let resolveCodexCreateStarted!: () => void;
|
||||
const codexCreateStarted = new Promise<void>((resolve) => {
|
||||
resolveCodexCreateStarted = resolve;
|
||||
});
|
||||
codex.onCreateSessionStarted = resolveCodexCreateStarted;
|
||||
|
||||
let resolveCodexTurn!: () => void;
|
||||
codex.turnCompletionGate = new Promise<void>((resolve) => {
|
||||
resolveCodexTurn = resolve;
|
||||
});
|
||||
let resolveCodexTurnStarted!: () => void;
|
||||
const codexTurnStarted = new Promise<void>((resolve) => {
|
||||
resolveCodexTurnStarted = resolve;
|
||||
});
|
||||
codex.onTurnStarted = resolveCodexTurnStarted;
|
||||
|
||||
// Client 1 starts switching to Codex; pause during Codex createSession.
|
||||
const switchPromise = client1.client.switchAgentProvider(agent.id, {
|
||||
provider: "codex",
|
||||
text: "Switch to Codex",
|
||||
messageId: "msg-ws-sw",
|
||||
});
|
||||
await codexCreateStarted;
|
||||
|
||||
// During target startup, the source session is NOT yet blocked from normal turns/rewinds,
|
||||
// while Client 2's waitForFinish must wait for the switch instead of returning "claude reply 1".
|
||||
expect(daemon.daemon.agentManager.hasInFlightRun(agent.id)).toBe(false);
|
||||
let waitSettled = false;
|
||||
const waitDuringStartup = client2.client.waitForFinish(agent.id, 15_000).then((res) => {
|
||||
waitSettled = true;
|
||||
return res;
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 40));
|
||||
expect(waitSettled).toBe(false);
|
||||
|
||||
// Let Codex finish opening and start turn 1; waitForFinish must still stay attached.
|
||||
resolveCodexCreate();
|
||||
await codexTurnStarted;
|
||||
await new Promise((resolve) => setTimeout(resolve, 40));
|
||||
expect(waitSettled).toBe(false);
|
||||
|
||||
// Finish Codex's first turn and confirm Client 2 receives Codex's reply, not Claude's.
|
||||
resolveCodexTurn();
|
||||
const [switched, finish] = await Promise.all([switchPromise, waitDuringStartup]);
|
||||
expect(switched.agent?.provider).toBe("codex");
|
||||
expect(finish.status).toBe("idle");
|
||||
expect(finish.final?.provider).toBe("codex");
|
||||
expect(finish.lastMessage).toBe("codex reply 1");
|
||||
});
|
||||
});
|
||||
@@ -5792,6 +5792,8 @@ describe("agent config setters", () => {
|
||||
return {
|
||||
waitForAgentClose: vi.fn().mockResolvedValue(undefined),
|
||||
getAgent: vi.fn(() => ({ id: "agent-1" })),
|
||||
assertSettingsMutationAllowedDuringSwitch: vi.fn(),
|
||||
waitForProviderSwitchUnlessAborted: vi.fn(async () => undefined),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -89,6 +89,7 @@ import {
|
||||
} from "./agent/agent-loading.js";
|
||||
import {
|
||||
sendPromptToAgent,
|
||||
startAgentRun,
|
||||
waitForAgentRunStartWithTimeout,
|
||||
unarchiveAgentState,
|
||||
} from "./agent/agent-prompt.js";
|
||||
@@ -130,7 +131,11 @@ import {
|
||||
type WorkspaceLabelService,
|
||||
} from "./workspace-labels/index.js";
|
||||
|
||||
import { AgentManager, AgentRunCancellationError } from "./agent/agent-manager.js";
|
||||
import {
|
||||
AgentManager,
|
||||
AgentProviderSwitchStartError,
|
||||
AgentRunCancellationError,
|
||||
} from "./agent/agent-manager.js";
|
||||
import { buildTimelinePromptIndex } from "./agent/timeline-prompt-index.js";
|
||||
import { ProviderSnapshotManager } from "./agent/provider-snapshot-manager.js";
|
||||
import type {
|
||||
@@ -380,6 +385,7 @@ function clientUsesLegacyWorkspaceRestore(appVersion: string | null): boolean {
|
||||
|
||||
type DeleteFencedAgentStorage = AgentStorage & {
|
||||
beginDelete(agentId: string): void;
|
||||
abandonDelete(agentId: string): void;
|
||||
};
|
||||
|
||||
function beginAgentDeleteIfSupported(agentStorage: AgentStorage, agentId: string): void {
|
||||
@@ -388,6 +394,12 @@ function beginAgentDeleteIfSupported(agentStorage: AgentStorage, agentId: string
|
||||
}
|
||||
}
|
||||
|
||||
function abandonAgentDeleteIfSupported(agentStorage: AgentStorage, agentId: string): void {
|
||||
if ("abandonDelete" in agentStorage && typeof agentStorage.abandonDelete === "function") {
|
||||
(agentStorage as DeleteFencedAgentStorage).abandonDelete(agentId);
|
||||
}
|
||||
}
|
||||
|
||||
const FETCH_AGENTS_SORT_KEYS = ["status_priority", "created_at", "updated_at", "title"] as const;
|
||||
|
||||
export function resolveWaitForFinishError(options: {
|
||||
@@ -1182,19 +1194,27 @@ export class Session {
|
||||
emit: (msg) => this.emit(msg),
|
||||
},
|
||||
operations: {
|
||||
ensureLoaded: async (agentId) => {
|
||||
ensureLoaded: async (agentId, mutationOptions) => {
|
||||
agentManager.assertSettingsMutationAllowedDuringSwitch(agentId, mutationOptions);
|
||||
await ensureUnarchivedAgentLoaded(agentId, {
|
||||
agentManager,
|
||||
agentStorage,
|
||||
logger: this.sessionLogger,
|
||||
});
|
||||
},
|
||||
setMode: async (agentId, modeId) =>
|
||||
(await setAgentModeCommand({ agentManager }, { agentId, modeId })).notice,
|
||||
setModel: (agentId, modelId) => agentManager.setAgentModel(agentId, modelId),
|
||||
setOptions: (agentId, patch) => agentManager.setAgentOptions(agentId, patch),
|
||||
setThinking: (agentId, thinkingOptionId) =>
|
||||
agentManager.setAgentThinkingOption(agentId, thinkingOptionId),
|
||||
setMode: async (agentId, modeId, mutationOptions) =>
|
||||
(
|
||||
await setAgentModeCommand(
|
||||
{ agentManager },
|
||||
{ agentId, modeId, expectedProvider: mutationOptions?.expectedProvider },
|
||||
)
|
||||
).notice,
|
||||
setModel: (agentId, modelId, mutationOptions) =>
|
||||
agentManager.setAgentModel(agentId, modelId, mutationOptions),
|
||||
setOptions: (agentId, patch, mutationOptions) =>
|
||||
agentManager.setAgentOptions(agentId, patch, mutationOptions),
|
||||
setThinking: (agentId, thinkingOptionId, mutationOptions) =>
|
||||
agentManager.setAgentThinkingOption(agentId, thinkingOptionId, mutationOptions),
|
||||
},
|
||||
logger: this.sessionLogger,
|
||||
});
|
||||
@@ -1565,12 +1585,13 @@ export class Session {
|
||||
return owner;
|
||||
}
|
||||
|
||||
// COMPAT(timelineItemCapabilities): plugin items added in v0.8.0, notifications in v0.7.2.
|
||||
// Remove after 2027-03-07 once the supported client floor is >= v0.8.0.
|
||||
// COMPAT(timelineItemCapabilities): plugin items added in v0.8.0, notifications in v0.7.2,
|
||||
// provider switches in v0.18.0. Remove each gate after its client floor advances.
|
||||
private supportsTimelineItem(item: { type: string }, source?: object): boolean {
|
||||
let capability: ClientCapability;
|
||||
if (item.type === "notification") capability = CLIENT_CAPS.timelineNotifications;
|
||||
else if (item.type === "plugin") capability = CLIENT_CAPS.pluginTimelineItems;
|
||||
else if (item.type === "provider_switch") capability = CLIENT_CAPS.timelineProviderSwitches;
|
||||
else return true;
|
||||
return source ? this.supportsForSource(capability, source) : this.supports(capability);
|
||||
}
|
||||
@@ -3259,6 +3280,8 @@ export class Session {
|
||||
switch (msg.type) {
|
||||
case "agent.rewind.request":
|
||||
return this.handleAgentRewindRequest(msg, source);
|
||||
case "agent.provider.switch.request":
|
||||
return this.handleAgentProviderSwitchRequest(msg, source);
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
@@ -3884,14 +3907,17 @@ export class Session {
|
||||
// durable snapshot, otherwise an in-flight background write can recreate it.
|
||||
await this.agentManager.flush();
|
||||
|
||||
// History goes before the record: if it cannot be removed, the request fails and the record
|
||||
// stays, so the user still sees the agent, can keep using it, and can delete it again.
|
||||
try {
|
||||
await this.agentStorage.remove(agentId);
|
||||
await this.agentManager.deleteAgentState(agentId);
|
||||
// Directory removal is daemon-wide; agent_deleted below stays a source-scoped RPC reply.
|
||||
if (knownAgent) this.agentManager.notifyAgentRemoved(knownAgent);
|
||||
} catch (error) {
|
||||
this.sessionLogger.error({ err: error, agentId }, `Failed to fully delete agent ${agentId}`);
|
||||
abandonAgentDeleteIfSupported(this.agentStorage, agentId);
|
||||
throw error;
|
||||
}
|
||||
await this.agentStorage.remove(agentId);
|
||||
// Directory removal is daemon-wide; agent_deleted below stays a source-scoped RPC reply.
|
||||
if (knownAgent) this.agentManager.notifyAgentRemoved(knownAgent);
|
||||
|
||||
this.emit({
|
||||
type: "agent_deleted",
|
||||
@@ -5603,7 +5629,7 @@ export class Session {
|
||||
}
|
||||
const event = serializeAgentStreamEvent({
|
||||
type: "timeline",
|
||||
provider,
|
||||
provider: row.provider ?? provider,
|
||||
item: row.item,
|
||||
...(row.turnId ? { turnId: row.turnId } : {}),
|
||||
timestamp: row.timestamp,
|
||||
@@ -8772,9 +8798,11 @@ export class Session {
|
||||
...(this.appliesRewinds(source)
|
||||
? { retirements: fetchedControlTimeline.retirements }
|
||||
: {}),
|
||||
activeSegmentStartSeq: fetchedControlTimeline.activeSegmentStartSeq,
|
||||
entries: entries.map((entry) => {
|
||||
const payloadEntry = {
|
||||
provider: agentPayload.provider,
|
||||
// A row keeps the provider that wrote it; older rows have none.
|
||||
provider: entry.provider ?? agentPayload.provider,
|
||||
item: entry.item,
|
||||
timestamp: entry.timestamp,
|
||||
seqStart: entry.seqStart,
|
||||
@@ -8905,13 +8933,9 @@ export class Session {
|
||||
): Promise<void> {
|
||||
try {
|
||||
await this.loadAgentHistoryPayload(msg.agentId);
|
||||
const rows = await this.agentManager.getTimelineRows(msg.agentId);
|
||||
const timeline = await this.agentManager.fetchTimeline(msg.agentId, {
|
||||
direction: "tail",
|
||||
limit: 1,
|
||||
});
|
||||
const { head, rows } = await this.agentManager.getTimelinePrompts(msg.agentId);
|
||||
const index = buildTimelinePromptIndex(
|
||||
this.wireEpoch(timeline.epoch, timeline.retirementCount, source),
|
||||
this.wireEpoch(head.epoch, head.retirementCount, source),
|
||||
rows,
|
||||
);
|
||||
this.emitForSource(
|
||||
@@ -9244,6 +9268,152 @@ export class Session {
|
||||
return requested ?? "queue";
|
||||
}
|
||||
|
||||
private async handleAgentProviderSwitchRequest(
|
||||
msg: Extract<SessionInboundMessage, { type: "agent.provider.switch.request" }>,
|
||||
source?: object,
|
||||
): Promise<void> {
|
||||
const resolved = await this.resolveAgentIdentifier(msg.agentId);
|
||||
if (!resolved.ok) {
|
||||
this.emitForSource(
|
||||
{
|
||||
type: "agent.provider.switch.response",
|
||||
payload: {
|
||||
requestId: msg.requestId,
|
||||
agentId: msg.agentId,
|
||||
accepted: false,
|
||||
error: resolved.error,
|
||||
},
|
||||
},
|
||||
source,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const agentId = resolved.agentId;
|
||||
try {
|
||||
const prompt = buildAgentPrompt(msg.text, msg.images, msg.attachments);
|
||||
const send = async (beforeDispatch: () => Promise<void>) => {
|
||||
const admitted: {
|
||||
dispatch: Awaited<ReturnType<typeof startAgentRun>> | null;
|
||||
} = { dispatch: null };
|
||||
const switched = await this.agentManager.switchAgentProvider(agentId, {
|
||||
toProvider: msg.provider,
|
||||
model: msg.model,
|
||||
modeId: msg.modeId,
|
||||
thinkingOptionId: msg.thinkingOptionId,
|
||||
providerOptions: msg.providerOptions,
|
||||
prompt,
|
||||
messageId: msg.messageId,
|
||||
admitFirstTurn: async (result, switchReservationToken) => {
|
||||
try {
|
||||
await beforeDispatch();
|
||||
admitted.dispatch = await startAgentRun(
|
||||
this.agentManager,
|
||||
agentId,
|
||||
result.handoffPrompt,
|
||||
this.sessionLogger,
|
||||
{
|
||||
idleOnly: true,
|
||||
skipPluginReload: true,
|
||||
switchReservationToken,
|
||||
runOptions: { clientMessageId: msg.messageId },
|
||||
},
|
||||
);
|
||||
} catch (startError) {
|
||||
const liveAgent = this.agentManager.getAgent(agentId) ?? result.agent;
|
||||
throw new AgentProviderSwitchStartError(liveAgent, startError);
|
||||
}
|
||||
},
|
||||
});
|
||||
const stored = await this.agentStorage.get(agentId);
|
||||
if (stored && !stored.title && !stored.lastUserMessageAt) {
|
||||
const { provisionalTitle } = resolveCreateAgentTitles({ initialPrompt: msg.text });
|
||||
if (provisionalTitle) await this.agentManager.setTitle(agentId, provisionalTitle);
|
||||
}
|
||||
if (admitted.dispatch?.disposition === "turn_started") {
|
||||
try {
|
||||
await waitForAgentRunStartWithTimeout(
|
||||
this.agentManager,
|
||||
agentId,
|
||||
admitted.dispatch.started,
|
||||
this.delivery.requestSignal,
|
||||
);
|
||||
} catch (startError) {
|
||||
const liveAgent = this.agentManager.getAgent(agentId) ?? switched.agent;
|
||||
throw new AgentProviderSwitchStartError(liveAgent, startError);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
await this.messageReceipts.send({
|
||||
agentId,
|
||||
messageId: msg.messageId,
|
||||
request: {
|
||||
kind: "provider_switch",
|
||||
provider: msg.provider,
|
||||
model: msg.model ?? null,
|
||||
modeId: msg.modeId ?? null,
|
||||
thinkingOptionId: msg.thinkingOptionId ?? null,
|
||||
providerOptions: msg.providerOptions ?? null,
|
||||
prompt,
|
||||
},
|
||||
send,
|
||||
});
|
||||
|
||||
const agentPayload = await this.getAgentPayloadById(agentId);
|
||||
this.emitForSource(
|
||||
{
|
||||
type: "agent.provider.switch.response",
|
||||
payload: {
|
||||
requestId: msg.requestId,
|
||||
agentId,
|
||||
accepted: true,
|
||||
...(agentPayload ? { agent: agentPayload } : {}),
|
||||
error: null,
|
||||
},
|
||||
},
|
||||
source,
|
||||
);
|
||||
} catch (error) {
|
||||
if (this.delivery.requestSignal.aborted) return;
|
||||
if (error instanceof AgentProviderSwitchStartError) {
|
||||
this.handleAgentRunError(
|
||||
agentId,
|
||||
error.cause ?? error,
|
||||
"Failed to start turn after provider switch",
|
||||
);
|
||||
const agentPayload =
|
||||
(await this.getAgentPayloadById(agentId)) ?? toAgentPayload(error.agent);
|
||||
this.emitForSource(
|
||||
{
|
||||
type: "agent.provider.switch.response",
|
||||
payload: {
|
||||
requestId: msg.requestId,
|
||||
agentId,
|
||||
accepted: false,
|
||||
agent: agentPayload,
|
||||
error: errorToFriendlyMessage(error),
|
||||
},
|
||||
},
|
||||
source,
|
||||
);
|
||||
return;
|
||||
}
|
||||
this.emitForSource(
|
||||
{
|
||||
type: "agent.provider.switch.response",
|
||||
payload: {
|
||||
requestId: msg.requestId,
|
||||
agentId,
|
||||
accepted: false,
|
||||
error: errorToFriendlyMessage(error),
|
||||
},
|
||||
},
|
||||
source,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async handleSendAgentMessageRequest(
|
||||
msg: Extract<SessionInboundMessage, { type: "send_agent_message_request" }>,
|
||||
): Promise<void> {
|
||||
@@ -9418,10 +9588,9 @@ export class Session {
|
||||
: null;
|
||||
|
||||
try {
|
||||
await this.agentMessages.waitForDispatch(
|
||||
agentId,
|
||||
AbortSignal.any([abortController.signal, sourceSignal]),
|
||||
);
|
||||
const waitSignal = AbortSignal.any([abortController.signal, sourceSignal]);
|
||||
await this.agentMessages.waitForDispatch(agentId, waitSignal);
|
||||
await this.agentManager.waitForProviderSwitchUnlessAborted(agentId, waitSignal);
|
||||
|
||||
const live = this.agentManager.getAgent(agentId);
|
||||
if (!live) {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type pino from "pino";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import type { AgentProvider } from "@getpaseo/protocol/agent-types";
|
||||
import { getErrorMessage, getErrorMessageOr } from "@getpaseo/protocol/error-utils";
|
||||
import type { AgentConfigApply } from "@getpaseo/protocol/messages";
|
||||
import type { AgentProviderNotice } from "../../agent/agent-sdk-types.js";
|
||||
@@ -25,14 +26,31 @@ export interface AgentConfigSessionHost {
|
||||
* routes through setAgentModeCommand); tests wire an in-memory fake. Mode and
|
||||
* thinking yield a provider notice; model and options do not.
|
||||
*/
|
||||
export interface AgentConfigMutationOptions {
|
||||
expectedProvider?: AgentProvider;
|
||||
}
|
||||
|
||||
export interface AgentConfigOperations {
|
||||
ensureLoaded(agentId: string): Promise<void>;
|
||||
setMode(agentId: string, modeId: string): Promise<AgentProviderNotice | null>;
|
||||
setModel(agentId: string, modelId: string | null): Promise<void>;
|
||||
setOptions(agentId: string, patch: ProviderOptionsPatch): Promise<void>;
|
||||
ensureLoaded(agentId: string, options?: AgentConfigMutationOptions): Promise<void>;
|
||||
setMode(
|
||||
agentId: string,
|
||||
modeId: string,
|
||||
options?: AgentConfigMutationOptions,
|
||||
): Promise<AgentProviderNotice | null>;
|
||||
setModel(
|
||||
agentId: string,
|
||||
modelId: string | null,
|
||||
options?: AgentConfigMutationOptions,
|
||||
): Promise<void>;
|
||||
setOptions(
|
||||
agentId: string,
|
||||
patch: ProviderOptionsPatch,
|
||||
options?: AgentConfigMutationOptions,
|
||||
): Promise<void>;
|
||||
setThinking(
|
||||
agentId: string,
|
||||
thinkingOptionId: string | null,
|
||||
options?: AgentConfigMutationOptions,
|
||||
): Promise<AgentProviderNotice | null>;
|
||||
}
|
||||
|
||||
@@ -45,6 +63,7 @@ export interface AgentConfigSessionOptions {
|
||||
interface ConfigChange {
|
||||
agentId: string;
|
||||
requestId: string;
|
||||
options?: AgentConfigMutationOptions;
|
||||
logLabel: string;
|
||||
logFields: Record<string, unknown>;
|
||||
failureText: string;
|
||||
@@ -73,14 +92,16 @@ export class AgentConfigSession {
|
||||
handleSetAgentModeRequest(
|
||||
msg: Extract<SessionInboundMessage, { type: "set_agent_mode_request" }>,
|
||||
): Promise<void> {
|
||||
const { agentId, modeId, requestId } = msg;
|
||||
const { agentId, modeId, expectedProvider, requestId } = msg;
|
||||
const options = expectedProvider ? { expectedProvider } : undefined;
|
||||
return this.applyConfigChange({
|
||||
agentId,
|
||||
requestId,
|
||||
options,
|
||||
logLabel: "set_agent_mode_request",
|
||||
logFields: { agentId, modeId, requestId },
|
||||
failureText: "Failed to set agent mode",
|
||||
run: () => this.operations.setMode(agentId, modeId),
|
||||
run: () => this.operations.setMode(agentId, modeId, options),
|
||||
emitResponse: (payload) => this.host.emit({ type: "set_agent_mode_response", payload }),
|
||||
});
|
||||
}
|
||||
@@ -88,15 +109,17 @@ export class AgentConfigSession {
|
||||
handleSetAgentModelRequest(
|
||||
msg: Extract<SessionInboundMessage, { type: "set_agent_model_request" }>,
|
||||
): Promise<void> {
|
||||
const { agentId, modelId, requestId } = msg;
|
||||
const { agentId, modelId, expectedProvider, requestId } = msg;
|
||||
const options = expectedProvider ? { expectedProvider } : undefined;
|
||||
return this.applyConfigChange({
|
||||
agentId,
|
||||
requestId,
|
||||
options,
|
||||
logLabel: "set_agent_model_request",
|
||||
logFields: { agentId, modelId, requestId },
|
||||
failureText: "Failed to set agent model",
|
||||
run: async () => {
|
||||
await this.operations.setModel(agentId, modelId);
|
||||
await this.operations.setModel(agentId, modelId, options);
|
||||
return undefined;
|
||||
},
|
||||
emitResponse: (payload) => this.host.emit({ type: "set_agent_model_response", payload }),
|
||||
@@ -106,16 +129,18 @@ export class AgentConfigSession {
|
||||
handleSetAgentFeatureRequest(
|
||||
msg: Extract<SessionInboundMessage, { type: "set_agent_feature_request" }>,
|
||||
): Promise<void> {
|
||||
const { agentId, featureId, value, requestId } = msg;
|
||||
const { agentId, featureId, value, expectedProvider, requestId } = msg;
|
||||
const options = expectedProvider ? { expectedProvider } : undefined;
|
||||
return this.applyConfigChange({
|
||||
agentId,
|
||||
requestId,
|
||||
options,
|
||||
logLabel: "set_agent_feature_request",
|
||||
logFields: { agentId, featureId, value, requestId },
|
||||
failureText: "Failed to set agent feature",
|
||||
// COMPAT(featureValues): added in v0.15.0, remove after 2027-05-01. A feature is a one-key options patch.
|
||||
run: async () => {
|
||||
await this.operations.setOptions(agentId, { [featureId]: value });
|
||||
await this.operations.setOptions(agentId, { [featureId]: value }, options);
|
||||
return undefined;
|
||||
},
|
||||
emitResponse: (payload) => this.host.emit({ type: "set_agent_feature_response", payload }),
|
||||
@@ -125,14 +150,16 @@ export class AgentConfigSession {
|
||||
handleSetAgentThinkingRequest(
|
||||
msg: Extract<SessionInboundMessage, { type: "set_agent_thinking_request" }>,
|
||||
): Promise<void> {
|
||||
const { agentId, thinkingOptionId, requestId } = msg;
|
||||
const { agentId, thinkingOptionId, expectedProvider, requestId } = msg;
|
||||
const options = expectedProvider ? { expectedProvider } : undefined;
|
||||
return this.applyConfigChange({
|
||||
agentId,
|
||||
requestId,
|
||||
options,
|
||||
logLabel: "set_agent_thinking_request",
|
||||
logFields: { agentId, thinkingOptionId, requestId },
|
||||
failureText: "Failed to set agent thinking option",
|
||||
run: () => this.operations.setThinking(agentId, thinkingOptionId),
|
||||
run: () => this.operations.setThinking(agentId, thinkingOptionId, options),
|
||||
emitResponse: (payload) => this.host.emit({ type: "set_agent_thinking_response", payload }),
|
||||
});
|
||||
}
|
||||
@@ -140,14 +167,16 @@ export class AgentConfigSession {
|
||||
handleAgentConfigApplyRequest(
|
||||
msg: Extract<SessionInboundMessage, { type: "agent.config.apply.request" }>,
|
||||
): Promise<void> {
|
||||
const { agentId, config, requestId } = msg;
|
||||
const { agentId, config, expectedProvider, requestId } = msg;
|
||||
const options = expectedProvider ? { expectedProvider } : undefined;
|
||||
return this.applyConfigChange({
|
||||
agentId,
|
||||
requestId,
|
||||
options,
|
||||
logLabel: "agent.config.apply.request",
|
||||
logFields: { agentId, requestId, config },
|
||||
failureText: "Failed to apply agent config",
|
||||
run: () => this.applyBundle(agentId, config),
|
||||
run: () => this.applyBundle(agentId, config, options),
|
||||
emitResponse: (payload) => this.host.emit({ type: "agent.config.apply.response", payload }),
|
||||
});
|
||||
}
|
||||
@@ -175,37 +204,43 @@ export class AgentConfigSession {
|
||||
private async applyBundle(
|
||||
agentId: string,
|
||||
config: AgentConfigApply,
|
||||
options?: AgentConfigMutationOptions,
|
||||
): Promise<AgentProviderNotice | null> {
|
||||
let notice: AgentProviderNotice | null = null;
|
||||
|
||||
if (config.modelId !== undefined) {
|
||||
await this.operations.setModel(agentId, config.modelId);
|
||||
await this.operations.setModel(agentId, config.modelId, options);
|
||||
}
|
||||
if (config.modeId !== undefined) {
|
||||
// Await first, assign second: `notice ??= await ...` would skip the call
|
||||
// entirely once an earlier step produced a notice.
|
||||
const modeNotice = await this.operations.setMode(agentId, config.modeId);
|
||||
const modeNotice = await this.operations.setMode(agentId, config.modeId, options);
|
||||
notice ??= modeNotice;
|
||||
}
|
||||
if (config.thinkingOptionId !== undefined) {
|
||||
const thinkingNotice = await this.operations.setThinking(agentId, config.thinkingOptionId);
|
||||
const thinkingNotice = await this.operations.setThinking(
|
||||
agentId,
|
||||
config.thinkingOptionId,
|
||||
options,
|
||||
);
|
||||
notice ??= thinkingNotice;
|
||||
}
|
||||
// COMPAT(featureValues): added in v0.15.0, remove after 2027-05-01. `featureValues` is an options patch.
|
||||
const optionsPatch = { ...config.featureValues, ...config.options };
|
||||
if (Object.keys(optionsPatch).length > 0) {
|
||||
await this.operations.setOptions(agentId, optionsPatch);
|
||||
await this.operations.setOptions(agentId, optionsPatch, options);
|
||||
}
|
||||
|
||||
return notice;
|
||||
}
|
||||
|
||||
private async applyConfigChange(change: ConfigChange): Promise<void> {
|
||||
const { agentId, requestId, logLabel, logFields, failureText, run, emitResponse } = change;
|
||||
const { agentId, requestId, options, logLabel, logFields, failureText, run, emitResponse } =
|
||||
change;
|
||||
this.logger.info(logFields, `session: ${logLabel}`);
|
||||
|
||||
try {
|
||||
await this.operations.ensureLoaded(agentId);
|
||||
await this.operations.ensureLoaded(agentId, options);
|
||||
const notice = await run();
|
||||
this.logger.info(logFields, `session: ${logLabel} success`);
|
||||
emitResponse({ requestId, agentId, accepted: true, error: null, notice });
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
let directory: string | undefined;
|
||||
let count = 0;
|
||||
|
||||
/** A path for a test database that no other test uses, in a directory removed at process exit. */
|
||||
export function nextTestDatabasePath(): string {
|
||||
if (!directory) {
|
||||
const created = mkdtempSync(path.join(tmpdir(), "paseo-database-"));
|
||||
directory = created;
|
||||
process.once("exit", () => rmSync(created, { recursive: true, force: true }));
|
||||
}
|
||||
count += 1;
|
||||
return path.join(directory, `test-${count}.db`);
|
||||
}
|
||||
@@ -2178,6 +2178,8 @@ export class VoiceAssistantWebSocketServer {
|
||||
rewind: true,
|
||||
// COMPAT(timelineRewindOperations): added in v0.14.1, remove gate after 2027-05-10.
|
||||
timelineRewindOperations: true,
|
||||
// COMPAT(providerSwitching): added in v0.18.0, remove gate after 2027-11-25.
|
||||
providerSwitching: true,
|
||||
// COMPAT(agentTimelinePromptIndex): added in v0.2.X, drop the gate when floor >= v0.2.X.
|
||||
agentTimelinePromptIndex: true,
|
||||
// COMPAT(agentHistorySearch): added in v0.3.0, remove gate after 2027-02-07.
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user