mirror of
https://github.com/getpaseo/paseo.git
synced 2026-10-15 05:42:34 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a134873d47 | ||
|
|
4274b2be0d |
@@ -34,8 +34,8 @@ workflows all live in the CLI process, and the completion notification that woul
|
||||
agent never arrives. A runtime that dies mid-turn is reported by whatever is draining its stream, but
|
||||
between turns nothing is watching, so the agent sits at `idle` looking healthy while its background
|
||||
work is gone. Report that exit as a turn failure so the agent lands in `error` with a timeline entry.
|
||||
Claude and OMP report exits between turns. OMP relaunches from its session file on the next prompt;
|
||||
the unfinished turn is lost.
|
||||
Only the Claude provider does this today; the others still report a death only when a turn happens to
|
||||
be in flight.
|
||||
|
||||
### Cancellation
|
||||
|
||||
|
||||
+1
-1
@@ -193,7 +193,7 @@ Terminology:
|
||||
|
||||
Loading is inline by default. `<LoadingSpinner size={14} color={foregroundMuted} />` sits next to the thing it relates to (`packages/app/src/screens/settings/providers-section.tsx:227-231`). Page-level loading is a centered `<LoadingSpinner size="large">` (`packages/app/src/screens/sessions-screen.tsx:69-72`). Card-level loading is a single short line, not a spinner. In-row dropdown items use `<DropdownMenuItem status="pending" pendingLabel="Removing...">`; the menu item handles its own pending state.
|
||||
|
||||
Screen-level empty states use a centered, muted noun phrase and at most one ghost button (`packages/app/src/screens/sessions-screen.tsx`). Sidebar list empty states use a quiet bordered card with a left-aligned `sm` title, a muted `sm` description, and `xs` `<Button>` actions. Use `secondary` for the primary action and `outline` for a secondary action (`packages/app/src/components/sidebar/empty-states.tsx`). Keep both forms short and free of illustrations.
|
||||
Empty states are short noun phrases. Centered, muted, one or two lines. Sessions screen pairs the empty noun with a single ghost button to navigate back (`packages/app/src/screens/sessions-screen.tsx:74-81`); that pairing is the maximum elaboration. Illustrations and CTAs disguised as empty states are wrong.
|
||||
|
||||
Inline errors are a single sentence in `palette.red[300]` `xs`, sitting under the field or inside the card it relates to (`packages/app/src/screens/settings/providers-section.tsx:115-119`).
|
||||
|
||||
|
||||
@@ -99,8 +99,6 @@ Pi RPC extension UI dialog requests (`select`, `input`, `editor`, `confirm`) are
|
||||
|
||||
OpenCode adapters target v1.14.46 and v2.0.10. V2 rejects binaries older than the tested 2.0.10 SDK at runtime selection. Runtime selection uses the configured command and environment. A recognized version is cached until provider configuration reload; a failed, timed-out, or unrecognized probe retains the v1 path and retries detection on the next operation. Load v2 code and materialize its plugin only after positive v2 selection; v1 sessions remain undecorated. Keep upstream SDK types inside the version-specific adapter. OpenCode owns storage migration; a missing native session must fail resume rather than create a replacement. V2 has no native archive/unarchive operation: archiving affects Paseo only. V1 retains native archiving.
|
||||
|
||||
Use OpenCode v2 execution events to trigger turn completion, with active-state and durable-log reconciliation after admission, reconnect, and while a turn remains active. Do not use `session.wait`: a healthy turn exceeding Node's HTTP headers deadline produces a transport error while OpenCode keeps working. The live event feed has no replay, and shutdown interruption preserves the previous idle outcome, so the session snapshot alone cannot recover missed execution events. Quiet streams are healthy: v2 heartbeats are SSE comments, not application events.
|
||||
|
||||
V2.0.4 also removed the activation endpoint that gated a cold location, and a cold location registers its config-derived commands, skills, and providers asynchronously. Wait until `plugin.list` returns a populated inventory before reading the catalog or commands; an empty inventory means the location is still warming. Fail when the readiness deadline expires, including when an inventory request stalls.
|
||||
|
||||
Paseo installs its OpenCode tool bridge through `OPENCODE_CONFIG_CONTENT`. V1 accepts a plugin file; v2 silently skips configured files and requires a package directory with a server entry point. Both versions use the daemon's private loopback bridge for caller-scoped tools. Bridge context lives only in daemon memory and is removed when the Paseo session closes. The content-addressed plugin artifacts contain no session data or secrets. V2 also needs this plugin when native Paseo tools are disabled: its prompt API has no structured-output format, so the plugin supplies a schema-validated final-answer tool.
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 52 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 134 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 134 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 132 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 134 KiB |
@@ -1,122 +0,0 @@
|
||||
import path from "node:path";
|
||||
import { expect, test, type Page } from "../support/fixtures";
|
||||
import { seedWorkspace } from "../support/helpers/seed-client";
|
||||
import { openAgentRoute } from "../support/helpers/mock-agent";
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import { connectDaemonClient } from "../support/helpers/daemon-client-loader";
|
||||
|
||||
// This fixture catalog advertises Ultrafast on Sol; another model offers Fast only.
|
||||
// The real daemon discovers both through the same Codex model/list boundary.
|
||||
test.use({
|
||||
e2eDaemonConfig: {
|
||||
version: 1,
|
||||
agents: {
|
||||
providers: {
|
||||
codex: {
|
||||
enabled: true,
|
||||
command: [process.execPath, path.resolve("e2e/fixtures/catalog-codex.mjs")],
|
||||
},
|
||||
claude: { enabled: false },
|
||||
copilot: { enabled: false },
|
||||
opencode: { enabled: false },
|
||||
pi: { enabled: false },
|
||||
omp: { enabled: false },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
async function openSpeedSelector(page: Page): Promise<void> {
|
||||
const speed = page.getByRole("button", { name: /^(Select speed|Speed: .+)$/ });
|
||||
const features = page.getByRole("button", { name: "Open agent features", exact: true });
|
||||
const modelSettings = page.getByRole("button", { name: /^Select model \(/ });
|
||||
await expect(speed.or(features).or(modelSettings).filter({ visible: true }).first()).toBeVisible({
|
||||
timeout: 30_000,
|
||||
});
|
||||
if (!(await speed.isVisible())) {
|
||||
if (await features.isVisible()) await features.click();
|
||||
else await modelSettings.click();
|
||||
}
|
||||
await expect(speed).toBeVisible({ timeout: 30_000 });
|
||||
await speed.click();
|
||||
await expect(page.getByText("Normal", { exact: true }).last()).toBeVisible();
|
||||
}
|
||||
|
||||
async function selectSpeed(page: Page, label: string): Promise<void> {
|
||||
await page.getByRole("button", { name: label, exact: true }).last().click();
|
||||
const toolbarTrigger = page.getByRole("button", { name: `Speed: ${label}`, exact: true });
|
||||
const sheetTrigger = page.getByRole("button", { name: "Select speed", exact: true });
|
||||
await expect(toolbarTrigger.or(sheetTrigger)).toBeVisible();
|
||||
if (await toolbarTrigger.isVisible()) await expect(toolbarTrigger).toHaveText("");
|
||||
else await expect(sheetTrigger).toContainText(label);
|
||||
}
|
||||
|
||||
async function expectSpeedChoices(page: Page, choices: string[]): Promise<void> {
|
||||
for (const choice of ["Normal", "Fast", "Ultrafast"]) {
|
||||
const option = page.getByText(choice, { exact: true }).last();
|
||||
if (choices.includes(choice)) {
|
||||
await expect(option).toBeVisible();
|
||||
await expect(option).toBeInViewport({ ratio: 1 });
|
||||
} else await expect(option).not.toBeVisible();
|
||||
}
|
||||
}
|
||||
|
||||
async function switchAgentModel(agentId: string, modelId: string): Promise<void> {
|
||||
const client = await connectDaemonClient<
|
||||
Pick<DaemonClient, "setAgentModel" | "close" | "connect">
|
||||
>({
|
||||
clientIdPrefix: "codex-speed-model",
|
||||
});
|
||||
try {
|
||||
await client.setAgentModel(agentId, modelId);
|
||||
} finally {
|
||||
await client.close();
|
||||
}
|
||||
}
|
||||
|
||||
for (const viewport of [
|
||||
{ name: "desktop", width: 1280, height: 850 },
|
||||
{ name: "compact", width: 390, height: 844 },
|
||||
]) {
|
||||
test(`Codex catalog drives speed choices on ${viewport.name}`, async ({ page }, testInfo) => {
|
||||
test.setTimeout(180_000);
|
||||
await page.setViewportSize(viewport);
|
||||
const workspace = await seedWorkspace({ repoPrefix: "codex-speed-" });
|
||||
try {
|
||||
const agent = await workspace.client.createAgent({
|
||||
provider: "codex",
|
||||
cwd: workspace.repoPath,
|
||||
workspaceId: workspace.workspaceId,
|
||||
title: "Speed settings",
|
||||
model: "gpt-6.1-sol",
|
||||
modeId: "full-access",
|
||||
initialPrompt: "Get ready to work on this project.",
|
||||
});
|
||||
await openAgentRoute(page, { workspaceId: workspace.workspaceId, agentId: agent.id });
|
||||
if (viewport.name === "desktop") {
|
||||
const trigger = page.getByRole("button", { name: "Speed: Normal", exact: true });
|
||||
await expect(trigger).toBeVisible({ timeout: 30_000 });
|
||||
await expect(trigger).toHaveText("");
|
||||
await page.screenshot({ path: testInfo.outputPath("desktop-normal-trigger.png") });
|
||||
}
|
||||
await openSpeedSelector(page);
|
||||
await expectSpeedChoices(page, ["Normal", "Fast", "Ultrafast"]);
|
||||
await page.screenshot({ path: testInfo.outputPath(`${viewport.name}-speed-options.png`) });
|
||||
await selectSpeed(page, "Ultrafast");
|
||||
await openSpeedSelector(page);
|
||||
await expectSpeedChoices(page, ["Normal", "Fast", "Ultrafast"]);
|
||||
await page.screenshot({
|
||||
path: testInfo.outputPath(`${viewport.name}-ultrafast-selected.png`),
|
||||
});
|
||||
await selectSpeed(page, "Normal");
|
||||
if (viewport.name === "desktop") {
|
||||
await switchAgentModel(agent.id, "gpt-6-sol");
|
||||
await openSpeedSelector(page);
|
||||
await expectSpeedChoices(page, ["Normal", "Fast"]);
|
||||
await page.screenshot({ path: testInfo.outputPath("desktop-fast-only.png") });
|
||||
}
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
import { test } from "../support/fixtures";
|
||||
import {
|
||||
expectContentColumnWidth,
|
||||
expectCustomContentWidthSetting,
|
||||
expectDefaultContentWidthSetting,
|
||||
openAppearanceSettings,
|
||||
resetContentWidth,
|
||||
setContentWidth,
|
||||
} from "../support/helpers/content-width";
|
||||
import { openFileExplorer, openFileFromExplorer } from "../support/helpers/file-explorer";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
|
||||
const ULTRAWIDE_VIEWPORT = { width: 2560, height: 1080 };
|
||||
|
||||
test("widens chat and Markdown files to the chosen content width and resets to the default", async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
test.setTimeout(120_000);
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "content-width-",
|
||||
title: "Content width",
|
||||
initialPrompt: "Write a long paragraph.",
|
||||
});
|
||||
|
||||
try {
|
||||
await agent.client.waitForFinish(agent.agentId, 30_000);
|
||||
await page.setViewportSize(ULTRAWIDE_VIEWPORT);
|
||||
const assistantMessage = page.getByTestId("assistant-message").first();
|
||||
const markdownPreview = page.getByTestId("markdown-preview-frame").first();
|
||||
|
||||
await test.step("chat starts at the default width", async () => {
|
||||
await openAgentRoute(page, agent);
|
||||
await expectContentColumnWidth(assistantMessage, { max: 820 });
|
||||
});
|
||||
|
||||
await test.step("settings show the default without a reset", async () => {
|
||||
await openAppearanceSettings(page);
|
||||
await expectDefaultContentWidthSetting(page, 820);
|
||||
});
|
||||
|
||||
await test.step("a custom width is saved and offers a reset", async () => {
|
||||
await setContentWidth(page, 1600);
|
||||
await expectCustomContentWidthSetting(page, 1600);
|
||||
await page.screenshot({ path: testInfo.outputPath("settings-custom-width.png") });
|
||||
});
|
||||
|
||||
await test.step("chat and Markdown files use the custom width", async () => {
|
||||
await openAgentRoute(page, agent);
|
||||
await expectContentColumnWidth(assistantMessage, { min: 1200, max: 1600 });
|
||||
await page.screenshot({ path: testInfo.outputPath("chat-custom-width.png") });
|
||||
|
||||
await openFileExplorer(page);
|
||||
await openFileFromExplorer(page, "README.md");
|
||||
await expectContentColumnWidth(markdownPreview, { min: 1200, max: 1600 });
|
||||
await page.screenshot({ path: testInfo.outputPath("markdown-custom-width.png") });
|
||||
});
|
||||
|
||||
await test.step("reset returns to the default without storing it", async () => {
|
||||
await openAppearanceSettings(page);
|
||||
await resetContentWidth(page);
|
||||
await expectDefaultContentWidthSetting(page, 820);
|
||||
|
||||
await openAgentRoute(page, agent);
|
||||
await expectContentColumnWidth(assistantMessage, { max: 820 });
|
||||
await page.screenshot({ path: testInfo.outputPath("chat-default-width.png") });
|
||||
});
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
@@ -1,7 +1,11 @@
|
||||
import type { UsageReportEntry } from "@getpaseo/protocol/messages";
|
||||
import { expect, test, type Page } from "../support/fixtures";
|
||||
import { expectComposerVisible, submitMessage } from "../support/helpers/composer";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
import {
|
||||
openAgentRoute,
|
||||
seedMockAgentWorkspace,
|
||||
seedRunningMockAgentWorkspace,
|
||||
} from "../support/helpers/mock-agent";
|
||||
import { installUsageReportsFixture } from "../support/helpers/usage-reports";
|
||||
|
||||
const REPORT_ID = "fixture:fixture-account";
|
||||
@@ -42,6 +46,30 @@ async function openMockAgent(page: Page) {
|
||||
}
|
||||
|
||||
test.describe("usage composer pill", () => {
|
||||
test("shows the report when an existing running chat opens", async ({ page }) => {
|
||||
test.setTimeout(180_000);
|
||||
const usage = await installUsageReportsFixture(page, {
|
||||
agentReportIds: [REPORT_ID],
|
||||
lists: [[agentEntry(42)]],
|
||||
});
|
||||
const session = await seedRunningMockAgentWorkspace({
|
||||
repoPrefix: "usage-running-",
|
||||
title: "Running usage pill",
|
||||
initialPrompt: "Show usage during the turn.",
|
||||
model: "one-minute-stream",
|
||||
});
|
||||
try {
|
||||
await openAgentRoute(page, session);
|
||||
await expectComposerVisible(page);
|
||||
await expect(page.getByTestId("usage-composer-pill")).toContainText("42%", {
|
||||
timeout: 20_000,
|
||||
});
|
||||
expect(usage.agentRequests()[0]).toEqual({ agentId: session.agentId });
|
||||
} finally {
|
||||
await session.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("opens the cached report without a request and shows when it was fetched", async ({
|
||||
page,
|
||||
}) => {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { existsSync, writeFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import {
|
||||
restoreArchivedWorkspace,
|
||||
@@ -355,88 +354,6 @@ test.describe("Worktree restore", () => {
|
||||
.toBeNull();
|
||||
});
|
||||
|
||||
test("restores a branchless workspace so its archived agent can be used again", async ({
|
||||
page,
|
||||
}) => {
|
||||
const project = await openProjectViaDaemon(worktreeClient, tempRepo.path);
|
||||
createdProjectIds.add(project.projectKey);
|
||||
const backingWorktree = await createWorktreeViaDaemon(worktreeClient, {
|
||||
cwd: tempRepo.path,
|
||||
slug: `branchless-${randomUUID().slice(0, 8)}`,
|
||||
});
|
||||
createdProjectIds.add(backingWorktree.projectKey);
|
||||
createdWorktreeDirectories.add(backingWorktree.workspaceDirectory);
|
||||
|
||||
execFileSync("git", ["switch", "--detach", "main"], {
|
||||
cwd: backingWorktree.workspaceDirectory,
|
||||
stdio: "pipe",
|
||||
});
|
||||
const created = await worktreeClient.createWorkspace({
|
||||
source: { kind: "directory", path: backingWorktree.workspaceDirectory },
|
||||
title: "Sample workspace",
|
||||
});
|
||||
if (!created.workspace) {
|
||||
throw new Error(created.error ?? "Could not create the branchless workspace");
|
||||
}
|
||||
const workspaceId = created.workspace.id;
|
||||
const agent = await createIdleAgent(client, {
|
||||
cwd: backingWorktree.workspaceDirectory,
|
||||
workspaceId,
|
||||
title: "Archived agent",
|
||||
});
|
||||
|
||||
await archiveWorkspaceFromDaemon(worktreeClient, backingWorktree.workspaceDirectory, {
|
||||
scope: "worktree",
|
||||
});
|
||||
await expect
|
||||
.poll(() => existsSync(backingWorktree.workspaceDirectory), { timeout: 30_000 })
|
||||
.toBe(false);
|
||||
await expect.poll(() => fetchAgentArchivedAt(client, agent.id)).not.toBeNull();
|
||||
|
||||
await gotoAppShell(page);
|
||||
await waitForSidebarHydration(page);
|
||||
await openSessions(page);
|
||||
await page.getByTestId(`agent-row-${getServerId()}-${agent.id}`).click();
|
||||
await expect(page.getByText("Workspace archived", { exact: true })).toBeVisible();
|
||||
await expect(
|
||||
page.getByText(
|
||||
"Restore Sample workspace to return to its agents. A new branch will start from the saved base or the repository default.",
|
||||
{ exact: true },
|
||||
),
|
||||
).toBeVisible();
|
||||
await captureBranchlessRestoreStep(page, "01-restore-workspace.png");
|
||||
|
||||
await page.getByRole("button", { name: "Restore", exact: true }).click();
|
||||
await expect
|
||||
.poll(() => existsSync(backingWorktree.workspaceDirectory), { timeout: 30_000 })
|
||||
.toBe(true);
|
||||
await expect(page.getByRole("button", { name: "Unarchive", exact: true })).toBeVisible({
|
||||
timeout: 30_000,
|
||||
});
|
||||
await captureBranchlessRestoreStep(page, "02-unarchive-agent.png");
|
||||
|
||||
await page.getByRole("button", { name: "Unarchive", exact: true }).click();
|
||||
await expect.poll(() => fetchAgentArchivedAt(client, agent.id)).toBeNull();
|
||||
await expect(page.getByRole("textbox", { name: "Message agent..." })).toBeEditable();
|
||||
await captureBranchlessRestoreStep(page, "03-agent-ready.png");
|
||||
|
||||
const restoredHead = execFileSync("git", ["rev-parse", "HEAD"], {
|
||||
cwd: backingWorktree.workspaceDirectory,
|
||||
encoding: "utf8",
|
||||
}).trim();
|
||||
const defaultHead = execFileSync("git", ["rev-parse", "main"], {
|
||||
cwd: tempRepo.path,
|
||||
encoding: "utf8",
|
||||
}).trim();
|
||||
expect(restoredHead).toBe(defaultHead);
|
||||
expect(
|
||||
execFileSync("git", ["branch", "--show-current"], {
|
||||
cwd: backingWorktree.workspaceDirectory,
|
||||
encoding: "utf8",
|
||||
}).trim(),
|
||||
).toMatch(/^restored\//);
|
||||
});
|
||||
|
||||
test("restore failure stays visible and permits a successful retry", async ({ page }) => {
|
||||
const { agent, worktree } = await openArchivedWorkspaceFromHistory(page, "restore-retry");
|
||||
const displacedProjectPath = `${tempRepo.path}-temporarily-unavailable`;
|
||||
@@ -505,12 +422,6 @@ test.describe("Worktree restore", () => {
|
||||
});
|
||||
});
|
||||
|
||||
async function captureBranchlessRestoreStep(page: Page, filename: string): Promise<void> {
|
||||
const screenshotDirectory = path.join(tmpdir(), "paseo-branchless-restore-evidence");
|
||||
mkdirSync(screenshotDirectory, { recursive: true });
|
||||
await page.screenshot({ path: path.join(screenshotDirectory, filename), fullPage: true });
|
||||
}
|
||||
|
||||
function commitRestorableChange(cwd: string): void {
|
||||
writeFileSync(path.join(cwd, "restored-change.txt"), "preserved after restore\n");
|
||||
execFileSync("git", ["add", "restored-change.txt"], { cwd, stdio: "pipe" });
|
||||
|
||||
@@ -1,88 +0,0 @@
|
||||
import readline from "node:readline";
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
const fast = { id: "priority", name: "Fast", description: "Faster processing, increased usage" };
|
||||
const ultra = {
|
||||
id: "ultrafast",
|
||||
name: "Ultrafast",
|
||||
description: "Lowest latency, increased usage",
|
||||
};
|
||||
const models = [
|
||||
{ id: "gpt-6.1-sol", displayName: "GPT-6.1 Sol", isDefault: true, serviceTiers: [fast, ultra] },
|
||||
{ id: "gpt-6-sol", displayName: "GPT-6 Sol", serviceTiers: [fast] },
|
||||
].map((model) =>
|
||||
Object.assign(model, {
|
||||
model: model.id,
|
||||
defaultReasoningEffort: "medium",
|
||||
supportedReasoningEfforts: [{ reasoningEffort: "medium", description: "Medium" }],
|
||||
}),
|
||||
);
|
||||
|
||||
function send(message) {
|
||||
process.stdout.write(JSON.stringify(message) + "\n");
|
||||
}
|
||||
function respond(method, params) {
|
||||
switch (method) {
|
||||
case "initialize":
|
||||
return {};
|
||||
case "model/list":
|
||||
return { data: models };
|
||||
case "config/read":
|
||||
return { config: { model: models[0].id, model_reasoning_effort: "medium" } };
|
||||
case "collaborationMode/list":
|
||||
return { data: [] };
|
||||
case "skills/list":
|
||||
return { data: [] };
|
||||
case "thread/list":
|
||||
case "thread/loaded/list":
|
||||
return { data: [] };
|
||||
case "thread/start":
|
||||
return { thread: { id: randomUUID() }, model: params.model };
|
||||
case "thread/resume":
|
||||
return { thread: { id: params.threadId } };
|
||||
case "thread/read":
|
||||
return { thread: { id: params.threadId, turns: [] } };
|
||||
case "turn/start": {
|
||||
const turnId = randomUUID();
|
||||
setTimeout(() => {
|
||||
send({
|
||||
method: "turn/started",
|
||||
params: { threadId: params.threadId, turn: { id: turnId } },
|
||||
});
|
||||
send({
|
||||
method: "item/completed",
|
||||
params: {
|
||||
threadId: params.threadId,
|
||||
turnId,
|
||||
item: {
|
||||
id: randomUUID(),
|
||||
type: "agentMessage",
|
||||
text: "Ready to work on this project.",
|
||||
},
|
||||
},
|
||||
});
|
||||
send({
|
||||
method: "turn/completed",
|
||||
params: { threadId: params.threadId, turn: { id: turnId, status: "completed" } },
|
||||
});
|
||||
}, 50);
|
||||
return { turn: { id: turnId } };
|
||||
}
|
||||
default:
|
||||
throw new Error(`Unsupported Codex fixture request: ${method}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (process.argv.includes("--version")) {
|
||||
console.log("codex-cli 0.159.0");
|
||||
} else {
|
||||
readline.createInterface({ input: process.stdin }).on("line", (line) => {
|
||||
const request = JSON.parse(line);
|
||||
if (request.id === undefined) return;
|
||||
try {
|
||||
send({ id: request.id, result: respond(request.method, request.params ?? {}) });
|
||||
} catch (error) {
|
||||
send({ id: request.id, error: { code: -32601, message: error.message } });
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
import { expect, type Locator, type Page } from "@playwright/test";
|
||||
import { openSettings } from "./app";
|
||||
import { openSettingsSection } from "./settings";
|
||||
|
||||
const APP_SETTINGS_KEY = "@paseo:app-settings";
|
||||
|
||||
function contentWidthInput(page: Page): Locator {
|
||||
return page.getByLabel("Content width in pixels", { exact: true });
|
||||
}
|
||||
|
||||
function resetContentWidthButton(page: Page): Locator {
|
||||
return page.getByRole("button", { name: "Reset content width to default", exact: true });
|
||||
}
|
||||
|
||||
export async function openAppearanceSettings(page: Page): Promise<void> {
|
||||
await openSettings(page);
|
||||
await openSettingsSection(page, "appearance");
|
||||
}
|
||||
|
||||
export async function setContentWidth(page: Page, width: number): Promise<void> {
|
||||
const input = contentWidthInput(page);
|
||||
await input.fill(String(width));
|
||||
await input.press("Tab");
|
||||
}
|
||||
|
||||
export async function resetContentWidth(page: Page): Promise<void> {
|
||||
await resetContentWidthButton(page).click();
|
||||
}
|
||||
|
||||
export async function expectDefaultContentWidthSetting(page: Page, width: number): Promise<void> {
|
||||
await expect(contentWidthInput(page)).toHaveValue(String(width));
|
||||
await expect(resetContentWidthButton(page)).toHaveCount(0);
|
||||
await expect.poll(() => readStoredContentWidth(page)).toBeNull();
|
||||
}
|
||||
|
||||
export async function expectCustomContentWidthSetting(page: Page, width: number): Promise<void> {
|
||||
await expect(contentWidthInput(page)).toHaveValue(String(width));
|
||||
await expect(resetContentWidthButton(page)).toBeVisible();
|
||||
await expect.poll(() => readStoredContentWidth(page)).toBe(width);
|
||||
}
|
||||
|
||||
/** Asserts the rendered width of a content-column element stays within `max` and above `min`. */
|
||||
export async function expectContentColumnWidth(
|
||||
element: Locator,
|
||||
bounds: { min?: number; max: number },
|
||||
): Promise<void> {
|
||||
await expect(element).toBeVisible({ timeout: 30_000 });
|
||||
await expect
|
||||
.poll(async () => (await element.boundingBox())?.width ?? 0)
|
||||
.toBeLessThanOrEqual(bounds.max);
|
||||
await expect
|
||||
.poll(async () => (await element.boundingBox())?.width ?? 0)
|
||||
.toBeGreaterThan(bounds.min ?? 0);
|
||||
}
|
||||
|
||||
async function readStoredContentWidth(page: Page): Promise<unknown> {
|
||||
return page.evaluate((key) => {
|
||||
const raw = localStorage.getItem(key);
|
||||
return raw === null
|
||||
? undefined
|
||||
: (JSON.parse(raw) as { contentMaxWidth?: unknown }).contentMaxWidth;
|
||||
}, APP_SETTINGS_KEY);
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
/**
|
||||
* @vitest-environment jsdom
|
||||
*/
|
||||
import { DEFAULT_CONTENT_MAX_WIDTH } from "@/styles/theme";
|
||||
import React from "react";
|
||||
import { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
@@ -145,7 +144,6 @@ describe("createWebStreamStrategy", () => {
|
||||
listStyle: null,
|
||||
baseListContentContainerStyle: null,
|
||||
forwardListContentContainerStyle: null,
|
||||
contentMaxWidth: DEFAULT_CONTENT_MAX_WIDTH,
|
||||
})}
|
||||
</>,
|
||||
);
|
||||
@@ -189,7 +187,6 @@ describe("createWebStreamStrategy", () => {
|
||||
listStyle: null,
|
||||
baseListContentContainerStyle: null,
|
||||
forwardListContentContainerStyle: null,
|
||||
contentMaxWidth: DEFAULT_CONTENT_MAX_WIDTH,
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -236,7 +233,6 @@ describe("createWebStreamStrategy", () => {
|
||||
listStyle: null,
|
||||
baseListContentContainerStyle: null,
|
||||
forwardListContentContainerStyle: null,
|
||||
contentMaxWidth: DEFAULT_CONTENT_MAX_WIDTH,
|
||||
};
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
@@ -295,7 +291,6 @@ describe("createWebStreamStrategy", () => {
|
||||
listStyle: null,
|
||||
baseListContentContainerStyle: null,
|
||||
forwardListContentContainerStyle: null,
|
||||
contentMaxWidth: DEFAULT_CONTENT_MAX_WIDTH,
|
||||
};
|
||||
const unrevised = {
|
||||
contentById: new Set<string>(),
|
||||
@@ -359,7 +354,6 @@ describe("createWebStreamStrategy", () => {
|
||||
listStyle: null,
|
||||
baseListContentContainerStyle: null,
|
||||
forwardListContentContainerStyle: null,
|
||||
contentMaxWidth: DEFAULT_CONTENT_MAX_WIDTH,
|
||||
};
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
@@ -435,7 +429,6 @@ describe("createWebStreamStrategy", () => {
|
||||
listStyle: null,
|
||||
baseListContentContainerStyle: null,
|
||||
forwardListContentContainerStyle: null,
|
||||
contentMaxWidth: DEFAULT_CONTENT_MAX_WIDTH,
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -480,7 +473,6 @@ describe("createWebStreamStrategy", () => {
|
||||
listStyle: null,
|
||||
baseListContentContainerStyle: null,
|
||||
forwardListContentContainerStyle: null,
|
||||
contentMaxWidth: DEFAULT_CONTENT_MAX_WIDTH,
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -561,7 +553,6 @@ describe("createWebStreamStrategy", () => {
|
||||
listStyle: null,
|
||||
baseListContentContainerStyle: null,
|
||||
forwardListContentContainerStyle: null,
|
||||
contentMaxWidth: DEFAULT_CONTENT_MAX_WIDTH,
|
||||
};
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
@@ -655,7 +646,6 @@ describe("createWebStreamStrategy", () => {
|
||||
listStyle: null,
|
||||
baseListContentContainerStyle: null,
|
||||
forwardListContentContainerStyle: null,
|
||||
contentMaxWidth: DEFAULT_CONTENT_MAX_WIDTH,
|
||||
};
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
@@ -765,7 +755,6 @@ describe("createWebStreamStrategy", () => {
|
||||
listStyle: null,
|
||||
baseListContentContainerStyle: null,
|
||||
forwardListContentContainerStyle: null,
|
||||
contentMaxWidth: DEFAULT_CONTENT_MAX_WIDTH,
|
||||
};
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
@@ -871,7 +860,6 @@ describe("createWebStreamStrategy", () => {
|
||||
listStyle: null,
|
||||
baseListContentContainerStyle: null,
|
||||
forwardListContentContainerStyle: null,
|
||||
contentMaxWidth: DEFAULT_CONTENT_MAX_WIDTH,
|
||||
};
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
@@ -971,7 +959,6 @@ describe("createWebStreamStrategy", () => {
|
||||
listStyle: null,
|
||||
baseListContentContainerStyle: null,
|
||||
forwardListContentContainerStyle: null,
|
||||
contentMaxWidth: DEFAULT_CONTENT_MAX_WIDTH,
|
||||
};
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
@@ -1069,7 +1056,6 @@ describe("createWebStreamStrategy", () => {
|
||||
listStyle: null,
|
||||
baseListContentContainerStyle: null,
|
||||
forwardListContentContainerStyle: null,
|
||||
contentMaxWidth: DEFAULT_CONTENT_MAX_WIDTH,
|
||||
};
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
@@ -1189,7 +1175,6 @@ describe("createWebStreamStrategy", () => {
|
||||
listStyle: null,
|
||||
baseListContentContainerStyle: null,
|
||||
forwardListContentContainerStyle: null,
|
||||
contentMaxWidth: DEFAULT_CONTENT_MAX_WIDTH,
|
||||
};
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
@@ -1423,7 +1408,6 @@ describe("createWebStreamStrategy", () => {
|
||||
listStyle: null,
|
||||
baseListContentContainerStyle: null,
|
||||
forwardListContentContainerStyle: null,
|
||||
contentMaxWidth: DEFAULT_CONTENT_MAX_WIDTH,
|
||||
};
|
||||
const renderWithActivity = (active: boolean, input: StreamRenderInput = renderInput) => (
|
||||
<RetainedPanelActivity active={active}>{strategy.render(input)}</RetainedPanelActivity>
|
||||
|
||||
@@ -303,7 +303,6 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
hasOlderHistory,
|
||||
olderHistoryProgressKey,
|
||||
scrollEnabled,
|
||||
contentMaxWidth,
|
||||
isMobileBreakpoint,
|
||||
} = props;
|
||||
const historyVirtualized = useRevisedHistoryRows(
|
||||
@@ -404,7 +403,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
getItemKey: (index: number) => segments.historyVirtualized[index]?.id ?? index,
|
||||
estimateSize: (index: number) => {
|
||||
const row = segments.historyVirtualized[index];
|
||||
return row ? estimateStreamItemHeight(row, contentMaxWidth) : 120;
|
||||
return row ? estimateStreamItemHeight(row) : 120;
|
||||
},
|
||||
measureElement: measureVirtualElement,
|
||||
rangeExtractor,
|
||||
|
||||
@@ -92,8 +92,6 @@ export interface StreamRenderInput {
|
||||
listStyle: StyleProp<ViewStyle>;
|
||||
baseListContentContainerStyle: StyleProp<ViewStyle>;
|
||||
forwardListContentContainerStyle: StyleProp<ViewStyle>;
|
||||
// The chat column's max width. The web viewport estimates unmeasured row heights with it.
|
||||
contentMaxWidth: number;
|
||||
}
|
||||
|
||||
export interface ResolveStreamRenderStrategyInput {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import React, { memo, useCallback, useMemo, type ReactNode } from "react";
|
||||
import { View } from "react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { MAX_CONTENT_WIDTH } from "@/constants/layout";
|
||||
import { SPACING, type Theme } from "@/styles/theme";
|
||||
import type { TurnTiming } from "@/timeline/turn-time";
|
||||
import type { StreamItem } from "@/types/stream";
|
||||
@@ -214,7 +215,7 @@ function TurnFooterRow({ children }: { children: ReactNode }) {
|
||||
const stylesheet = StyleSheet.create((theme) => ({
|
||||
streamItemWrapper: {
|
||||
width: "100%",
|
||||
maxWidth: theme.contentMaxWidth,
|
||||
maxWidth: MAX_CONTENT_WIDTH,
|
||||
alignSelf: "center",
|
||||
paddingHorizontal: theme.spacing[2],
|
||||
},
|
||||
|
||||
@@ -23,7 +23,7 @@ import {
|
||||
type ViewStyle,
|
||||
} from "react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { MAX_CONTENT_WIDTH, useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import Animated, { FadeIn, FadeOut } from "react-native-reanimated";
|
||||
import { Check, ChevronDown, X } from "lucide-react-native";
|
||||
@@ -55,7 +55,7 @@ import { useSessionStore } from "@/stores/session-store";
|
||||
import { useRevealedText } from "@/hooks/use-revealed-text";
|
||||
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 { useSettings } from "@/hooks/use-settings";
|
||||
import type { ToastApi } from "@/components/toast-host";
|
||||
import { returnToTimelineTail } from "./timeline-tail-navigation";
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
@@ -349,7 +349,6 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
const autoExpandReasoning = useSettings((settings) => settings.autoExpandReasoning);
|
||||
const toolCallDetailLevel = useSettings((settings) => settings.toolCallDetailLevel);
|
||||
const chatOutlineEnabled = useSettings((settings) => settings.chatOutlineEnabled);
|
||||
const contentMaxWidth = useSettings(resolveContentMaxWidth);
|
||||
const viewportRef = useRef<StreamViewportHandle | null>(null);
|
||||
const pendingClientMessageIds = useMemo(
|
||||
() => new Set(pendingMessageSubmissions.map((submission) => submission.clientMessageId)),
|
||||
@@ -1130,7 +1129,6 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
listStyle: stylesheet.list,
|
||||
baseListContentContainerStyle: stylesheet.listContentContainer,
|
||||
forwardListContentContainerStyle: stylesheet.forwardListContentContainer,
|
||||
contentMaxWidth,
|
||||
})}
|
||||
</MessageOuterSpacingProvider>
|
||||
<ChatOutlineRail
|
||||
@@ -1624,7 +1622,7 @@ const stylesheet = StyleSheet.create((theme) => ({
|
||||
},
|
||||
contentWrapper: {
|
||||
width: "100%",
|
||||
maxWidth: theme.contentMaxWidth,
|
||||
maxWidth: MAX_CONTENT_WIDTH,
|
||||
alignSelf: "center",
|
||||
paddingHorizontal: theme.spacing[2],
|
||||
},
|
||||
@@ -1645,7 +1643,7 @@ const stylesheet = StyleSheet.create((theme) => ({
|
||||
},
|
||||
streamItemWrapper: {
|
||||
width: "100%",
|
||||
maxWidth: theme.contentMaxWidth,
|
||||
maxWidth: MAX_CONTENT_WIDTH,
|
||||
alignSelf: "center",
|
||||
paddingHorizontal: theme.spacing[2],
|
||||
},
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { DEFAULT_CONTENT_MAX_WIDTH } from "@/styles/theme";
|
||||
import type { StreamItem } from "@/types/stream";
|
||||
import {
|
||||
clearAssistantImageMetadataCache,
|
||||
@@ -124,8 +123,8 @@ describe("splitWebVirtualizedHistory", () => {
|
||||
|
||||
describe("estimateStreamItemHeight", () => {
|
||||
it("uses compact estimates for collapsed tool sequence rows", () => {
|
||||
expect(estimateStreamItemHeight(toolCall("tool", 1), DEFAULT_CONTENT_MAX_WIDTH)).toBe(40);
|
||||
expect(estimateStreamItemHeight(thought("thought", 2), DEFAULT_CONTENT_MAX_WIDTH)).toBe(40);
|
||||
expect(estimateStreamItemHeight(toolCall("tool", 1))).toBe(40);
|
||||
expect(estimateStreamItemHeight(thought("thought", 2))).toBe(40);
|
||||
});
|
||||
|
||||
it("uses a larger estimate for user messages with image attachments", () => {
|
||||
@@ -147,7 +146,7 @@ describe("estimateStreamItemHeight", () => {
|
||||
],
|
||||
};
|
||||
|
||||
expect(estimateStreamItemHeight(item, DEFAULT_CONTENT_MAX_WIDTH)).toBe(220);
|
||||
expect(estimateStreamItemHeight(item)).toBe(220);
|
||||
});
|
||||
|
||||
it("uses cached assistant image metadata when available", () => {
|
||||
@@ -166,7 +165,7 @@ describe("estimateStreamItemHeight", () => {
|
||||
timestamp: createTimestamp(2),
|
||||
};
|
||||
|
||||
expect(estimateStreamItemHeight(item, DEFAULT_CONTENT_MAX_WIDTH)).toBeGreaterThan(220);
|
||||
expect(estimateStreamItemHeight(item)).toBeGreaterThan(220);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -58,12 +58,12 @@ export interface WebVirtualizedHistoryWindow {
|
||||
mountedEntries: IndexedStreamItem[];
|
||||
}
|
||||
|
||||
export function estimateStreamItemHeight(item: StreamItem, contentMaxWidth: number): number {
|
||||
export function estimateStreamItemHeight(item: StreamItem): number {
|
||||
switch (item.kind) {
|
||||
case "user_message":
|
||||
return item.images && item.images.length > 0 ? 220 : 96;
|
||||
case "assistant_message":
|
||||
return estimateAssistantMessageHeightFromCache(item.text, contentMaxWidth) ?? 220;
|
||||
return estimateAssistantMessageHeightFromCache(item.text) ?? 220;
|
||||
case "tool_call":
|
||||
return COLLAPSED_TOOL_SEQUENCE_ROW_HEIGHT_ESTIMATE;
|
||||
case "thought":
|
||||
|
||||
@@ -37,7 +37,6 @@ interface FakeTheme {
|
||||
"4xl": number;
|
||||
};
|
||||
lineHeight: { diff: number };
|
||||
contentMaxWidth: number;
|
||||
colors: { foreground: string; syntax: Record<string, string> };
|
||||
}
|
||||
|
||||
@@ -57,7 +56,6 @@ function makeFakeTheme(): FakeTheme {
|
||||
"4xl": 26,
|
||||
},
|
||||
lineHeight: { diff: 22 },
|
||||
contentMaxWidth: 820,
|
||||
colors: { foreground: "#fff", syntax: {} },
|
||||
};
|
||||
}
|
||||
@@ -69,7 +67,6 @@ function makeInput(overrides: Partial<AppearanceInput> = {}): AppearanceInput {
|
||||
uiBaseFontSize: 14,
|
||||
contentFontSize: 15,
|
||||
codeFontSize: 12,
|
||||
contentMaxWidth: 820,
|
||||
syntaxTheme: "one",
|
||||
...overrides,
|
||||
};
|
||||
@@ -105,12 +102,6 @@ describe("applyAppearance", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("patches the content max width into the theme", () => {
|
||||
applyAppearance(makeInput({ contentMaxWidth: 1600 }));
|
||||
|
||||
expect(runCapturedUpdater().contentMaxWidth).toBe(1600);
|
||||
});
|
||||
|
||||
it("resolves an empty UI font family to the default stack", () => {
|
||||
applyAppearance(makeInput({ uiFontFamily: "" }));
|
||||
|
||||
|
||||
@@ -17,7 +17,6 @@ export interface AppearanceInput {
|
||||
uiBaseFontSize: number; // already clamped
|
||||
contentFontSize: number; // already clamped
|
||||
codeFontSize: number; // already clamped
|
||||
contentMaxWidth: number; // already clamped, default resolved
|
||||
syntaxTheme: SyntaxThemeId;
|
||||
}
|
||||
|
||||
@@ -56,7 +55,7 @@ function scaleFontSize(
|
||||
* always current and makes ordering vs `setTheme`/`setAdaptiveThemes` irrelevant.
|
||||
*
|
||||
* The updater preserves the active theme wholesale (surfaces, accents,
|
||||
* terminal) and only patches the font ramp, content width, and syntax palette.
|
||||
* terminal) and only patches the font ramp and syntax palette.
|
||||
* `updateTheme` replaces the stored theme rather than merging, so we spread
|
||||
* `...t` first.
|
||||
*/
|
||||
@@ -87,7 +86,6 @@ export function applyAppearance(input: AppearanceInput): void {
|
||||
fontFamily,
|
||||
fontSize,
|
||||
lineHeight,
|
||||
contentMaxWidth: input.contentMaxWidth,
|
||||
colors: { ...t.colors, syntax: resolveSyntaxColors(input.syntaxTheme, t.colorScheme) },
|
||||
};
|
||||
}
|
||||
@@ -96,7 +94,6 @@ export function applyAppearance(input: AppearanceInput): void {
|
||||
fontFamily,
|
||||
fontSize,
|
||||
lineHeight,
|
||||
contentMaxWidth: input.contentMaxWidth,
|
||||
colors: { ...t.colors, syntax: resolveSyntaxColors(input.syntaxTheme, t.colorScheme) },
|
||||
};
|
||||
});
|
||||
|
||||
@@ -8,12 +8,7 @@ import {
|
||||
useState,
|
||||
} from "react";
|
||||
import { UnistylesRuntime } from "react-native-unistyles";
|
||||
import {
|
||||
DEFAULT_THEME_PREFERENCE,
|
||||
resolveContentMaxWidth,
|
||||
useAppSettings,
|
||||
type AppSettings,
|
||||
} from "@/hooks/use-settings";
|
||||
import { DEFAULT_THEME_PREFERENCE, useAppSettings, type AppSettings } from "@/hooks/use-settings";
|
||||
import {
|
||||
rememberPluginThemeHost,
|
||||
usePluginThemeCatalog,
|
||||
@@ -73,7 +68,6 @@ export function AppearanceProvider({ children }: { children: ReactNode }) {
|
||||
uiBaseFontSize: settings.uiBaseFontSize,
|
||||
contentFontSize: settings.contentFontSize,
|
||||
codeFontSize: settings.codeFontSize,
|
||||
contentMaxWidth: resolveContentMaxWidth({ contentMaxWidth: settings.contentMaxWidth }),
|
||||
syntaxTheme: settings.syntaxTheme,
|
||||
});
|
||||
setHasAppliedAppearance(true);
|
||||
@@ -86,7 +80,6 @@ export function AppearanceProvider({ children }: { children: ReactNode }) {
|
||||
settings.uiBaseFontSize,
|
||||
settings.contentFontSize,
|
||||
settings.codeFontSize,
|
||||
settings.contentMaxWidth,
|
||||
settings.syntaxTheme,
|
||||
]);
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useCallback, useState } from "react";
|
||||
import { View, Text } from "react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { FOOTER_HEIGHT } from "@/constants/layout";
|
||||
import { FOOTER_HEIGHT, MAX_CONTENT_WIDTH } from "@/constants/layout";
|
||||
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
|
||||
import { KeyboardTranslateView } from "@/keyboard/shift";
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -77,7 +77,7 @@ const styles = StyleSheet.create((theme: Theme) => ({
|
||||
},
|
||||
inputAreaContent: {
|
||||
width: "100%",
|
||||
maxWidth: theme.contentMaxWidth,
|
||||
maxWidth: MAX_CONTENT_WIDTH,
|
||||
},
|
||||
callout: {
|
||||
flexDirection: "row",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type ReactNode, useCallback } from "react";
|
||||
import { useCallback } from "react";
|
||||
import { Import, Plus } from "lucide-react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Text, View } from "react-native";
|
||||
@@ -6,28 +6,6 @@ import { StyleSheet } from "react-native-unistyles";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useSidebarViewStore } from "@/stores/sidebar-view-store";
|
||||
|
||||
function SidebarEmptyStateCard({
|
||||
testID,
|
||||
title,
|
||||
description,
|
||||
children,
|
||||
}: {
|
||||
testID: string;
|
||||
title: string;
|
||||
description: string;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<View style={styles.card} testID={testID}>
|
||||
<View style={styles.copy}>
|
||||
<Text style={styles.title}>{title}</Text>
|
||||
<Text style={styles.description}>{description}</Text>
|
||||
</View>
|
||||
<View style={styles.actions}>{children}</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The two things the sidebar's workspace list says when it has no rows.
|
||||
*
|
||||
@@ -49,15 +27,13 @@ export function SidebarFilterEmptyState() {
|
||||
}, [clearLabelFilter, clearProjectFilters]);
|
||||
|
||||
return (
|
||||
<SidebarEmptyStateCard
|
||||
testID="sidebar-filter-empty-state"
|
||||
title={t("sidebar.filterEmpty.title")}
|
||||
description={t("sidebar.filterEmpty.description")}
|
||||
>
|
||||
<Button variant="secondary" size="xs" onPress={clearFilters}>
|
||||
<View style={styles.container} testID="sidebar-filter-empty-state">
|
||||
<Text style={styles.title}>{t("sidebar.filterEmpty.title")}</Text>
|
||||
<Text style={styles.description}>{t("sidebar.filterEmpty.description")}</Text>
|
||||
<Button variant="ghost" size="sm" onPress={clearFilters}>
|
||||
{t("sidebar.filterEmpty.clear")}
|
||||
</Button>
|
||||
</SidebarEmptyStateCard>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -71,44 +47,40 @@ export function SidebarProjectEmptyState({
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<SidebarEmptyStateCard
|
||||
testID="sidebar-project-empty-state"
|
||||
title={t("sidebar.project.empty.title")}
|
||||
description={t("sidebar.project.empty.description")}
|
||||
>
|
||||
<Button variant="secondary" size="xs" leftIcon={Plus} onPress={onAddProject}>
|
||||
<View style={styles.container} testID="sidebar-project-empty-state">
|
||||
<Text style={styles.title}>{t("sidebar.project.empty.title")}</Text>
|
||||
<Text style={styles.description}>{t("sidebar.project.empty.description")}</Text>
|
||||
<Button variant="ghost" size="sm" leftIcon={Plus} onPress={onAddProject}>
|
||||
{t("sidebar.actions.addProject")}
|
||||
</Button>
|
||||
<Button variant="outline" size="xs" leftIcon={Import} onPress={onImportSession}>
|
||||
<Button variant="ghost" size="sm" leftIcon={Import} onPress={onImportSession}>
|
||||
{t("importSession.title")}
|
||||
</Button>
|
||||
</SidebarEmptyStateCard>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
card: {
|
||||
marginTop: theme.spacing[3],
|
||||
padding: theme.spacing[4],
|
||||
borderWidth: 1,
|
||||
borderColor: theme.colors.border,
|
||||
borderRadius: theme.borderRadius.lg,
|
||||
},
|
||||
copy: {
|
||||
gap: theme.spacing[1],
|
||||
},
|
||||
actions: {
|
||||
flexDirection: "row",
|
||||
gap: theme.spacing[2],
|
||||
container: {
|
||||
marginHorizontal: theme.spacing[2],
|
||||
marginTop: theme.spacing[4],
|
||||
paddingTop: theme.spacing[6],
|
||||
paddingBottom: theme.spacing[4],
|
||||
paddingHorizontal: theme.spacing[4],
|
||||
borderRadius: theme.borderRadius.lg,
|
||||
backgroundColor: theme.colors.surface0,
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[3],
|
||||
},
|
||||
title: {
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.sm,
|
||||
fontWeight: theme.fontWeight.normal,
|
||||
fontWeight: theme.fontWeight.medium,
|
||||
textAlign: "center",
|
||||
},
|
||||
description: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
textAlign: "center",
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -1357,10 +1357,6 @@ function DesktopFeatureItem({
|
||||
if (feature.type === "select") {
|
||||
const FeatureIcon = getAgentFeatureIcon(feature.icon);
|
||||
const selectedOption = feature.options.find((o) => o.id === feature.value);
|
||||
const iconOnly = feature.desktopTrigger === "icon";
|
||||
const tooltip = iconOnly
|
||||
? `${feature.label}: ${selectedOption?.label ?? feature.label}`
|
||||
: getFeatureTooltip(feature);
|
||||
return (
|
||||
<>
|
||||
<Tooltip delayDuration={0} enabledOnDesktop enabledOnMobile={false}>
|
||||
@@ -1371,16 +1367,15 @@ function DesktopFeatureItem({
|
||||
surface="toolbar"
|
||||
label={feature.label}
|
||||
value={selectedOption?.label ?? feature.label}
|
||||
showToolbarLabel={!iconOnly}
|
||||
open={openSelector === featureSelector}
|
||||
disabled={disabled}
|
||||
onPress={handleSelectPress}
|
||||
accessibilityLabel={tooltip}
|
||||
accessibilityLabel={getFeatureTooltip(feature)}
|
||||
testID={`agent-feature-${feature.id}`}
|
||||
/>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top" align="center" offset={8}>
|
||||
<Text style={styles.tooltipText}>{tooltip}</Text>
|
||||
<Text style={styles.tooltipText}>{getFeatureTooltip(feature)}</Text>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
<Combobox
|
||||
|
||||
@@ -2,8 +2,7 @@ import { ComposerDockBackground } from "./internal/background";
|
||||
export { ComposerDockBackground } from "./internal/background";
|
||||
import { ScrollView } from "@/components/ui/scroll-view";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { HEADER_INNER_HEIGHT } from "@/constants/layout";
|
||||
import { resolveContentMaxWidth, useAppSettings } from "@/hooks/use-settings";
|
||||
import { HEADER_INNER_HEIGHT, MAX_CONTENT_WIDTH } from "@/constants/layout";
|
||||
import { KeyboardTranslateView } from "@/keyboard/shift";
|
||||
import { createContext, useCallback, useContext, type ReactNode } from "react";
|
||||
import { View, type LayoutChangeEvent, type ViewProps, StyleSheet } from "react-native";
|
||||
@@ -90,7 +89,6 @@ export function ComposerDock({
|
||||
centered = false,
|
||||
}: ComposerDockProps) {
|
||||
const insets = useSafeAreaInsets();
|
||||
const contentMaxWidth = resolveContentMaxWidth(useAppSettings().settings);
|
||||
// Preserve the existing centered form's visual balance on tablets.
|
||||
const bottomInset = centered ? HEADER_INNER_HEIGHT + 24 : 0;
|
||||
if (centered) {
|
||||
@@ -100,7 +98,7 @@ export function ComposerDock({
|
||||
bottomInset={bottomInset}
|
||||
centered
|
||||
>
|
||||
<KeyboardTranslateView style={[dockStyles.centered, { maxWidth: contentMaxWidth }]}>
|
||||
<KeyboardTranslateView style={dockStyles.centered}>
|
||||
<ComposerViewportContent style={dockStyles.composer}>
|
||||
<ScrollView style={dockStyles.setup} keyboardShouldPersistTaps="handled">
|
||||
{content}
|
||||
@@ -139,15 +137,13 @@ export function ComposerDock({
|
||||
);
|
||||
}
|
||||
|
||||
// Plain React Native styles: these land on Reanimated views, which must not carry
|
||||
// theme-driven Unistyles (docs/unistyles.md). The content width arrives inline.
|
||||
const dockStyles = StyleSheet.create({
|
||||
viewport: { flex: 1, overflow: "hidden" },
|
||||
surface: { flex: 1 },
|
||||
content: { flex: 1, justifyContent: "flex-end" },
|
||||
composer: { width: "100%", flexShrink: 1 },
|
||||
centeredViewport: { flex: 1, alignItems: "center", justifyContent: "center" },
|
||||
centered: { flexShrink: 1, width: "100%" },
|
||||
centered: { flexShrink: 1, width: "100%", maxWidth: MAX_CONTENT_WIDTH },
|
||||
// Reserve the composer's own capped height before the setup scroll view shrinks.
|
||||
centeredComposer: { width: "100%", flexShrink: 0 },
|
||||
setup: { flexGrow: 0, flexShrink: 1, minHeight: 0 },
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
export { ComposerDockBackground } from "./internal/background";
|
||||
import { ScrollView } from "@/components/ui/scroll-view";
|
||||
import type { ReactNode } from "react";
|
||||
import { View } from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { HEADER_INNER_HEIGHT } from "@/constants/layout";
|
||||
import { View, StyleSheet } from "react-native";
|
||||
import { HEADER_INNER_HEIGHT, MAX_CONTENT_WIDTH } from "@/constants/layout";
|
||||
|
||||
interface ComposerDockProps {
|
||||
children: [ReactNode, ReactNode, ReactNode?];
|
||||
@@ -36,7 +35,7 @@ export function ComposerDock({
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
const styles = StyleSheet.create({
|
||||
surface: { flex: 1, overflow: "hidden" },
|
||||
content: { flex: 1, justifyContent: "flex-end" },
|
||||
composer: { width: "100%", flexShrink: 1 },
|
||||
@@ -46,7 +45,7 @@ const styles = StyleSheet.create((theme) => ({
|
||||
justifyContent: "center",
|
||||
paddingBottom: HEADER_INNER_HEIGHT + 24,
|
||||
},
|
||||
form: { flexShrink: 1, width: "100%", maxWidth: theme.contentMaxWidth },
|
||||
form: { flexShrink: 1, width: "100%", maxWidth: MAX_CONTENT_WIDTH },
|
||||
centeredComposer: { flexShrink: 0 },
|
||||
setup: { flexGrow: 0, flexShrink: 1, minHeight: 0 },
|
||||
}));
|
||||
});
|
||||
|
||||
@@ -40,7 +40,11 @@ import {
|
||||
useWorkspaceAttachmentsStore,
|
||||
} from "@/attachments/workspace-attachments-store";
|
||||
import type { UserMessageImageAttachment } from "@/types/stream";
|
||||
import { COMPACT_FORM_FACTOR_WIDTH, useIsCompactFormFactor } from "@/constants/layout";
|
||||
import {
|
||||
COMPACT_FORM_FACTOR_WIDTH,
|
||||
MAX_CONTENT_WIDTH,
|
||||
useIsCompactFormFactor,
|
||||
} from "@/constants/layout";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import {
|
||||
buildWorkspaceTabPersistenceKey,
|
||||
@@ -733,7 +737,7 @@ const styles = StyleSheet.create((theme) => ({
|
||||
},
|
||||
importPillContent: {
|
||||
width: "100%",
|
||||
maxWidth: theme.contentMaxWidth,
|
||||
maxWidth: MAX_CONTENT_WIDTH,
|
||||
flexDirection: "row",
|
||||
},
|
||||
errorContainer: {
|
||||
|
||||
@@ -41,7 +41,7 @@ import {
|
||||
Paperclip,
|
||||
} from "lucide-react-native";
|
||||
import * as Clipboard from "expo-clipboard";
|
||||
import { FOOTER_HEIGHT } from "@/constants/layout";
|
||||
import { FOOTER_HEIGHT, MAX_CONTENT_WIDTH } from "@/constants/layout";
|
||||
import {
|
||||
AgentControls,
|
||||
DraftAgentControls,
|
||||
@@ -2542,7 +2542,7 @@ const styles = StyleSheet.create((theme: Theme) => ({
|
||||
inputAreaContent: {
|
||||
flexShrink: 1,
|
||||
width: "100%",
|
||||
maxWidth: theme.contentMaxWidth,
|
||||
maxWidth: MAX_CONTENT_WIDTH,
|
||||
gap: theme.spacing[3],
|
||||
},
|
||||
messageInputContainer: {
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
} from "@/components/ui/menu";
|
||||
import { StatusRing } from "@/components/status-ring";
|
||||
import { STATUS_RING_HALO_INSET } from "@/components/status-ring/geometry";
|
||||
import { MAX_CONTENT_WIDTH } from "@/constants/layout";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { getStatusDotColor } from "@/utils/status-dot-color";
|
||||
import { STATUS_INDICATOR_FILLED_DOT_SIZE } from "@/utils/status-indicator-geometry";
|
||||
@@ -327,7 +328,7 @@ const styles = StyleSheet.create((theme) => {
|
||||
},
|
||||
track: {
|
||||
width: "100%",
|
||||
maxWidth: theme.contentMaxWidth,
|
||||
maxWidth: MAX_CONTENT_WIDTH,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[1],
|
||||
|
||||
@@ -11,6 +11,8 @@ export const HEADER_INNER_HEIGHT_MOBILE = 56;
|
||||
export const WORKSPACE_SECONDARY_HEADER_HEIGHT = 36;
|
||||
export const HEADER_TOP_PADDING_MOBILE = 8;
|
||||
|
||||
// Max width for chat content (stream view, input area, new agent form)
|
||||
export const MAX_CONTENT_WIDTH = 820;
|
||||
export const COMPACT_FORM_FACTOR_WIDTH = 500;
|
||||
|
||||
// Settings uses the canonical desktop list + detail layout. Its sidebar and
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useMemo } from "react";
|
||||
import { Text, View } from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { MarkdownRenderer } from "@/components/markdown/renderer";
|
||||
import { MAX_CONTENT_WIDTH } from "@/constants/layout";
|
||||
import { parseMarkdownPreviewDocument } from "./document";
|
||||
|
||||
export function FileMarkdownPreview({ source }: { source: string }) {
|
||||
@@ -9,7 +10,7 @@ export function FileMarkdownPreview({ source }: { source: string }) {
|
||||
|
||||
return (
|
||||
<View style={styles.outerGutter}>
|
||||
<View style={styles.readingFrame} testID="markdown-preview-frame">
|
||||
<View style={styles.readingFrame}>
|
||||
{document.frontMatter.length > 0 ? (
|
||||
<View style={styles.frontMatterTable} testID="markdown-front-matter">
|
||||
{document.frontMatter.map((row, index) => (
|
||||
@@ -48,7 +49,7 @@ const styles = StyleSheet.create((theme) => ({
|
||||
},
|
||||
readingFrame: {
|
||||
width: "100%",
|
||||
maxWidth: theme.contentMaxWidth,
|
||||
maxWidth: MAX_CONTENT_WIDTH,
|
||||
alignSelf: "center",
|
||||
paddingHorizontal: theme.spacing[2],
|
||||
},
|
||||
|
||||
@@ -17,27 +17,22 @@ import {
|
||||
DEFAULT_CLIENT_SETTINGS,
|
||||
DEFAULT_CODE_FONT_SIZE,
|
||||
DEFAULT_CONTENT_FONT_SIZE,
|
||||
DEFAULT_CONTENT_MAX_WIDTH,
|
||||
DEFAULT_TERMINAL_SCROLLBACK_LINES,
|
||||
DEFAULT_THEME_PREFERENCE,
|
||||
DEFAULT_UI_BASE_FONT_SIZE,
|
||||
MAX_CODE_FONT_SIZE,
|
||||
MAX_CONTENT_FONT_SIZE,
|
||||
MAX_CONTENT_MAX_WIDTH,
|
||||
MAX_TERMINAL_SCROLLBACK_LINES,
|
||||
MAX_UI_BASE_FONT_SIZE,
|
||||
MIN_CODE_FONT_SIZE,
|
||||
MIN_CONTENT_FONT_SIZE,
|
||||
MIN_CONTENT_MAX_WIDTH,
|
||||
MIN_TERMINAL_SCROLLBACK_LINES,
|
||||
MIN_UI_BASE_FONT_SIZE,
|
||||
loadAppSettingsFromStorage as loadAppSettingsFromStoragePure,
|
||||
loadSettingsFromStorage as loadSettingsFromStoragePure,
|
||||
normalizeAppSettings,
|
||||
parseClampedFontSize,
|
||||
parseContentMaxWidth,
|
||||
parseTerminalScrollbackLines,
|
||||
resolveContentMaxWidth,
|
||||
sanitizeFontFamily,
|
||||
saveAppSettings as saveAppSettingsPure,
|
||||
type AppSettings,
|
||||
@@ -61,24 +56,19 @@ export {
|
||||
DEFAULT_CLIENT_SETTINGS,
|
||||
DEFAULT_CODE_FONT_SIZE,
|
||||
DEFAULT_CONTENT_FONT_SIZE,
|
||||
DEFAULT_CONTENT_MAX_WIDTH,
|
||||
DEFAULT_TERMINAL_SCROLLBACK_LINES,
|
||||
DEFAULT_THEME_PREFERENCE,
|
||||
DEFAULT_UI_BASE_FONT_SIZE,
|
||||
MAX_CODE_FONT_SIZE,
|
||||
MAX_CONTENT_FONT_SIZE,
|
||||
MAX_CONTENT_MAX_WIDTH,
|
||||
MAX_TERMINAL_SCROLLBACK_LINES,
|
||||
MAX_UI_BASE_FONT_SIZE,
|
||||
MIN_CODE_FONT_SIZE,
|
||||
MIN_CONTENT_FONT_SIZE,
|
||||
MIN_CONTENT_MAX_WIDTH,
|
||||
MIN_TERMINAL_SCROLLBACK_LINES,
|
||||
MIN_UI_BASE_FONT_SIZE,
|
||||
parseClampedFontSize,
|
||||
parseContentMaxWidth,
|
||||
parseTerminalScrollbackLines,
|
||||
resolveContentMaxWidth,
|
||||
sanitizeFontFamily,
|
||||
};
|
||||
export type {
|
||||
|
||||
@@ -14,7 +14,6 @@ import {
|
||||
loadSettingsFromStorage,
|
||||
parseClampedFontSize,
|
||||
parseTerminalScrollbackLines,
|
||||
resolveContentMaxWidth,
|
||||
saveAppSettings,
|
||||
type SettingsDeps,
|
||||
} from "./storage";
|
||||
@@ -23,7 +22,7 @@ import {
|
||||
DEFAULT_SIDEBAR_ROW_ITEMS,
|
||||
SIDEBAR_ROW_ITEMS,
|
||||
} from "@/components/sidebar/display-preferences/row-items";
|
||||
import { DEFAULT_CONTENT_MAX_WIDTH, THEME_OPTIONS } from "@/styles/theme";
|
||||
import { THEME_OPTIONS } from "@/styles/theme";
|
||||
|
||||
const LEGACY_SETTINGS_KEY = "@paseo:settings";
|
||||
|
||||
@@ -956,49 +955,3 @@ describe("parseClampedFontSize", () => {
|
||||
expect(parseClampedFontSize("abc", { min: 11, max: 24 })).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("content max width", () => {
|
||||
it("follows the current default until the user picks a width", async () => {
|
||||
const deps = makeDeps();
|
||||
const queryClient = new QueryClient();
|
||||
|
||||
await saveAppSettings({ queryClient, updates: { codeFontSize: 14 }, deps });
|
||||
|
||||
const stored = JSON.parse(deps.storage.entries.get(APP_SETTINGS_KEY) ?? "null");
|
||||
expect(stored.contentMaxWidth).toBeNull();
|
||||
expect(resolveContentMaxWidth(await loadAppSettingsFromStorage(deps))).toBe(
|
||||
DEFAULT_CONTENT_MAX_WIDTH,
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps a picked width and returns to the default when reset", async () => {
|
||||
const deps = makeDeps();
|
||||
const queryClient = new QueryClient();
|
||||
|
||||
await saveAppSettings({ queryClient, updates: { contentMaxWidth: 1600 }, deps });
|
||||
expect(resolveContentMaxWidth(await loadAppSettingsFromStorage(deps))).toBe(1600);
|
||||
|
||||
await saveAppSettings({ queryClient, updates: { contentMaxWidth: null }, deps });
|
||||
expect(JSON.parse(deps.storage.entries.get(APP_SETTINGS_KEY) ?? "null").contentMaxWidth).toBe(
|
||||
null,
|
||||
);
|
||||
expect(resolveContentMaxWidth(await loadAppSettingsFromStorage(deps))).toBe(
|
||||
DEFAULT_CONTENT_MAX_WIDTH,
|
||||
);
|
||||
});
|
||||
|
||||
it("clamps stored widths and drops malformed ones to the default", async () => {
|
||||
const load = (contentMaxWidth: unknown) =>
|
||||
loadAppSettingsFromStorage(
|
||||
makeDeps({
|
||||
storage: createInMemoryKeyValueStorage({
|
||||
[APP_SETTINGS_KEY]: JSON.stringify({ contentMaxWidth }),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
expect((await load(100_000)).contentMaxWidth).toBe(4000);
|
||||
expect((await load(10)).contentMaxWidth).toBe(600);
|
||||
expect((await load("wide")).contentMaxWidth).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -15,7 +15,6 @@ import {
|
||||
} from "@/components/sidebar/display-preferences/row-items";
|
||||
import { isNative } from "@/constants/platform";
|
||||
import {
|
||||
DEFAULT_CONTENT_MAX_WIDTH,
|
||||
FONT_SIZE,
|
||||
PLUGIN_THEME_PREFERENCE,
|
||||
THEME_OPTIONS,
|
||||
@@ -64,9 +63,6 @@ export const DEFAULT_CODE_FONT_SIZE = 12; // == FONT_SIZE.code
|
||||
export const MIN_CODE_FONT_SIZE = 9;
|
||||
export const MAX_CODE_FONT_SIZE = 22; // line-height 1.5×22=33 stays safe
|
||||
export const MAX_FONT_FAMILY_LENGTH = 200;
|
||||
export { DEFAULT_CONTENT_MAX_WIDTH };
|
||||
export const MIN_CONTENT_MAX_WIDTH = 600;
|
||||
export const MAX_CONTENT_MAX_WIDTH = 4000;
|
||||
|
||||
export interface AppSettings {
|
||||
theme: ThemePreference;
|
||||
@@ -82,8 +78,6 @@ export interface AppSettings {
|
||||
uiBaseFontSize: number; // clamped px, platform default 14 or 15
|
||||
contentFontSize: number; // clamped px, platform default 15 or 16
|
||||
codeFontSize: number; // clamped px, default 12
|
||||
/** Max width of chat and markdown content in px; null follows the current default. */
|
||||
contentMaxWidth: number | null;
|
||||
syntaxTheme: SyntaxThemeId; // default "one"
|
||||
workspaceTitleSource: WorkspaceTitleSource;
|
||||
sidebarWorkspaceTrailing: SidebarWorkspaceTrailing;
|
||||
@@ -138,7 +132,6 @@ export const DEFAULT_CLIENT_SETTINGS: AppSettings = {
|
||||
uiBaseFontSize: DEFAULT_UI_BASE_FONT_SIZE,
|
||||
contentFontSize: DEFAULT_CONTENT_FONT_SIZE,
|
||||
codeFontSize: DEFAULT_CODE_FONT_SIZE,
|
||||
contentMaxWidth: null,
|
||||
syntaxTheme: "one",
|
||||
workspaceTitleSource: "title",
|
||||
sidebarWorkspaceTrailing: "diff",
|
||||
@@ -225,10 +218,6 @@ const StoredAppSettingsSchema = z
|
||||
codeFontSize: clampedNumber(MIN_CODE_FONT_SIZE, MAX_CODE_FONT_SIZE).catch(
|
||||
DEFAULT_CODE_FONT_SIZE,
|
||||
),
|
||||
contentMaxWidth: z
|
||||
.null()
|
||||
.or(clampedNumber(MIN_CONTENT_MAX_WIDTH, MAX_CONTENT_MAX_WIDTH))
|
||||
.catch(null),
|
||||
syntaxTheme: z.string().refine(isSyntaxThemeId).catch("one"),
|
||||
workspaceTitleSource: z.enum(["title", "branch"]).catch("title"),
|
||||
sidebarWorkspaceTrailing: z.enum(["diff", "timestamp", "none"]).catch("diff"),
|
||||
@@ -468,14 +457,6 @@ export function parseTerminalScrollbackLines(value: unknown): number | null {
|
||||
);
|
||||
}
|
||||
|
||||
export function parseContentMaxWidth(value: unknown): number | null {
|
||||
return parseClampedFontSize(value, { min: MIN_CONTENT_MAX_WIDTH, max: MAX_CONTENT_MAX_WIDTH });
|
||||
}
|
||||
|
||||
export function resolveContentMaxWidth(settings: Pick<AppSettings, "contentMaxWidth">): number {
|
||||
return settings.contentMaxWidth ?? DEFAULT_CONTENT_MAX_WIDTH;
|
||||
}
|
||||
|
||||
export function parseClampedFontSize(
|
||||
value: unknown,
|
||||
bounds: { min: number; max: number },
|
||||
|
||||
@@ -439,9 +439,7 @@ export const ar: TranslationResources = {
|
||||
recovery: {
|
||||
archivedTitle: "مساحة العمل مؤرشفة",
|
||||
restoreDescription:
|
||||
"استعد {{workspaceName}} للعودة إلى وكلائها. ستستخدم شجرة العمل الفرع {{branch}}.",
|
||||
restoreWithoutBranchDescription:
|
||||
"استعد {{workspaceName}} للعودة إلى وكلائها. سيبدأ فرع جديد من الفرع الأساسي المحفوظ أو الفرع الافتراضي للمستودع.",
|
||||
"تمت أرشفة {{workspaceName}} وإزالة شجرة العمل الخاصة بها. استعد الفرع {{branch}} لفتحها مجددًا.",
|
||||
unarchiveDescription: "{{workspaceName}} مؤرشفة. ألغِ أرشفتها لفتحها مجددًا.",
|
||||
restoreAction: "استعادة",
|
||||
unarchiveAction: "إلغاء الأرشفة",
|
||||
@@ -2193,14 +2191,6 @@ export const ar: TranslationResources = {
|
||||
codeSizeHint: "يُستخدم للكود والفروقات ومخرجات الطرفية",
|
||||
codeSizeAccessibility: "حجم خط الكود",
|
||||
},
|
||||
layout: {
|
||||
title: "التخطيط",
|
||||
contentWidth: "عرض المحتوى",
|
||||
contentWidthHint: "أقصى عرض للمحادثة وملفات Markdown على الشاشات العريضة",
|
||||
contentWidthAccessibility: "عرض المحتوى بالبكسل",
|
||||
reset: "إعادة تعيين",
|
||||
resetAccessibility: "إعادة عرض المحتوى إلى الافتراضي",
|
||||
},
|
||||
syntax: {
|
||||
title: "بناء الجملة",
|
||||
highlightTheme: "تسليط الضوء على الموضوع",
|
||||
|
||||
@@ -436,9 +436,7 @@ export const en = {
|
||||
recovery: {
|
||||
archivedTitle: "Workspace archived",
|
||||
restoreDescription:
|
||||
"Restore {{workspaceName}} to return to its agents. Its worktree will use branch {{branch}}.",
|
||||
restoreWithoutBranchDescription:
|
||||
"Restore {{workspaceName}} to return to its agents. A new branch will start from the saved base or the repository default.",
|
||||
"{{workspaceName}} was archived and its worktree was removed. Restore branch {{branch}} to open it again.",
|
||||
unarchiveDescription: "{{workspaceName}} is archived. Unarchive it to open it again.",
|
||||
restoreAction: "Restore",
|
||||
unarchiveAction: "Unarchive",
|
||||
@@ -2317,14 +2315,6 @@ export const en = {
|
||||
codeSizeHint: "Used for code, diffs, and terminal output",
|
||||
codeSizeAccessibility: "Code font size",
|
||||
},
|
||||
layout: {
|
||||
title: "Layout",
|
||||
contentWidth: "Content width",
|
||||
contentWidthHint: "Max width of chat and Markdown files on wide screens",
|
||||
contentWidthAccessibility: "Content width in pixels",
|
||||
reset: "Reset",
|
||||
resetAccessibility: "Reset content width to default",
|
||||
},
|
||||
syntax: {
|
||||
title: "Syntax",
|
||||
highlightTheme: "Highlight theme",
|
||||
|
||||
@@ -444,9 +444,7 @@ export const es: TranslationResources = {
|
||||
recovery: {
|
||||
archivedTitle: "Espacio de trabajo archivado",
|
||||
restoreDescription:
|
||||
"Restaura {{workspaceName}} para volver a sus agentes. Su worktree usará la rama {{branch}}.",
|
||||
restoreWithoutBranchDescription:
|
||||
"Restaura {{workspaceName}} para volver a sus agentes. Se creará una rama nueva desde la base guardada o la rama predeterminada del repositorio.",
|
||||
"{{workspaceName}} se archivó y se eliminó su worktree. Restaura la rama {{branch}} para volver a abrirlo.",
|
||||
unarchiveDescription:
|
||||
"{{workspaceName}} está archivado. Desarchívalo para volver a abrirlo.",
|
||||
restoreAction: "Restaurar",
|
||||
@@ -2247,14 +2245,6 @@ export const es: TranslationResources = {
|
||||
codeSizeHint: "Se usa en código, diferencias y la salida del terminal",
|
||||
codeSizeAccessibility: "Tamaño de fuente del código",
|
||||
},
|
||||
layout: {
|
||||
title: "Diseño",
|
||||
contentWidth: "Ancho del contenido",
|
||||
contentWidthHint: "Ancho máximo del chat y de los archivos Markdown en pantallas anchas",
|
||||
contentWidthAccessibility: "Ancho del contenido en píxeles",
|
||||
reset: "Restablecer",
|
||||
resetAccessibility: "Restablecer el ancho del contenido",
|
||||
},
|
||||
syntax: {
|
||||
title: "Sintaxis",
|
||||
highlightTheme: "Tema destacado",
|
||||
|
||||
@@ -445,9 +445,7 @@ export const fr: TranslationResources = {
|
||||
recovery: {
|
||||
archivedTitle: "Espace de travail archivé",
|
||||
restoreDescription:
|
||||
"Restaurez {{workspaceName}} pour retrouver ses agents. Son worktree utilisera la branche {{branch}}.",
|
||||
restoreWithoutBranchDescription:
|
||||
"Restaurez {{workspaceName}} pour retrouver ses agents. Une nouvelle branche partira de la base enregistrée ou de la branche par défaut du dépôt.",
|
||||
"{{workspaceName}} a été archivé et son worktree supprimé. Restaurez la branche {{branch}} pour le rouvrir.",
|
||||
unarchiveDescription: "{{workspaceName}} est archivé. Désarchivez-le pour le rouvrir.",
|
||||
restoreAction: "Restaurer",
|
||||
unarchiveAction: "Désarchiver",
|
||||
@@ -2250,14 +2248,6 @@ export const fr: TranslationResources = {
|
||||
codeSizeHint: "Utilisée pour le code, les diffs et la sortie du terminal",
|
||||
codeSizeAccessibility: "Taille de la police du code",
|
||||
},
|
||||
layout: {
|
||||
title: "Mise en page",
|
||||
contentWidth: "Largeur du contenu",
|
||||
contentWidthHint: "Largeur maximale du chat et des fichiers Markdown sur les grands écrans",
|
||||
contentWidthAccessibility: "Largeur du contenu en pixels",
|
||||
reset: "Réinitialiser",
|
||||
resetAccessibility: "Réinitialiser la largeur du contenu",
|
||||
},
|
||||
syntax: {
|
||||
title: "Syntaxe",
|
||||
highlightTheme: "Thème de surbrillance",
|
||||
|
||||
@@ -444,9 +444,7 @@ export const ja: TranslationResources = {
|
||||
recovery: {
|
||||
archivedTitle: "ワークスペースはアーカイブ済みです",
|
||||
restoreDescription:
|
||||
"{{workspaceName}} を復元してエージェントに戻ります。worktree ではブランチ {{branch}} を使用します。",
|
||||
restoreWithoutBranchDescription:
|
||||
"{{workspaceName}} を復元してエージェントに戻ります。保存されたベース、またはリポジトリのデフォルトブランチから新しいブランチを作成します。",
|
||||
"{{workspaceName}} はアーカイブされ、worktree が削除されました。ブランチ {{branch}} を復元して再度開きます。",
|
||||
unarchiveDescription:
|
||||
"{{workspaceName}} はアーカイブされています。再度開くにはアーカイブを解除してください。",
|
||||
restoreAction: "復元",
|
||||
@@ -2213,14 +2211,6 @@ export const ja: TranslationResources = {
|
||||
codeSizeHint: "コード、差分、ターミナル出力に使用されます",
|
||||
codeSizeAccessibility: "コードフォントサイズ",
|
||||
},
|
||||
layout: {
|
||||
title: "レイアウト",
|
||||
contentWidth: "コンテンツ幅",
|
||||
contentWidthHint: "ワイド画面でのチャットと Markdown ファイルの最大幅",
|
||||
contentWidthAccessibility: "コンテンツ幅 (ピクセル)",
|
||||
reset: "リセット",
|
||||
resetAccessibility: "コンテンツ幅をデフォルトに戻す",
|
||||
},
|
||||
syntax: {
|
||||
title: "構文ハイライト",
|
||||
highlightTheme: "ハイライトテーマ",
|
||||
|
||||
@@ -440,9 +440,7 @@ export const ko: TranslationResources = {
|
||||
recovery: {
|
||||
archivedTitle: "워크스페이스가 보관되었습니다",
|
||||
restoreDescription:
|
||||
"{{workspaceName}}를 복원하여 에이전트로 돌아갑니다. 워크트리는 {{branch}} 브랜치를 사용합니다.",
|
||||
restoreWithoutBranchDescription:
|
||||
"{{workspaceName}}를 복원하여 에이전트로 돌아갑니다. 저장된 기반 브랜치 또는 저장소 기본 브랜치에서 새 브랜치를 만듭니다.",
|
||||
"{{workspaceName}}가 보관되고 워크트리가 제거되었습니다. 다시 열려면 {{branch}} 브랜치를 복원하세요.",
|
||||
unarchiveDescription: "{{workspaceName}}가 보관되었습니다. 다시 열려면 보관을 취소하세요.",
|
||||
restoreAction: "복원",
|
||||
unarchiveAction: "보관 취소",
|
||||
@@ -2204,14 +2202,6 @@ export const ko: TranslationResources = {
|
||||
codeSizeHint: "코드, diff 및 터미널 출력에 사용됩니다",
|
||||
codeSizeAccessibility: "코드 글꼴 크기",
|
||||
},
|
||||
layout: {
|
||||
title: "레이아웃",
|
||||
contentWidth: "콘텐츠 너비",
|
||||
contentWidthHint: "와이드 화면에서 채팅과 Markdown 파일의 최대 너비",
|
||||
contentWidthAccessibility: "콘텐츠 너비(픽셀)",
|
||||
reset: "재설정",
|
||||
resetAccessibility: "콘텐츠 너비를 기본값으로 재설정",
|
||||
},
|
||||
syntax: {
|
||||
title: "구문",
|
||||
highlightTheme: "강조 테마",
|
||||
|
||||
@@ -443,9 +443,7 @@ export const ptBR: TranslationResources = {
|
||||
recovery: {
|
||||
archivedTitle: "Workspace arquivado",
|
||||
restoreDescription:
|
||||
"Restaure {{workspaceName}} para voltar aos seus agentes. A worktree usará a branch {{branch}}.",
|
||||
restoreWithoutBranchDescription:
|
||||
"Restaure {{workspaceName}} para voltar aos seus agentes. Uma nova branch partirá da base salva ou da branch padrão do repositório.",
|
||||
"{{workspaceName}} foi arquivado e sua worktree foi removida. Restaure a branch {{branch}} para abri-lo novamente.",
|
||||
unarchiveDescription:
|
||||
"{{workspaceName}} está arquivado. Desarquive-o para abri-lo novamente.",
|
||||
restoreAction: "Restaurar",
|
||||
@@ -2228,14 +2226,6 @@ export const ptBR: TranslationResources = {
|
||||
codeSizeHint: "Usado em código, diffs e saída do terminal",
|
||||
codeSizeAccessibility: "Tamanho da fonte de código",
|
||||
},
|
||||
layout: {
|
||||
title: "Layout",
|
||||
contentWidth: "Largura do conteúdo",
|
||||
contentWidthHint: "Largura máxima do chat e dos arquivos Markdown em telas largas",
|
||||
contentWidthAccessibility: "Largura do conteúdo em pixels",
|
||||
reset: "Redefinir",
|
||||
resetAccessibility: "Redefinir a largura do conteúdo",
|
||||
},
|
||||
syntax: {
|
||||
title: "Sintaxe",
|
||||
highlightTheme: "Tema de destaque",
|
||||
|
||||
@@ -443,9 +443,7 @@ export const ru: TranslationResources = {
|
||||
recovery: {
|
||||
archivedTitle: "Рабочая область в архиве",
|
||||
restoreDescription:
|
||||
"Восстановите «{{workspaceName}}», чтобы вернуться к его агентам. Worktree будет использовать ветку {{branch}}.",
|
||||
restoreWithoutBranchDescription:
|
||||
"Восстановите «{{workspaceName}}», чтобы вернуться к его агентам. Новая ветка будет создана от сохранённой базовой или ветки репозитория по умолчанию.",
|
||||
"Рабочее пространство «{{workspaceName}}» было архивировано, а его worktree удалён. Восстановите ветку {{branch}}, чтобы снова открыть рабочее пространство.",
|
||||
unarchiveDescription:
|
||||
"Рабочее пространство «{{workspaceName}}» находится в архиве. Разархивируйте его, чтобы снова открыть.",
|
||||
restoreAction: "Восстановить",
|
||||
@@ -2233,14 +2231,6 @@ export const ru: TranslationResources = {
|
||||
codeSizeHint: "Используется для кода, диффов и вывода терминала",
|
||||
codeSizeAccessibility: "Размер шрифта кода",
|
||||
},
|
||||
layout: {
|
||||
title: "Макет",
|
||||
contentWidth: "Ширина содержимого",
|
||||
contentWidthHint: "Максимальная ширина чата и файлов Markdown на широких экранах",
|
||||
contentWidthAccessibility: "Ширина содержимого в пикселях",
|
||||
reset: "Сбросить",
|
||||
resetAccessibility: "Сбросить ширину содержимого",
|
||||
},
|
||||
syntax: {
|
||||
title: "Синтаксис",
|
||||
highlightTheme: "Тема подсветки",
|
||||
|
||||
@@ -439,9 +439,7 @@ export const zhCN: TranslationResources = {
|
||||
recovery: {
|
||||
archivedTitle: "Workspace 已归档",
|
||||
restoreDescription:
|
||||
"恢复 {{workspaceName}} 以返回其中的代理。worktree 将使用分支 {{branch}}。",
|
||||
restoreWithoutBranchDescription:
|
||||
"恢复 {{workspaceName}} 以返回其中的代理。新分支将从保存的基准分支或仓库默认分支创建。",
|
||||
"{{workspaceName}} 已归档,其 worktree 已移除。恢复分支 {{branch}} 以重新打开。",
|
||||
unarchiveDescription: "{{workspaceName}} 已归档。取消归档以重新打开。",
|
||||
restoreAction: "恢复",
|
||||
unarchiveAction: "取消归档",
|
||||
@@ -2168,14 +2166,6 @@ export const zhCN: TranslationResources = {
|
||||
codeSizeHint: "用于代码、差异和终端输出",
|
||||
codeSizeAccessibility: "代码字号",
|
||||
},
|
||||
layout: {
|
||||
title: "布局",
|
||||
contentWidth: "内容宽度",
|
||||
contentWidthHint: "宽屏上聊天和 Markdown 文件的最大宽度",
|
||||
contentWidthAccessibility: "内容宽度(像素)",
|
||||
reset: "重置",
|
||||
resetAccessibility: "将内容宽度重置为默认值",
|
||||
},
|
||||
syntax: {
|
||||
title: "语法",
|
||||
highlightTheme: "高亮主题",
|
||||
|
||||
@@ -38,7 +38,11 @@ import { getProviderIcon } from "@/components/provider-icons";
|
||||
import { useToastHost, type ToastApi, type ToastState } from "@/components/toast-host";
|
||||
import type { WorkspaceComposerAttachment } from "@/attachments/types";
|
||||
import { useWorkspaceAttachmentScopeKey } from "@/attachments/workspace-attachments-store";
|
||||
import { COMPACT_FORM_FACTOR_WIDTH, useIsCompactFormFactor } from "@/constants/layout";
|
||||
import {
|
||||
COMPACT_FORM_FACTOR_WIDTH,
|
||||
MAX_CONTENT_WIDTH,
|
||||
useIsCompactFormFactor,
|
||||
} from "@/constants/layout";
|
||||
import { isNative, isWeb } from "@/constants/platform";
|
||||
import { useAgentAttentionClear } from "@/hooks/use-agent-attention-clear";
|
||||
import { useAgentInputDraft, type AgentInputDraft } from "@/composer/draft/input-draft";
|
||||
@@ -1746,7 +1750,7 @@ const styles = StyleSheet.create((theme) => ({
|
||||
},
|
||||
timelineSyncCalloutContent: {
|
||||
width: "100%",
|
||||
maxWidth: theme.contentMaxWidth,
|
||||
maxWidth: MAX_CONTENT_WIDTH,
|
||||
},
|
||||
timelineSyncCallout: {
|
||||
flexDirection: "row",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Fragment, useCallback, useEffect, useMemo, useState } from "react";
|
||||
import type { TFunction } from "i18next";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Text, View } from "react-native";
|
||||
@@ -18,11 +18,7 @@ import {
|
||||
import { DropdownTrigger } from "@/components/ui/dropdown-trigger";
|
||||
import { SettingsSection } from "@/components/settings/headings/settings-section";
|
||||
import { useContributedThemes } from "@/appearance/provider";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
EditingTextInput as TextInput,
|
||||
type EditingTextInputHandle,
|
||||
} from "@/components/ui/text-input";
|
||||
import { EditingTextInput as TextInput } from "@/components/ui/text-input";
|
||||
import {
|
||||
MAX_CODE_FONT_SIZE,
|
||||
MAX_CONTENT_FONT_SIZE,
|
||||
@@ -31,8 +27,6 @@ import {
|
||||
MIN_CONTENT_FONT_SIZE,
|
||||
MIN_UI_BASE_FONT_SIZE,
|
||||
parseClampedFontSize,
|
||||
parseContentMaxWidth,
|
||||
resolveContentMaxWidth,
|
||||
sanitizeFontFamily,
|
||||
useAppSettings,
|
||||
type AppSettings,
|
||||
@@ -332,74 +326,6 @@ function FontSizeRow({
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Content width: numeric field (commit on blur/submit) + reset to the default
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
interface ContentWidthRowProps {
|
||||
value: AppSettings["contentMaxWidth"];
|
||||
onChange: (value: AppSettings["contentMaxWidth"]) => void;
|
||||
}
|
||||
|
||||
function ContentWidthRow({ value, onChange }: ContentWidthRowProps) {
|
||||
const { t } = useTranslation();
|
||||
const width = resolveContentMaxWidth({ contentMaxWidth: value });
|
||||
// The field is uncontrolled, so a saved or reset width is written into it directly.
|
||||
const input = useRef<EditingTextInputHandle>(null);
|
||||
|
||||
useEffect(() => {
|
||||
input.current?.replaceText(String(width));
|
||||
}, [width]);
|
||||
|
||||
const commit = useCallback(() => {
|
||||
const next = parseContentMaxWidth(input.current?.getText()) ?? width;
|
||||
input.current?.replaceText(String(next));
|
||||
// Typing the width already in effect keeps following the default.
|
||||
if (next !== width) {
|
||||
onChange(next);
|
||||
}
|
||||
}, [onChange, width]);
|
||||
|
||||
const reset = useCallback(() => {
|
||||
onChange(null);
|
||||
}, [onChange]);
|
||||
|
||||
return (
|
||||
<View style={settingsStyles.row}>
|
||||
<View style={settingsStyles.rowContent}>
|
||||
<Text style={settingsStyles.rowTitle}>{t("settings.appearance.layout.contentWidth")}</Text>
|
||||
<Text style={settingsStyles.rowHint}>
|
||||
{t("settings.appearance.layout.contentWidthHint")}
|
||||
</Text>
|
||||
</View>
|
||||
<View style={styles.sizeField}>
|
||||
{value === null ? null : (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onPress={reset}
|
||||
accessibilityLabel={t("settings.appearance.layout.resetAccessibility")}
|
||||
>
|
||||
{t("settings.appearance.layout.reset")}
|
||||
</Button>
|
||||
)}
|
||||
<TextInput
|
||||
ref={input}
|
||||
initialValue={String(width)}
|
||||
onBlur={commit}
|
||||
onSubmitEditing={commit}
|
||||
keyboardType="number-pad"
|
||||
inputMode="numeric"
|
||||
selectTextOnFocus
|
||||
style={styles.widthInput}
|
||||
accessibilityLabel={t("settings.appearance.layout.contentWidthAccessibility")}
|
||||
/>
|
||||
<Text style={styles.unit}>px</Text>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Syntax highlight theme picker (commits immediately)
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -514,13 +440,6 @@ export function AppearanceSection() {
|
||||
[selectPluginTheme],
|
||||
);
|
||||
|
||||
const handleContentMaxWidthChange = useCallback(
|
||||
(contentMaxWidth: AppSettings["contentMaxWidth"]) => {
|
||||
void updateSettings({ contentMaxWidth });
|
||||
},
|
||||
[updateSettings],
|
||||
);
|
||||
|
||||
const handleSyntaxThemeChange = useCallback(
|
||||
(syntaxTheme: SyntaxThemeId) => {
|
||||
void updateSettings({ syntaxTheme });
|
||||
@@ -684,14 +603,6 @@ export function AppearanceSection() {
|
||||
/>
|
||||
</View>
|
||||
</SettingsSection>
|
||||
<SettingsSection title={t("settings.appearance.layout.title")}>
|
||||
<View style={settingsStyles.card}>
|
||||
<ContentWidthRow
|
||||
value={settings.contentMaxWidth}
|
||||
onChange={handleContentMaxWidthChange}
|
||||
/>
|
||||
</View>
|
||||
</SettingsSection>
|
||||
<SettingsSection title={t("settings.appearance.syntax.title")}>
|
||||
<View style={settingsStyles.card}>
|
||||
<SyntaxRow value={settings.syntaxTheme} onChange={handleSyntaxThemeChange} />
|
||||
@@ -757,19 +668,6 @@ const styles = StyleSheet.create((theme) => ({
|
||||
fontSize: theme.fontSize.base,
|
||||
textAlign: "right",
|
||||
},
|
||||
widthInput: {
|
||||
width: 80,
|
||||
minHeight: 36,
|
||||
paddingVertical: theme.spacing[2],
|
||||
paddingHorizontal: theme.spacing[3],
|
||||
borderRadius: theme.borderRadius.md,
|
||||
borderWidth: theme.borderWidth[1],
|
||||
borderColor: theme.colors.border,
|
||||
backgroundColor: theme.colors.surface2,
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.base,
|
||||
textAlign: "right",
|
||||
},
|
||||
unit: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.base,
|
||||
|
||||
@@ -126,21 +126,15 @@ function ArchivedWorkspaceRecovery({
|
||||
if (recovery.phase === "failed") {
|
||||
actionLabel = t("common.actions.retry");
|
||||
}
|
||||
let description: string;
|
||||
if (recovery.recovery.action === "restore" && recovery.recovery.branch) {
|
||||
description = t("workspace.route.recovery.restoreDescription", {
|
||||
workspaceName: recovery.recovery.workspaceName,
|
||||
branch: recovery.recovery.branch,
|
||||
});
|
||||
} else if (recovery.recovery.action === "restore") {
|
||||
description = t("workspace.route.recovery.restoreWithoutBranchDescription", {
|
||||
workspaceName: recovery.recovery.workspaceName,
|
||||
});
|
||||
} else {
|
||||
description = t("workspace.route.recovery.unarchiveDescription", {
|
||||
workspaceName: recovery.recovery.workspaceName,
|
||||
});
|
||||
}
|
||||
const description =
|
||||
recovery.recovery.action === "restore"
|
||||
? t("workspace.route.recovery.restoreDescription", {
|
||||
workspaceName: recovery.recovery.workspaceName,
|
||||
branch: recovery.recovery.branch,
|
||||
})
|
||||
: t("workspace.route.recovery.unarchiveDescription", {
|
||||
workspaceName: recovery.recovery.workspaceName,
|
||||
});
|
||||
|
||||
return (
|
||||
<View style={styles.emptyState}>
|
||||
|
||||
@@ -642,10 +642,7 @@ export const DEFAULT_MONO_FONT_STACK: string = Platform.select({
|
||||
web: "SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace",
|
||||
});
|
||||
|
||||
// Chat and markdown content column; the appearance updater patches the user's width in.
|
||||
export const DEFAULT_CONTENT_MAX_WIDTH = 820;
|
||||
|
||||
// `fontSize`, `fontFamily`, `lineHeight`, and `contentMaxWidth` are deliberately widened to plain
|
||||
// `fontSize`, `fontFamily`, and `lineHeight` are deliberately widened to plain
|
||||
// `number`/`string` (not narrowed by `as const`) so the appearance updater can patch
|
||||
// them at runtime via `UnistylesRuntime.updateTheme`. The remaining tokens keep their
|
||||
// literal types.
|
||||
@@ -654,7 +651,6 @@ interface CommonTheme {
|
||||
fontSize: Record<keyof typeof FONT_SIZE, number>;
|
||||
fontFamily: { ui: string; mono: string };
|
||||
lineHeight: Record<keyof typeof LINE_HEIGHT, number>;
|
||||
contentMaxWidth: number;
|
||||
iconSize: typeof ICON_SIZE;
|
||||
fontWeight: typeof FONT_WEIGHT;
|
||||
borderRadius: typeof BORDER_RADIUS;
|
||||
@@ -667,7 +663,6 @@ const commonTheme: CommonTheme = {
|
||||
fontSize: FONT_SIZE,
|
||||
fontFamily: { ui: DEFAULT_UI_FONT_STACK, mono: DEFAULT_MONO_FONT_STACK },
|
||||
lineHeight: LINE_HEIGHT,
|
||||
contentMaxWidth: DEFAULT_CONTENT_MAX_WIDTH,
|
||||
iconSize: ICON_SIZE,
|
||||
fontWeight: FONT_WEIGHT,
|
||||
borderRadius: BORDER_RADIUS,
|
||||
|
||||
@@ -31,8 +31,13 @@ function usageReportsQueryKey(serverId: string) {
|
||||
return ["usage", "reports", serverId] as const;
|
||||
}
|
||||
|
||||
function agentUsageQueryKey(serverId: string, agentId: string, model: string | null) {
|
||||
return ["usage", "agent", serverId, agentId, model] as const;
|
||||
function agentUsageQueryKey(
|
||||
serverId: string,
|
||||
agentId: string,
|
||||
model: string | null,
|
||||
isRunning: boolean,
|
||||
) {
|
||||
return ["usage", "agent", serverId, agentId, model, isRunning] as const;
|
||||
}
|
||||
|
||||
function requireClient(serverId: string) {
|
||||
@@ -160,8 +165,7 @@ export function useUsageByHost(): {
|
||||
/**
|
||||
* The usage report for the account an agent is spending. The daemon resolves the
|
||||
* report ID, which is re-resolved when the model changes (a new key) and when a
|
||||
* turn completes (the query is paused while the agent runs, and its data is always
|
||||
* stale, so resuming refetches). The report itself is read from the shared cache.
|
||||
* turn completes (a new query key). The report itself is read from the shared cache.
|
||||
*/
|
||||
export function useAgentUsage(
|
||||
serverId: string,
|
||||
@@ -176,10 +180,10 @@ export function useAgentUsage(
|
||||
}),
|
||||
);
|
||||
const identity = useFetchQuery({
|
||||
queryKey: agentUsageQueryKey(serverId, agentId, model),
|
||||
queryKey: agentUsageQueryKey(serverId, agentId, model, isRunning),
|
||||
queryFn: async () =>
|
||||
(await requireClient(serverId).resolveAgentUsageReport({ agentId })).reportId,
|
||||
enabled: isConnected && isSupported && !isRunning,
|
||||
enabled: isConnected && isSupported,
|
||||
dataShape: "value",
|
||||
staleTimeMs: 0,
|
||||
});
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { DEFAULT_CONTENT_MAX_WIDTH } from "@/styles/theme";
|
||||
import {
|
||||
clearAssistantImageMetadataCache,
|
||||
estimateAssistantMessageHeightFromCache,
|
||||
@@ -53,7 +52,6 @@ describe("assistant image metadata", () => {
|
||||
expect(
|
||||
estimateAssistantMessageHeightFromCache(
|
||||
"Here is the screenshot\n\n",
|
||||
DEFAULT_CONTENT_MAX_WIDTH,
|
||||
),
|
||||
).toBeGreaterThan(220);
|
||||
});
|
||||
@@ -62,14 +60,8 @@ describe("assistant image metadata", () => {
|
||||
const source = `data:image/png;base64,${"a".repeat(512)}`;
|
||||
setAssistantImageMetadata({ source }, { width: 1200, height: 800 });
|
||||
|
||||
const imageOnlyHeight = estimateAssistantMessageHeightFromCache(
|
||||
``,
|
||||
DEFAULT_CONTENT_MAX_WIDTH,
|
||||
);
|
||||
const mixedHeight = estimateAssistantMessageHeightFromCache(
|
||||
`Text\n\n`,
|
||||
DEFAULT_CONTENT_MAX_WIDTH,
|
||||
);
|
||||
const imageOnlyHeight = estimateAssistantMessageHeightFromCache(``);
|
||||
const mixedHeight = estimateAssistantMessageHeightFromCache(`Text\n\n`);
|
||||
|
||||
expect(imageOnlyHeight).toBeGreaterThan(220);
|
||||
expect(mixedHeight).toBeGreaterThan(imageOnlyHeight ?? 0);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { MAX_CONTENT_WIDTH } from "@/constants/layout";
|
||||
import { resolveAssistantImageSource } from "@/utils/assistant-image-source";
|
||||
import { createImageSourceCacheKey } from "@/attachments/utils";
|
||||
|
||||
@@ -13,7 +14,7 @@ const ASSISTANT_IMAGE_METADATA_CACHE_LIMIT = 500;
|
||||
const ASSISTANT_IMAGE_PARSE_CACHE_LIMIT = 500;
|
||||
|
||||
const MARKDOWN_IMAGE_PATTERN = /!\[[^\]]*]\((<[^>]+>|[^)\n]+)\)/g;
|
||||
const ASSISTANT_IMAGE_INSET = 8;
|
||||
const ASSISTANT_IMAGE_ESTIMATE_WIDTH = MAX_CONTENT_WIDTH - 8;
|
||||
const ASSISTANT_IMAGE_MIN_HEIGHT = 160;
|
||||
const ASSISTANT_IMAGE_BLOCK_GAP = 24;
|
||||
const ASSISTANT_MESSAGE_BASE_HEIGHT = 96;
|
||||
@@ -176,10 +177,7 @@ export function extractAssistantImageSources(markdown: string): string[] {
|
||||
return parsed.sources;
|
||||
}
|
||||
|
||||
export function estimateAssistantMessageHeightFromCache(
|
||||
markdown: string,
|
||||
contentMaxWidth: number,
|
||||
): number | null {
|
||||
export function estimateAssistantMessageHeightFromCache(markdown: string): number | null {
|
||||
const parsed = assistantImageParseCache.get(markdown) ?? parseAssistantImageMarkdown(markdown);
|
||||
if (parsed.sources.length === 0) {
|
||||
return null;
|
||||
@@ -191,7 +189,7 @@ export function estimateAssistantMessageHeightFromCache(
|
||||
.map((metadata) =>
|
||||
Math.max(
|
||||
ASSISTANT_IMAGE_MIN_HEIGHT,
|
||||
Math.round((contentMaxWidth - ASSISTANT_IMAGE_INSET) / metadata.aspectRatio),
|
||||
Math.round(ASSISTANT_IMAGE_ESTIMATE_WIDTH / metadata.aspectRatio),
|
||||
),
|
||||
);
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { DEFAULT_CONTENT_MAX_WIDTH } from "@/styles/theme";
|
||||
import {
|
||||
clearAssistantMessageHeightEstimateCache,
|
||||
estimateAssistantMessageHeightFromCache,
|
||||
@@ -28,21 +27,7 @@ describe("assistant message height estimate", () => {
|
||||
height: 41.1,
|
||||
});
|
||||
|
||||
expect(
|
||||
estimateAssistantMessageHeightFromCache(
|
||||
"First paragraph\n\nSecond paragraph",
|
||||
DEFAULT_CONTENT_MAX_WIDTH,
|
||||
),
|
||||
).toBe(97);
|
||||
});
|
||||
|
||||
it("reads block heights measured at the configured content width", () => {
|
||||
setAssistantMarkdownBlockHeight({ block: "Wide paragraph", width: 1584, height: 20 });
|
||||
|
||||
expect(estimateAssistantMessageHeightFromCache("Wide paragraph", 1600)).toBe(44);
|
||||
expect(
|
||||
estimateAssistantMessageHeightFromCache("Wide paragraph", DEFAULT_CONTENT_MAX_WIDTH),
|
||||
).toBeNull();
|
||||
expect(estimateAssistantMessageHeightFromCache("First paragraph\n\nSecond paragraph")).toBe(97);
|
||||
});
|
||||
|
||||
it("falls back to image metadata when markdown blocks are not measured", () => {
|
||||
@@ -56,7 +41,6 @@ describe("assistant message height estimate", () => {
|
||||
expect(
|
||||
estimateAssistantMessageHeightFromCache(
|
||||
"Here is the screenshot\n\n",
|
||||
DEFAULT_CONTENT_MAX_WIDTH,
|
||||
),
|
||||
).toBeGreaterThan(220);
|
||||
});
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { MAX_CONTENT_WIDTH } from "@/constants/layout";
|
||||
import { estimateAssistantMessageHeightFromCache as estimateAssistantImageMessageHeightFromCache } from "@/utils/assistant-image-metadata";
|
||||
import { splitMarkdownBlocks } from "@/utils/split-markdown-blocks";
|
||||
|
||||
const ASSISTANT_MARKDOWN_BLOCK_HEIGHT_CACHE_LIMIT = 1000;
|
||||
const ASSISTANT_MARKDOWN_BLOCK_INSET = 16;
|
||||
const ASSISTANT_MARKDOWN_BLOCK_ESTIMATE_WIDTH = MAX_CONTENT_WIDTH - 16;
|
||||
const ASSISTANT_MESSAGE_VERTICAL_PADDING = 24;
|
||||
const ASSISTANT_MARKDOWN_BLOCK_GAP = 12;
|
||||
|
||||
@@ -77,10 +78,7 @@ export function setAssistantMarkdownBlockHeight(input: {
|
||||
return height;
|
||||
}
|
||||
|
||||
function estimateAssistantMarkdownBlockHeightFromCache(
|
||||
markdown: string,
|
||||
contentMaxWidth: number,
|
||||
): number | null {
|
||||
function estimateAssistantMarkdownBlockHeightFromCache(markdown: string): number | null {
|
||||
const blocks = splitMarkdownBlocks(markdown);
|
||||
if (blocks.length === 0) {
|
||||
return null;
|
||||
@@ -90,7 +88,7 @@ function estimateAssistantMarkdownBlockHeightFromCache(
|
||||
for (const block of blocks) {
|
||||
const key = createMarkdownBlockHeightKey({
|
||||
block,
|
||||
width: contentMaxWidth - ASSISTANT_MARKDOWN_BLOCK_INSET,
|
||||
width: ASSISTANT_MARKDOWN_BLOCK_ESTIMATE_WIDTH,
|
||||
});
|
||||
const cachedHeight = key ? assistantMarkdownBlockHeightCache.get(key) : undefined;
|
||||
if (cachedHeight === undefined) {
|
||||
@@ -106,13 +104,10 @@ function estimateAssistantMarkdownBlockHeightFromCache(
|
||||
);
|
||||
}
|
||||
|
||||
export function estimateAssistantMessageHeightFromCache(
|
||||
markdown: string,
|
||||
contentMaxWidth: number,
|
||||
): number | null {
|
||||
export function estimateAssistantMessageHeightFromCache(markdown: string): number | null {
|
||||
return (
|
||||
estimateAssistantMarkdownBlockHeightFromCache(markdown, contentMaxWidth) ??
|
||||
estimateAssistantImageMessageHeightFromCache(markdown, contentMaxWidth)
|
||||
estimateAssistantMarkdownBlockHeightFromCache(markdown) ??
|
||||
estimateAssistantImageMessageHeightFromCache(markdown)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -125,36 +125,6 @@ describe("daemon-manager commands", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("reports a stopped daemon without launching the CLI when no local daemon runs", async () => {
|
||||
mkdirSync(mocks.paseoHome);
|
||||
writeFileSync(path.join(mocks.paseoHome, "server-id"), "srv_existing\n");
|
||||
mocks.runExternalCliJsonCommand.mockResolvedValue({
|
||||
home: mocks.paseoHome,
|
||||
pid: null,
|
||||
startedAt: null,
|
||||
listen: null,
|
||||
hostname: null,
|
||||
localDaemon: "stopped",
|
||||
desktopManaged: false,
|
||||
connectedDaemon: "not_probed",
|
||||
});
|
||||
|
||||
const status = await createDaemonCommandHandlers().desktop_daemon_status();
|
||||
|
||||
expect(status).toMatchObject({ serverId: "", status: "stopped", pid: null });
|
||||
expect(mocks.runExternalCliJsonCommand).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reports an errored daemon when the local daemon state cannot be read", async () => {
|
||||
mkdirSync(mocks.paseoHome);
|
||||
writeFileSync(path.join(mocks.paseoHome, "paseo.pid"), "garbage");
|
||||
|
||||
const status = await createDaemonCommandHandlers().desktop_daemon_status();
|
||||
|
||||
expect(status).toMatchObject({ serverId: "", status: "errored", pid: null });
|
||||
expect(status.error).toBeTruthy();
|
||||
});
|
||||
|
||||
it("returns a local credential only for its live managed daemon listen", async () => {
|
||||
mkdirSync(mocks.paseoHome);
|
||||
const token = "a".repeat(43);
|
||||
|
||||
@@ -224,12 +224,6 @@ export async function resolveDesktopDaemonStatus(): Promise<DesktopDaemonStatus>
|
||||
const home = getPaseoHome();
|
||||
|
||||
try {
|
||||
// The app polls this while no local daemon runs. Answer that case in-process,
|
||||
// since launching the CLI once per poll keeps spawning processes while idle.
|
||||
if (!(await readDaemonInstance(home))) {
|
||||
return statusFromDaemonProbe({ localDaemon: "stopped" }, home);
|
||||
}
|
||||
|
||||
const payload = (await runExternalCliJsonCommand([
|
||||
"daemon",
|
||||
"status",
|
||||
@@ -240,7 +234,7 @@ export async function resolveDesktopDaemonStatus(): Promise<DesktopDaemonStatus>
|
||||
return statusFromDaemonProbe(payload, home);
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
logDesktopDaemonLifecycle("resolveStatus failed", { error: errorMessage });
|
||||
logDesktopDaemonLifecycle("resolveStatus CLI command failed", { error: errorMessage });
|
||||
return {
|
||||
serverId: "",
|
||||
status: "errored",
|
||||
|
||||
@@ -29,7 +29,7 @@ function harness(guest: BrowserCaptureGuest | null = null) {
|
||||
describe("browser capture service", () => {
|
||||
it("validates and rounds guest-relative bounds before capture", async () => {
|
||||
const capturePage = vi.fn(async () => image());
|
||||
const { service } = harness({ isDestroyed: () => false, getZoomFactor: () => 1, capturePage });
|
||||
const { service } = harness({ isDestroyed: () => false, capturePage });
|
||||
|
||||
await expect(
|
||||
service.capture({
|
||||
@@ -41,25 +41,9 @@ describe("browser capture service", () => {
|
||||
expect(capturePage).toHaveBeenCalledWith({ x: 0, y: 9, width: 20, height: 11 });
|
||||
});
|
||||
|
||||
it("captures the selected element when the page is zoomed", async () => {
|
||||
const capturePage = vi.fn(async () => image());
|
||||
const { service } = harness({
|
||||
isDestroyed: () => false,
|
||||
getZoomFactor: () => 1.2,
|
||||
capturePage,
|
||||
});
|
||||
|
||||
await service.capture({
|
||||
browserId: "browser-1",
|
||||
hostWebContentsId: 42,
|
||||
rect: { x: 300, y: 200, width: 120, height: 60 },
|
||||
});
|
||||
expect(capturePage).toHaveBeenCalledWith({ x: 360, y: 240, width: 144, height: 72 });
|
||||
});
|
||||
|
||||
it("rejects invalid or unavailable captures without touching the guest", async () => {
|
||||
const capturePage = vi.fn(async () => image());
|
||||
const { service } = harness({ isDestroyed: () => false, getZoomFactor: () => 1, capturePage });
|
||||
const { service } = harness({ isDestroyed: () => false, capturePage });
|
||||
|
||||
await expect(
|
||||
service.capture({ browserId: "browser-1", hostWebContentsId: 42, rect: { width: 0 } }),
|
||||
|
||||
@@ -5,7 +5,6 @@ export interface BrowserCaptureImage {
|
||||
|
||||
export interface BrowserCaptureGuest<TImage extends BrowserCaptureImage = BrowserCaptureImage> {
|
||||
isDestroyed(): boolean;
|
||||
getZoomFactor(): number;
|
||||
capturePage(rect: BrowserCaptureRect): Promise<TImage>;
|
||||
}
|
||||
|
||||
@@ -41,9 +40,7 @@ export interface BrowserCaptureService {
|
||||
copy(payload: unknown): Promise<boolean>;
|
||||
}
|
||||
|
||||
// The renderer measures the element in page CSS pixels, while capturePage
|
||||
// takes device-independent pixels, so the page zoom scales the region.
|
||||
function captureRect(value: unknown, zoomFactor: number): BrowserCaptureRect | null {
|
||||
function captureRect(value: unknown): BrowserCaptureRect | null {
|
||||
if (!value || typeof value !== "object") return null;
|
||||
const record = value as Record<string, unknown>;
|
||||
const coordinates = [record.x, record.y, record.width, record.height];
|
||||
@@ -54,9 +51,7 @@ function captureRect(value: unknown, zoomFactor: number): BrowserCaptureRect | n
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const [x, y, width, height] = (coordinates as number[]).map(
|
||||
(coordinate) => coordinate * zoomFactor,
|
||||
);
|
||||
const [x, y, width, height] = coordinates as number[];
|
||||
if (width <= 0 || height <= 0) return null;
|
||||
return {
|
||||
x: Math.max(0, Math.round(x)),
|
||||
@@ -85,9 +80,8 @@ export function createBrowserCaptureService<TImage extends BrowserCaptureImage>(
|
||||
async capture({ browserId, hostWebContentsId, rect }) {
|
||||
if (typeof browserId !== "string" || browserId.trim().length === 0) return null;
|
||||
const guest = dependencies.findGuest(browserId, hostWebContentsId);
|
||||
if (!guest || guest.isDestroyed()) return null;
|
||||
const bounds = captureRect(rect, guest.getZoomFactor());
|
||||
if (!bounds) return null;
|
||||
const bounds = captureRect(rect);
|
||||
if (!guest || guest.isDestroyed() || !bounds) return null;
|
||||
try {
|
||||
const image = await guest.capturePage(bounds);
|
||||
return image.isEmpty() ? null : image.toDataURL();
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
import type { SpawnOptions } from "node:child_process";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { listAvailableEditorTargets, openEditorTarget } from "./registry.js";
|
||||
import { createEditorTargetRuntime } from "./runtime.js";
|
||||
import { zedTarget } from "./targets/zed.js";
|
||||
|
||||
interface SpawnRecord {
|
||||
command: string;
|
||||
@@ -12,23 +10,6 @@ interface SpawnRecord {
|
||||
unrefed: boolean;
|
||||
}
|
||||
|
||||
function recordSpawns(records: SpawnRecord[]) {
|
||||
return (command: string, args: string[], options: SpawnOptions) => {
|
||||
const record = { command, args, options, unrefed: false };
|
||||
records.push(record);
|
||||
const child = {
|
||||
once(event: "error" | "spawn", handler: (error?: Error) => void) {
|
||||
if (event === "spawn") queueMicrotask(() => handler());
|
||||
return child;
|
||||
},
|
||||
unref() {
|
||||
record.unrefed = true;
|
||||
},
|
||||
};
|
||||
return child;
|
||||
};
|
||||
}
|
||||
|
||||
describe("editor target runtime", () => {
|
||||
it("resolves command aliases and safely launches Windows command scripts", async () => {
|
||||
const records: SpawnRecord[] = [];
|
||||
@@ -39,7 +20,20 @@ describe("editor target runtime", () => {
|
||||
ELECTRON_RUN_AS_NODE: "1",
|
||||
},
|
||||
pathExists: (targetPath) => targetPath === "C:/Program Files/Editors & Tools/bin/code.cmd",
|
||||
spawn: recordSpawns(records),
|
||||
spawn: (command, args, options) => {
|
||||
const record = { command, args, options, unrefed: false };
|
||||
records.push(record);
|
||||
const child = {
|
||||
once(event: "error" | "spawn", handler: (error?: Error) => void) {
|
||||
if (event === "spawn") queueMicrotask(() => handler());
|
||||
return child;
|
||||
},
|
||||
unref() {
|
||||
record.unrefed = true;
|
||||
},
|
||||
};
|
||||
return child;
|
||||
},
|
||||
});
|
||||
|
||||
const command = runtime.resolveCommand(["missing", "code"]);
|
||||
@@ -63,32 +57,4 @@ describe("editor target runtime", () => {
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["system", "/var/lib/flatpak/exports/bin/dev.zed.Zed"],
|
||||
["user", "/home/dev/.local/share/flatpak/exports/bin/dev.zed.Zed"],
|
||||
])("finds and opens Zed from a %s Flatpak install on Linux", async (_scope, flatpakExport) => {
|
||||
const records: SpawnRecord[] = [];
|
||||
const existingPaths = new Set([flatpakExport, "/repo", "/repo/src/app.ts"]);
|
||||
const runtime = createEditorTargetRuntime({
|
||||
platform: "linux",
|
||||
env: { PATH: "/usr/local/bin:/usr/bin:/bin" },
|
||||
homeDirectory: "/home/dev",
|
||||
pathExists: (targetPath) => existingPaths.has(targetPath),
|
||||
spawn: recordSpawns(records),
|
||||
loadIcon: async (fileName) => ({ kind: "image", dataUrl: fileName }),
|
||||
});
|
||||
|
||||
const targets = await listAvailableEditorTargets(runtime, [zedTarget]);
|
||||
expect(targets.map((target) => target.id)).toEqual(["zed"]);
|
||||
|
||||
await openEditorTarget(
|
||||
{ editorId: "zed", workspacePath: "/repo", filePath: "/repo/src/app.ts", line: 3 },
|
||||
runtime,
|
||||
[zedTarget],
|
||||
);
|
||||
expect(records.map(({ command, args }) => ({ command, args }))).toEqual([
|
||||
{ command: flatpakExport, args: ["/repo", "/repo/src/app.ts:3"] },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -56,28 +56,10 @@ function isAbsolutePath(value: string, platform: NodeJS.Platform): boolean {
|
||||
return platform === "win32" ? win32.isAbsolute(value) : posix.isAbsolute(value);
|
||||
}
|
||||
|
||||
// Flatpak exports app launchers here, but does not put these directories on PATH.
|
||||
function flatpakExportDirectories(env: NodeJS.ProcessEnv, homeDirectory: string): string[] {
|
||||
const userDataDirectory = env.XDG_DATA_HOME || `${homeDirectory}/.local/share`;
|
||||
return [`${userDataDirectory}/flatpak/exports/bin`, "/var/lib/flatpak/exports/bin"];
|
||||
}
|
||||
|
||||
function commandSearchDirectories(input: {
|
||||
env: NodeJS.ProcessEnv;
|
||||
platform: NodeJS.Platform;
|
||||
homeDirectory: string;
|
||||
}): string[] {
|
||||
const pathValue = input.env.PATH ?? input.env.Path ?? input.env.path ?? "";
|
||||
const pathDelimiter = input.platform === "win32" ? ";" : ":";
|
||||
const directories = pathValue.split(pathDelimiter).filter(Boolean);
|
||||
if (input.platform !== "linux") return directories;
|
||||
return [...directories, ...flatpakExportDirectories(input.env, input.homeDirectory)];
|
||||
}
|
||||
|
||||
function resolveExecutable(
|
||||
commands: readonly string[],
|
||||
input: {
|
||||
searchDirectories: readonly string[];
|
||||
env: NodeJS.ProcessEnv;
|
||||
pathExists: (path: string) => boolean;
|
||||
platform: NodeJS.Platform;
|
||||
},
|
||||
@@ -87,7 +69,10 @@ function resolveExecutable(
|
||||
return command;
|
||||
}
|
||||
|
||||
for (const directory of input.searchDirectories) {
|
||||
const pathValue = input.env.PATH ?? input.env.Path ?? input.env.path ?? "";
|
||||
const pathDelimiter = input.platform === "win32" ? ";" : ":";
|
||||
for (const directory of pathValue.split(pathDelimiter)) {
|
||||
if (!directory) continue;
|
||||
const candidate = `${directory}/${command}`;
|
||||
if (input.platform !== "win32") {
|
||||
if (input.pathExists(candidate)) return candidate;
|
||||
@@ -155,12 +140,7 @@ export function createEditorTargetRuntime(
|
||||
env,
|
||||
pathExists,
|
||||
isAbsolutePath: (targetPath) => isAbsolutePath(targetPath, platform),
|
||||
resolveCommand: (commands) =>
|
||||
resolveExecutable(commands, {
|
||||
searchDirectories: commandSearchDirectories({ env, platform, homeDirectory }),
|
||||
pathExists,
|
||||
platform,
|
||||
}),
|
||||
resolveCommand: (commands) => resolveExecutable(commands, { env, pathExists, platform }),
|
||||
async spawnDetached({ command, args }) {
|
||||
const commandScript = isWindowsCommandScript(command, platform);
|
||||
const launchCommand = commandScript ? escapeWindowsCmdValue(command) : command;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { EditorTarget, EditorTargetLaunchInput } from "../target.js";
|
||||
|
||||
const COMMANDS = ["zed", "zeditor", "dev.zed.Zed"] as const;
|
||||
const COMMANDS = ["zed", "zeditor"] as const;
|
||||
|
||||
function location(input: EditorTargetLaunchInput): string {
|
||||
if (!input.line) return input.filePath!;
|
||||
|
||||
@@ -49,22 +49,6 @@ describe("agent feature schemas", () => {
|
||||
expect(parsed.value).toBe("flex");
|
||||
});
|
||||
|
||||
it.each(["icon", "label"])(
|
||||
"preserves the %s desktop trigger for any select feature",
|
||||
(desktopTrigger) => {
|
||||
const feature = {
|
||||
type: "select",
|
||||
id: "custom-feature",
|
||||
label: "Custom setting",
|
||||
icon: "gauge",
|
||||
value: "first",
|
||||
options: [{ id: "first", label: "First" }],
|
||||
desktopTrigger,
|
||||
};
|
||||
expect(AgentFeatureSchema.parse(feature)).toEqual(feature);
|
||||
},
|
||||
);
|
||||
|
||||
it("rejects invalid features", () => {
|
||||
const invalidDiscriminator = AgentFeatureSchema.safeParse({
|
||||
type: "slider",
|
||||
|
||||
@@ -145,8 +145,6 @@ export interface AgentFeatureSelect {
|
||||
description?: string;
|
||||
tooltip?: string;
|
||||
icon?: string;
|
||||
/** Desktop toolbar presentation; omitted means labeled. Mobile selectors stay labeled. */
|
||||
desktopTrigger?: "icon" | "label";
|
||||
value: string | null;
|
||||
options: AgentSelectOption[];
|
||||
}
|
||||
|
||||
@@ -301,7 +301,6 @@ export const AgentFeatureSelectSchema = z.object({
|
||||
description: z.string().optional(),
|
||||
tooltip: z.string().optional(),
|
||||
icon: z.string().optional(),
|
||||
desktopTrigger: z.enum(["icon", "label"]).optional(),
|
||||
value: z.string().nullable(),
|
||||
options: z.array(AgentSelectOptionSchema),
|
||||
});
|
||||
|
||||
@@ -50,6 +50,7 @@ import {
|
||||
type AgentTimelineItem,
|
||||
type AgentUsage,
|
||||
type AgentRuntimeInfo,
|
||||
type UsageReference,
|
||||
type ImportedTimelineEntry,
|
||||
type ImportableProviderSession,
|
||||
type ListImportableSessionsOptions,
|
||||
@@ -1167,6 +1168,24 @@ export class AgentManager {
|
||||
return agent ? { ...agent } : null;
|
||||
}
|
||||
|
||||
async resolveUsageReference(
|
||||
id: string,
|
||||
): Promise<{ found: boolean; reference: UsageReference | null }> {
|
||||
const agent = this.getAgent(id);
|
||||
const stored = agent?.session ? null : await this.registry?.get(id);
|
||||
const source = stored ?? agent;
|
||||
if (!source) return { found: false, reference: null };
|
||||
const config = stored ? buildStoredAgentConfig(stored) : agent!.config;
|
||||
const reference =
|
||||
(await this.clients.get(source.provider)?.resolveUsageReference?.({
|
||||
config,
|
||||
runtimeInfo: source.runtimeInfo ?? null,
|
||||
persistence: source.persistence ?? null,
|
||||
session: agent?.session ?? null,
|
||||
})) ?? null;
|
||||
return { found: true, reference };
|
||||
}
|
||||
|
||||
async waitForAgentClose(agentId: string): Promise<void> {
|
||||
// Loading during reload must wait for the replacement, not resume another writer.
|
||||
await this.lifecycleMutationTails.get(agentId);
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
import type {
|
||||
AgentFeature,
|
||||
AgentFeatureSelect,
|
||||
AgentFeatureToggle,
|
||||
AgentProviderNotice,
|
||||
AgentTaskItem,
|
||||
JsonValue,
|
||||
@@ -11,13 +8,7 @@ import type {
|
||||
import type { AgentAttachment } from "@getpaseo/protocol/messages";
|
||||
import type { PaseoToolCatalog } from "./tools/types.js";
|
||||
|
||||
export type {
|
||||
AgentFeature,
|
||||
AgentFeatureSelect,
|
||||
AgentFeatureToggle,
|
||||
AgentProviderNotice,
|
||||
AgentTaskItem,
|
||||
};
|
||||
export type { AgentProviderNotice, AgentTaskItem };
|
||||
|
||||
export type AgentProvider = string;
|
||||
|
||||
@@ -165,6 +156,29 @@ export interface AgentCreateConfigUnattendedInput {
|
||||
availableModes: AgentMode[];
|
||||
}
|
||||
|
||||
export interface AgentFeatureToggle {
|
||||
type: "toggle";
|
||||
id: string;
|
||||
label: string;
|
||||
description?: string;
|
||||
tooltip?: string;
|
||||
icon?: string;
|
||||
value: boolean;
|
||||
}
|
||||
|
||||
export interface AgentFeatureSelect {
|
||||
type: "select";
|
||||
id: string;
|
||||
label: string;
|
||||
description?: string;
|
||||
tooltip?: string;
|
||||
icon?: string;
|
||||
value: string | null;
|
||||
options: AgentSelectOption[];
|
||||
}
|
||||
|
||||
export type AgentFeature = AgentFeatureToggle | AgentFeatureSelect;
|
||||
|
||||
export interface AgentCapabilityFlags {
|
||||
[capability: string]: boolean | undefined;
|
||||
supportsStreaming: boolean;
|
||||
@@ -659,8 +673,6 @@ export interface AgentSession {
|
||||
/** New provider-owned rows to commit on registration. streamHistory must also
|
||||
* replay them at their original timestamps; restored sessions omit old rows. */
|
||||
readonly initialTimeline?: ImportedTimelineEntry[];
|
||||
/** Resolved at fetch time because model and credentials may change during a session. */
|
||||
getUsageReference?(): Promise<UsageReference | null>;
|
||||
run(prompt: AgentPromptInput, options?: AgentRunOptions): Promise<AgentRunResult>;
|
||||
startTurn(prompt: AgentPromptInput, options?: AgentRunOptions): Promise<{ turnId: string }>;
|
||||
steerActiveTurn?(prompt: AgentPromptInput, options: SteerActiveTurnOptions): Promise<SteerResult>;
|
||||
@@ -736,6 +748,13 @@ export interface ResolveAgentDefaultModeInput {
|
||||
export interface AgentClient {
|
||||
readonly provider: AgentProvider;
|
||||
readonly capabilities: AgentCapabilityFlags;
|
||||
/** Account used by the agent. Resolving this must not start or load a session. */
|
||||
resolveUsageReference?(input: {
|
||||
config: AgentSessionConfig;
|
||||
runtimeInfo: AgentRuntimeInfo | null;
|
||||
persistence: AgentPersistenceHandle | null;
|
||||
session: AgentSession | null;
|
||||
}): Promise<UsageReference | null>;
|
||||
createSession(
|
||||
config: AgentSessionConfig,
|
||||
launchContext?: AgentLaunchContext,
|
||||
|
||||
@@ -406,7 +406,12 @@ describe("PluginAgentClientRegistry", () => {
|
||||
cwd: "/workspace",
|
||||
});
|
||||
try {
|
||||
expect(await session.getUsageReference?.()).toBeNull();
|
||||
expect(
|
||||
await client.resolveUsageReference?.({
|
||||
config: { provider: harness.registration.id, cwd: "/workspace" },
|
||||
session,
|
||||
}),
|
||||
).toBeNull();
|
||||
expect(harness.inputs.some((input) => input.type === "session.usage_reference")).toBe(false);
|
||||
} finally {
|
||||
await session.close();
|
||||
|
||||
@@ -897,6 +897,15 @@ class PluginAgentClient implements AgentClient {
|
||||
return agentCapabilities(this.runtime.negotiatedCapabilities);
|
||||
}
|
||||
|
||||
async resolveUsageReference({
|
||||
session,
|
||||
}: {
|
||||
config: AgentSessionConfig;
|
||||
session: AgentSession | null;
|
||||
}) {
|
||||
return session instanceof PluginAgentSession ? session.getPluginUsageReference() : null;
|
||||
}
|
||||
|
||||
async createSession(
|
||||
config: AgentSessionConfig,
|
||||
launchContext?: AgentLaunchContext,
|
||||
@@ -1096,7 +1105,7 @@ class PluginAgentSession implements AgentSession {
|
||||
return agentCapabilities(this.bridge.negotiatedCapabilities);
|
||||
}
|
||||
|
||||
getUsageReference(): Promise<UsageReference | null> {
|
||||
getPluginUsageReference(): Promise<UsageReference | null> {
|
||||
return this.bridge.getUsageReference();
|
||||
}
|
||||
|
||||
|
||||
@@ -458,7 +458,6 @@ export function wrapSessionProvider(provider: AgentProvider, inner: AgentSession
|
||||
}
|
||||
},
|
||||
getRuntimeInfo: async () => mapRuntimeInfo(provider, await inner.getRuntimeInfo()),
|
||||
getUsageReference: inner.getUsageReference?.bind(inner),
|
||||
getAvailableModes: () => inner.getAvailableModes(),
|
||||
getCurrentMode: () => inner.getCurrentMode(),
|
||||
setMode: (modeId) => inner.setMode(modeId),
|
||||
@@ -490,13 +489,28 @@ function wrapClientProvider(
|
||||
const listFeatures = inner.listFeatures?.bind(inner);
|
||||
const archiveNativeSession = inner.archiveNativeSession?.bind(inner);
|
||||
const unarchiveNativeSession = inner.unarchiveNativeSession?.bind(inner);
|
||||
// An alias's live session can carry launch env that is fresher than stored config.
|
||||
const sessions = new WeakMap<AgentSession, AgentSession>();
|
||||
const wrapSession = (session: AgentSession) => {
|
||||
const wrapped = wrapSessionProvider(provider, session);
|
||||
sessions.set(wrapped, session);
|
||||
return wrapped;
|
||||
};
|
||||
|
||||
return {
|
||||
provider,
|
||||
capabilities: inner.capabilities,
|
||||
resolveUsageReference: inner.resolveUsageReference
|
||||
? ({ config, runtimeInfo, persistence, session }) =>
|
||||
inner.resolveUsageReference!({
|
||||
config: { ...config, provider: inner.provider },
|
||||
runtimeInfo,
|
||||
persistence,
|
||||
session: session ? (sessions.get(session) ?? null) : null,
|
||||
})
|
||||
: undefined,
|
||||
createSession: async (config, launchContext) =>
|
||||
wrapSessionProvider(
|
||||
provider,
|
||||
wrapSession(
|
||||
await inner.createSession(
|
||||
{
|
||||
...config,
|
||||
@@ -506,8 +520,7 @@ function wrapClientProvider(
|
||||
),
|
||||
),
|
||||
resumeSession: async (handle, overrides, launchContext, options) =>
|
||||
wrapSessionProvider(
|
||||
provider,
|
||||
wrapSession(
|
||||
await inner.resumeSession(
|
||||
{
|
||||
...handle,
|
||||
@@ -569,7 +582,7 @@ function wrapClientProvider(
|
||||
}
|
||||
return {
|
||||
...imported,
|
||||
session: wrapSessionProvider(provider, imported.session),
|
||||
session: wrapSession(imported.session),
|
||||
config: {
|
||||
...imported.config,
|
||||
provider,
|
||||
|
||||
@@ -224,8 +224,17 @@ function createSessionWithConfig(
|
||||
|
||||
test("ACP usage reference uses the provider ID", async () => {
|
||||
for (const provider of ["copilot", "cursor", "kimi", "custom-source"]) {
|
||||
const session = createSessionWithConfig({ provider });
|
||||
expect(await session.getUsageReference()).toEqual({ source: provider, input: {} });
|
||||
const client = new ACPAgentClient({
|
||||
provider,
|
||||
logger: createTestLogger(),
|
||||
defaultCommand: ["unused"],
|
||||
});
|
||||
expect(
|
||||
await client.resolveUsageReference({
|
||||
config: { provider, cwd: "/tmp/paseo-acp-test" },
|
||||
session: null,
|
||||
}),
|
||||
).toEqual({ source: provider, input: {} });
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -882,6 +882,9 @@ function isACPCreateConfigUnattended(input: AgentCreateConfigUnattendedInput): b
|
||||
export class ACPAgentClient implements AgentClient {
|
||||
readonly provider: string;
|
||||
readonly capabilities: AgentCapabilityFlags;
|
||||
async resolveUsageReference() {
|
||||
return { source: this.provider, input: {} };
|
||||
}
|
||||
readonly resolveCreateConfig = resolveACPCreateConfig;
|
||||
readonly isCreateConfigUnattended = isACPCreateConfigUnattended;
|
||||
|
||||
@@ -1633,10 +1636,6 @@ export class ACPAgentSession implements AgentSession, ACPClient {
|
||||
readonly provider: string;
|
||||
readonly capabilities: AgentCapabilityFlags;
|
||||
|
||||
async getUsageReference() {
|
||||
return { source: this.provider, input: {} };
|
||||
}
|
||||
|
||||
private readonly logger: Logger;
|
||||
private readonly runtimeSettings?: ProviderRuntimeSettings;
|
||||
private readonly defaultCommand: [string, ...string[]];
|
||||
|
||||
@@ -531,16 +531,16 @@ describe("ClaudeAgentClient binary resolution", () => {
|
||||
const logger = createTestLogger();
|
||||
|
||||
test("Claude usage reference follows CLAUDE_CONFIG_DIR and excludes API overrides", async () => {
|
||||
const client = new ClaudeAgentClient({ logger, resolveBinary: async () => "/test/claude/bin" });
|
||||
const session = await client.createSession(
|
||||
{ provider: "claude", cwd: process.cwd() },
|
||||
{ env: { CLAUDE_CONFIG_DIR: "/accounts/second" } },
|
||||
);
|
||||
expect(await session.getUsageReference?.()).toEqual({
|
||||
const config = { provider: "claude", cwd: process.cwd() };
|
||||
const client = new ClaudeAgentClient({
|
||||
logger,
|
||||
runtimeSettings: { env: { CLAUDE_CONFIG_DIR: "/accounts/second" } },
|
||||
resolveBinary: async () => "/test/claude/bin",
|
||||
});
|
||||
expect(await client.resolveUsageReference?.({ config, session: null })).toEqual({
|
||||
source: "claude",
|
||||
input: { configDir: "/accounts/second" },
|
||||
});
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test.each(["ANTHROPIC_BASE_URL", "ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN"])(
|
||||
@@ -548,14 +548,15 @@ describe("ClaudeAgentClient binary resolution", () => {
|
||||
async (name) => {
|
||||
const client = new ClaudeAgentClient({
|
||||
logger,
|
||||
runtimeSettings: { env: { [name]: "override" } },
|
||||
resolveBinary: async () => "/test/claude/bin",
|
||||
});
|
||||
const session = await client.createSession(
|
||||
{ provider: "claude", cwd: process.cwd() },
|
||||
{ env: { [name]: "override" } },
|
||||
);
|
||||
expect(await session.getUsageReference?.()).toBeNull();
|
||||
await session.close();
|
||||
expect(
|
||||
await client.resolveUsageReference?.({
|
||||
config: { provider: "claude", cwd: process.cwd() },
|
||||
session: null,
|
||||
}),
|
||||
).toBeNull();
|
||||
},
|
||||
);
|
||||
|
||||
@@ -569,15 +570,16 @@ describe("ClaudeAgentClient binary resolution", () => {
|
||||
},
|
||||
},
|
||||
});
|
||||
const session = await registry["work-claude"].createClient(logger).createSession({
|
||||
provider: "work-claude",
|
||||
cwd: process.cwd(),
|
||||
});
|
||||
expect(await session.getUsageReference?.()).toEqual({
|
||||
const client = registry["work-claude"].createClient(logger);
|
||||
expect(
|
||||
await client.resolveUsageReference?.({
|
||||
config: { provider: "work-claude", cwd: process.cwd() },
|
||||
session: null,
|
||||
}),
|
||||
).toEqual({
|
||||
source: "claude",
|
||||
input: { configDir: "/accounts/work" },
|
||||
});
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test("resolves the installed Claude Code version", async () => {
|
||||
|
||||
@@ -1519,6 +1519,15 @@ export class ClaudeAgentClient implements AgentClient {
|
||||
this.rewindSdk = options.rewindSdk ?? realClaudeRewindSdk;
|
||||
}
|
||||
|
||||
async resolveUsageReference() {
|
||||
const env = createProviderEnv({ baseEnv: process.env, runtimeSettings: this.runtimeSettings });
|
||||
if (env.ANTHROPIC_BASE_URL || env.ANTHROPIC_API_KEY || env.ANTHROPIC_AUTH_TOKEN) return null;
|
||||
return {
|
||||
source: "claude",
|
||||
input: { configDir: env.CLAUDE_CONFIG_DIR || path.join(env.HOME || homedir(), ".claude") },
|
||||
};
|
||||
}
|
||||
|
||||
resolveConfiguredModel(model: AgentModelDefinition): AgentModelDefinition {
|
||||
return resolveConfiguredClaudeModel(model);
|
||||
}
|
||||
@@ -2042,15 +2051,6 @@ class ClaudeAgentSession implements AgentSession {
|
||||
readonly provider = "claude" as const;
|
||||
readonly capabilities = CLAUDE_CAPABILITIES;
|
||||
|
||||
async getUsageReference() {
|
||||
const env = this.buildSdkEnv();
|
||||
if (env.ANTHROPIC_BASE_URL || env.ANTHROPIC_API_KEY || env.ANTHROPIC_AUTH_TOKEN) return null;
|
||||
return {
|
||||
source: "claude",
|
||||
input: { configDir: env.CLAUDE_CONFIG_DIR || path.join(env.HOME || homedir(), ".claude") },
|
||||
};
|
||||
}
|
||||
|
||||
private readonly config: ClaudeAgentConfig;
|
||||
private readonly launchEnv?: Record<string, string>;
|
||||
private readonly agentId?: string;
|
||||
|
||||
+55
-228
@@ -19,41 +19,6 @@ interface CollaborationModeRecord {
|
||||
developer_instructions?: string | null;
|
||||
}
|
||||
|
||||
const TEST_SPEED_MODELS = [
|
||||
"gpt-6-astra",
|
||||
"gpt-6.1-sol",
|
||||
"gpt-6-sol",
|
||||
"gpt-6-luna",
|
||||
"gpt-5.6",
|
||||
"gpt-5.6-sol",
|
||||
"gpt-5.6-terra",
|
||||
"gpt-5.6-luna",
|
||||
"gpt-5.5",
|
||||
"gpt-5.4",
|
||||
].map((id) => ({
|
||||
id,
|
||||
isDefault: id === "gpt-5.4",
|
||||
defaultReasoningEffort: "medium",
|
||||
serviceTiers: [{ id: "priority", name: "Fast", description: "Faster processing" }],
|
||||
}));
|
||||
|
||||
function speedFeature(value: string) {
|
||||
return {
|
||||
type: "select",
|
||||
id: "service_tier",
|
||||
label: "Speed",
|
||||
description: "Choose processing speed. Faster tiers increase usage.",
|
||||
tooltip: "Select speed",
|
||||
icon: "zap",
|
||||
desktopTrigger: "icon",
|
||||
value,
|
||||
options: [
|
||||
{ id: "default", label: "Normal", isDefault: true },
|
||||
{ id: "priority", label: "Fast" },
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
const TEST_COLLABORATION_MODES: CollaborationModeRecord[] = [
|
||||
{
|
||||
name: "Code",
|
||||
@@ -100,7 +65,7 @@ function createConfig(overrides: Partial<AgentSessionConfig> = {}): AgentSession
|
||||
|
||||
function createSessionHarness(
|
||||
configOverrides: Partial<AgentSessionConfig> = {},
|
||||
options: { logger?: pino.Logger; models?: unknown[] } = {},
|
||||
options: { logger?: pino.Logger } = {},
|
||||
): {
|
||||
session: CodexFeaturesTestSession;
|
||||
appServer: FakeCodexAppServer;
|
||||
@@ -108,7 +73,6 @@ function createSessionHarness(
|
||||
const config = createConfig(configOverrides);
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"collaborationMode/list": () => ({ data: TEST_COLLABORATION_MODES }),
|
||||
"model/list": () => ({ data: options.models ?? TEST_SPEED_MODELS }),
|
||||
});
|
||||
const session = new CodexAppServerAgentSession(
|
||||
{ ...config, provider: CODEX_PROVIDER },
|
||||
@@ -121,7 +85,7 @@ function createSessionHarness(
|
||||
|
||||
async function createConnectedSession(
|
||||
configOverrides: Partial<AgentSessionConfig> = {},
|
||||
options: { logger?: pino.Logger; models?: unknown[] } = {},
|
||||
options: { logger?: pino.Logger } = {},
|
||||
): Promise<{
|
||||
session: CodexFeaturesTestSession;
|
||||
appServer: FakeCodexAppServer;
|
||||
@@ -133,169 +97,8 @@ async function createConnectedSession(
|
||||
}
|
||||
|
||||
describe("Codex app-server provider features", () => {
|
||||
test("GPT-6.1 Sol offers catalog speed tiers and sends Ultrafast", async () => {
|
||||
const { session, appServer } = await createConnectedSession(
|
||||
{ model: "gpt-6.1-sol" },
|
||||
{
|
||||
models: [
|
||||
{
|
||||
id: "gpt-6.1-sol",
|
||||
serviceTiers: [
|
||||
{ id: "priority", name: "Fast", description: "Faster processing" },
|
||||
{ id: "ultrafast", name: "Ultrafast", description: "Lowest latency" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
);
|
||||
try {
|
||||
expect(session.features).toContainEqual(
|
||||
expect.objectContaining({
|
||||
id: "service_tier",
|
||||
type: "select",
|
||||
value: "default",
|
||||
options: [
|
||||
{ id: "default", label: "Normal", isDefault: true },
|
||||
{ id: "priority", label: "Fast" },
|
||||
{ id: "ultrafast", label: "Ultrafast" },
|
||||
],
|
||||
}),
|
||||
);
|
||||
await session.setFeature?.("service_tier", "ultrafast");
|
||||
await session.startTurn("hello");
|
||||
await expect(appServer.waitForTurnStart()).resolves.toMatchObject({
|
||||
serviceTier: "ultrafast",
|
||||
});
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("new models and service tiers work without a Paseo catalog update", async () => {
|
||||
const { session, appServer } = await createConnectedSession(
|
||||
{ model: "future-codex-model" },
|
||||
{
|
||||
models: [
|
||||
{
|
||||
id: "future-codex-model",
|
||||
serviceTiers: [
|
||||
{ id: "future-tier", name: "Future speed", description: "A newly advertised tier" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
);
|
||||
try {
|
||||
expect(session.features).toContainEqual(
|
||||
expect.objectContaining({
|
||||
id: "service_tier",
|
||||
options: [
|
||||
{ id: "default", label: "Normal", isDefault: true },
|
||||
{ id: "future-tier", label: "Future speed" },
|
||||
],
|
||||
}),
|
||||
);
|
||||
await session.setFeature?.("service_tier", "future-tier");
|
||||
await session.startTurn("hello");
|
||||
await expect(appServer.waitForTurnStart()).resolves.toMatchObject({
|
||||
model: "future-codex-model",
|
||||
serviceTier: "future-tier",
|
||||
});
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test.each(["priority", "ultrafast"])(
|
||||
"restores %s and Normal explicitly overrides an existing thread tier",
|
||||
async (tier) => {
|
||||
const { session, appServer } = await createConnectedSession(
|
||||
{ model: "future-model", featureValues: { service_tier: tier } },
|
||||
{
|
||||
models: [
|
||||
{
|
||||
id: "future-model",
|
||||
serviceTiers: [
|
||||
{ id: "priority", name: "Fast", description: "Fast processing" },
|
||||
{ id: "ultrafast", name: "Ultrafast", description: "Ultra processing" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
);
|
||||
try {
|
||||
expect(session.features).toContainEqual(
|
||||
expect.objectContaining({ id: "service_tier", value: tier }),
|
||||
);
|
||||
await session.getRuntimeInfo();
|
||||
await session.setFeature?.("service_tier", "default");
|
||||
await session.startTurn("hello");
|
||||
await expect(appServer.waitForTurnStart()).resolves.toMatchObject({
|
||||
serviceTier: "default",
|
||||
});
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test("rejects unadvertised tiers and non-string values", async () => {
|
||||
const { session } = await createConnectedSession();
|
||||
try {
|
||||
for (const value of ["ultrafast", "bogus", true, null]) {
|
||||
await expect(session.setFeature?.("service_tier", value)).rejects.toThrow(
|
||||
"is not available",
|
||||
);
|
||||
}
|
||||
expect(session.features).toContainEqual(
|
||||
expect.objectContaining({ id: "service_tier", value: "default" }),
|
||||
);
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("switching to a model without the selected tier resets speed", async () => {
|
||||
const { session, appServer } = await createConnectedSession(
|
||||
{ model: "ultra-model", featureValues: { service_tier: "ultrafast" } },
|
||||
{
|
||||
models: [
|
||||
{
|
||||
id: "ultra-model",
|
||||
serviceTiers: [{ id: "ultrafast", name: "Ultrafast", description: "Ultra processing" }],
|
||||
},
|
||||
...TEST_SPEED_MODELS,
|
||||
],
|
||||
},
|
||||
);
|
||||
try {
|
||||
await session.setModel("gpt-6.1-sol");
|
||||
expect(session.features).toContainEqual(
|
||||
expect.objectContaining({ id: "service_tier", value: "default" }),
|
||||
);
|
||||
await session.startTurn("hello");
|
||||
await expect(appServer.waitForTurnStart()).resolves.toMatchObject({ serviceTier: "default" });
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("maps legacy Fast commands to the catalog's request id", async () => {
|
||||
const { session, appServer } = await createConnectedSession();
|
||||
try {
|
||||
await session.setFeature?.("fast_mode", true);
|
||||
await session.startTurn("hello");
|
||||
await expect(appServer.waitForTurnStart()).resolves.toMatchObject({
|
||||
serviceTier: "priority",
|
||||
});
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test.each([
|
||||
"gpt-6-astra",
|
||||
"gpt-6.1-sol",
|
||||
"gpt-6-sol",
|
||||
"gpt-6-luna",
|
||||
"gpt-5.6",
|
||||
@@ -309,15 +112,15 @@ describe("Codex app-server provider features", () => {
|
||||
try {
|
||||
expect(session.features).toContainEqual(
|
||||
expect.objectContaining({
|
||||
id: "service_tier",
|
||||
value: "default",
|
||||
id: "fast_mode",
|
||||
value: false,
|
||||
}),
|
||||
);
|
||||
await session.setFeature?.("service_tier", "priority");
|
||||
await session.setFeature?.("fast_mode", true);
|
||||
await session.startTurn("hello");
|
||||
await expect(appServer.waitForTurnStart()).resolves.toMatchObject({
|
||||
model,
|
||||
serviceTier: "priority",
|
||||
serviceTier: "fast",
|
||||
});
|
||||
} finally {
|
||||
await session.close();
|
||||
@@ -346,8 +149,8 @@ describe("Codex app-server provider features", () => {
|
||||
`Codex fast mode is not available for model '${model}'`,
|
||||
);
|
||||
await session.startTurn("hello");
|
||||
await expect(appServer.waitForTurnStart()).resolves.toMatchObject({
|
||||
serviceTier: "default",
|
||||
await expect(appServer.waitForTurnStart()).resolves.not.toMatchObject({
|
||||
serviceTier: expect.anything(),
|
||||
});
|
||||
} finally {
|
||||
await session.close();
|
||||
@@ -362,8 +165,8 @@ describe("Codex app-server provider features", () => {
|
||||
try {
|
||||
expect(session.features).toContainEqual(
|
||||
expect.objectContaining({
|
||||
id: "service_tier",
|
||||
value: "priority",
|
||||
id: "fast_mode",
|
||||
value: true,
|
||||
}),
|
||||
);
|
||||
await session.setModel("gpt-5.6-sol");
|
||||
@@ -371,18 +174,26 @@ describe("Codex app-server provider features", () => {
|
||||
await session.startTurn("hello");
|
||||
await expect(appServer.waitForTurnStart()).resolves.toMatchObject({
|
||||
model: "gpt-6-astra",
|
||||
serviceTier: "priority",
|
||||
serviceTier: "fast",
|
||||
});
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("features returns speed selector and plan toggle when supported", async () => {
|
||||
test("features returns fast and plan toggles when supported", async () => {
|
||||
const { session } = await createConnectedSession();
|
||||
|
||||
expect(session.features).toEqual([
|
||||
speedFeature("default"),
|
||||
{
|
||||
type: "toggle",
|
||||
id: "fast_mode",
|
||||
label: "Fast",
|
||||
description: "Priority inference at increased usage",
|
||||
tooltip: "Toggle fast mode",
|
||||
icon: "zap",
|
||||
value: false,
|
||||
},
|
||||
{
|
||||
type: "toggle",
|
||||
id: "plan_mode",
|
||||
@@ -394,11 +205,19 @@ describe("Codex app-server provider features", () => {
|
||||
},
|
||||
]);
|
||||
|
||||
await session.setFeature?.("service_tier", "priority");
|
||||
await session.setFeature?.("fast_mode", true);
|
||||
await session.setFeature?.("plan_mode", true);
|
||||
|
||||
expect(session.features).toEqual([
|
||||
speedFeature("priority"),
|
||||
{
|
||||
type: "toggle",
|
||||
id: "fast_mode",
|
||||
label: "Fast",
|
||||
description: "Priority inference at increased usage",
|
||||
tooltip: "Toggle fast mode",
|
||||
icon: "zap",
|
||||
value: true,
|
||||
},
|
||||
{
|
||||
type: "toggle",
|
||||
id: "plan_mode",
|
||||
@@ -446,23 +265,23 @@ describe("Codex app-server provider features", () => {
|
||||
]);
|
||||
|
||||
await session.startTurn("hello");
|
||||
await expect(appServer.waitForTurnStart()).resolves.toMatchObject({
|
||||
serviceTier: "default",
|
||||
await expect(appServer.waitForTurnStart()).resolves.not.toMatchObject({
|
||||
serviceTier: expect.anything(),
|
||||
});
|
||||
});
|
||||
|
||||
test("selecting Fast sends the catalog service tier", async () => {
|
||||
test("setFeature('fast_mode', true) sets serviceTier to fast", async () => {
|
||||
const { session, appServer } = await createConnectedSession();
|
||||
|
||||
await session.setFeature?.("service_tier", "priority");
|
||||
await session.setFeature?.("fast_mode", true);
|
||||
await session.startTurn("hello");
|
||||
|
||||
await expect(appServer.waitForTurnStart()).resolves.toMatchObject({
|
||||
serviceTier: "priority",
|
||||
serviceTier: "fast",
|
||||
});
|
||||
});
|
||||
|
||||
test("legacy Fast off explicitly selects Normal", async () => {
|
||||
test("setFeature('fast_mode', false) clears serviceTier to null", async () => {
|
||||
const { session, appServer } = await createConnectedSession({
|
||||
featureValues: { fast_mode: true },
|
||||
});
|
||||
@@ -470,8 +289,8 @@ describe("Codex app-server provider features", () => {
|
||||
await session.setFeature?.("fast_mode", false);
|
||||
await session.startTurn("hello");
|
||||
|
||||
await expect(appServer.waitForTurnStart()).resolves.toMatchObject({
|
||||
serviceTier: "default",
|
||||
await expect(appServer.waitForTurnStart()).resolves.not.toMatchObject({
|
||||
serviceTier: expect.anything(),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -511,7 +330,15 @@ describe("Codex app-server provider features", () => {
|
||||
});
|
||||
|
||||
expect(session.features).toEqual([
|
||||
speedFeature("priority"),
|
||||
{
|
||||
type: "toggle",
|
||||
id: "fast_mode",
|
||||
label: "Fast",
|
||||
description: "Priority inference at increased usage",
|
||||
tooltip: "Toggle fast mode",
|
||||
icon: "zap",
|
||||
value: true,
|
||||
},
|
||||
{
|
||||
type: "toggle",
|
||||
id: "plan_mode",
|
||||
@@ -525,7 +352,7 @@ describe("Codex app-server provider features", () => {
|
||||
|
||||
await session.startTurn("hello");
|
||||
await expect(appServer.waitForTurnStart()).resolves.toMatchObject({
|
||||
serviceTier: "priority",
|
||||
serviceTier: "fast",
|
||||
collaborationMode: expect.objectContaining({
|
||||
mode: "plan",
|
||||
}),
|
||||
@@ -535,11 +362,11 @@ describe("Codex app-server provider features", () => {
|
||||
test("startTurn includes serviceTier when fast mode is enabled", async () => {
|
||||
const { session, appServer } = await createConnectedSession();
|
||||
|
||||
await session.setFeature?.("service_tier", "priority");
|
||||
await session.setFeature?.("fast_mode", true);
|
||||
await session.startTurn("hello");
|
||||
|
||||
await expect(appServer.waitForTurnStart()).resolves.toMatchObject({
|
||||
serviceTier: "priority",
|
||||
serviceTier: "fast",
|
||||
});
|
||||
});
|
||||
|
||||
@@ -561,7 +388,7 @@ describe("Codex app-server provider features", () => {
|
||||
msg: "Starting Codex app-server turn",
|
||||
model: "gpt-5.4",
|
||||
modeId: "auto",
|
||||
serviceTier: "priority",
|
||||
serviceTier: "fast",
|
||||
cwd: "/tmp/codex-fast-mode-test",
|
||||
});
|
||||
expect(JSON.stringify(entry)).not.toContain(prompt);
|
||||
@@ -570,7 +397,7 @@ describe("Codex app-server provider features", () => {
|
||||
test("setModel clears fast mode when switching to an unsupported model", async () => {
|
||||
const { session, appServer } = await createConnectedSession();
|
||||
|
||||
await session.setFeature?.("service_tier", "priority");
|
||||
await session.setFeature?.("fast_mode", true);
|
||||
await session.setModel("gpt-3.5-turbo");
|
||||
|
||||
expect(session.features).toEqual([
|
||||
@@ -586,8 +413,8 @@ describe("Codex app-server provider features", () => {
|
||||
]);
|
||||
await session.startTurn("hello");
|
||||
|
||||
await expect(appServer.waitForTurnStart()).resolves.toMatchObject({
|
||||
serviceTier: "default",
|
||||
await expect(appServer.waitForTurnStart()).resolves.not.toMatchObject({
|
||||
serviceTier: expect.anything(),
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -172,41 +172,18 @@ function createSession(
|
||||
}
|
||||
|
||||
test("Codex usage reference follows CODEX_HOME and excludes custom base URLs", async () => {
|
||||
const session = new CodexAppServerAgentSession(
|
||||
createConfig(),
|
||||
null,
|
||||
createTestLogger(),
|
||||
() => {
|
||||
throw new Error("unused");
|
||||
},
|
||||
{},
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
undefined,
|
||||
"interactive",
|
||||
{ CODEX_HOME: "/accounts/second" },
|
||||
);
|
||||
expect(await session.getUsageReference()).toEqual({
|
||||
const config = createConfig();
|
||||
const client = new CodexAppServerAgentClient(createTestLogger(), {
|
||||
env: { CODEX_HOME: "/accounts/second" },
|
||||
});
|
||||
expect(await client.resolveUsageReference({ config, session: null })).toEqual({
|
||||
source: "codex",
|
||||
input: { codexHome: "/accounts/second" },
|
||||
});
|
||||
const custom = new CodexAppServerAgentSession(
|
||||
createConfig(),
|
||||
null,
|
||||
createTestLogger(),
|
||||
() => {
|
||||
throw new Error("unused");
|
||||
},
|
||||
{},
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
undefined,
|
||||
"interactive",
|
||||
{ CODEX_HOME: "/accounts/second", OPENAI_BASE_URL: "https://example.test" },
|
||||
);
|
||||
expect(await custom.getUsageReference()).toBeNull();
|
||||
const custom = new CodexAppServerAgentClient(createTestLogger(), {
|
||||
env: { CODEX_HOME: "/accounts/second", OPENAI_BASE_URL: "https://example.test" },
|
||||
});
|
||||
expect(await custom.resolveUsageReference({ config, session: null })).toBeNull();
|
||||
});
|
||||
|
||||
function createProviderWithFakeAppServer(
|
||||
@@ -660,7 +637,6 @@ async function withCustomCodexProviderHome<T>(
|
||||
session: AgentSession;
|
||||
readCaptured: () => CapturedFakeCodexRecord[];
|
||||
}) => Promise<T>,
|
||||
providerPrompts: Record<string, string> = {},
|
||||
): Promise<T> {
|
||||
const tempDir = await mkdtemp(path.join(tmpdir(), "codex-provider-home-"));
|
||||
const daemonCodexHome = path.join(tempDir, "daemon-codex-home");
|
||||
@@ -677,9 +653,6 @@ async function withCustomCodexProviderHome<T>(
|
||||
path.join(providerCodexHome, "prompts", "probe-profile.md"),
|
||||
"---\ndescription: Provider home prompt\n---\nfrom the provider home\n",
|
||||
);
|
||||
for (const [name, content] of Object.entries(providerPrompts)) {
|
||||
writeFileSync(path.join(providerCodexHome, "prompts", `${name}.md`), content);
|
||||
}
|
||||
writeFileSync(
|
||||
fakeAppServerPath,
|
||||
`
|
||||
@@ -757,21 +730,11 @@ async function listPromptCommandsFromCustomCodexHome(): Promise<string[]> {
|
||||
});
|
||||
}
|
||||
|
||||
async function runPromptFromCustomCodexHome(
|
||||
prompt: string,
|
||||
providerPrompts: Record<string, string> = {},
|
||||
): Promise<CapturedFakeCodexRecord[]> {
|
||||
async function runPromptFromCustomCodexHome(prompt: string): Promise<CapturedFakeCodexRecord[]> {
|
||||
return withCustomCodexProviderHome(async ({ session, readCaptured }) => {
|
||||
await session.startTurn(prompt);
|
||||
return readCaptured();
|
||||
}, providerPrompts);
|
||||
}
|
||||
|
||||
async function expandCustomPrompt(template: string, args: string): Promise<string> {
|
||||
const records = await runPromptFromCustomCodexHome(`/prompts:template ${args}`, { template });
|
||||
const turnStart = records.find((record) => record.method === "turn/start");
|
||||
const params = turnStart?.params as { input: Array<{ text: string }> };
|
||||
return params.input[0].text;
|
||||
});
|
||||
}
|
||||
|
||||
function capturedThreadStartConfig(records: CapturedFakeCodexRecord[]): unknown {
|
||||
@@ -804,7 +767,6 @@ let buffer = "";
|
||||
function resultFor(method, params) {
|
||||
if (method === "initialize") return {};
|
||||
if (method === "collaborationMode/list") return { data: [] };
|
||||
if (method === "model/list") return { data: [] };
|
||||
if (method === "skills/list") {
|
||||
const cwds = params && params.cwds;
|
||||
const projectCwd = ${JSON.stringify(projectCwd)};
|
||||
@@ -1171,36 +1133,6 @@ describe("Codex app-server provider", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps the default effort when a session without one is resumed after a restart", async () => {
|
||||
const beforeRestart = createFakeCodexAppServer();
|
||||
const firstSession = await createProviderWithFakeAppServer(beforeRestart).createSession(
|
||||
createConfig({ thinkingOptionId: undefined }),
|
||||
);
|
||||
await firstSession.startTurn("first turn");
|
||||
await expect(beforeRestart.waitForTurnStart()).resolves.toMatchObject({ effort: "medium" });
|
||||
const handle = firstSession.describePersistence()!;
|
||||
await firstSession.close();
|
||||
|
||||
const afterRestart = createFakeCodexAppServer();
|
||||
// The daemon resumes with the stored agent config, which never recorded an effort.
|
||||
const resumed = await createProviderWithFakeAppServer(afterRestart).resumeSession(handle, {
|
||||
model: "gpt-5.4",
|
||||
thinkingOptionId: undefined,
|
||||
});
|
||||
|
||||
try {
|
||||
await expect(resumed.getRuntimeInfo()).resolves.toMatchObject({
|
||||
thinkingOptionId: "medium",
|
||||
});
|
||||
await resumed.startTurn("turn after restart");
|
||||
await expect(afterRestart.waitForTurnStart()).resolves.toMatchObject({ effort: "medium" });
|
||||
beforeRestart.assertNoErrors();
|
||||
afterRestart.assertNoErrors();
|
||||
} finally {
|
||||
await resumed.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("preapproves only granted tools on the injected Codex MCP server", async () => {
|
||||
const session = createSession({
|
||||
modeId: undefined,
|
||||
@@ -1965,66 +1897,6 @@ describe("Codex app-server provider", () => {
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test("rewinds a legacy conversation with a bounded fork on Codex without thread/rollback", async () => {
|
||||
const appServer = createFakeCodexAppServer({
|
||||
initialize: () => ({ userAgent: "paseo/0.159.0 (Ubuntu 26.4.0; x86_64) (paseo; 0)" }),
|
||||
"thread/read": () => ({
|
||||
thread: { id: "thread-1", historyMode: "legacy", turns: [] },
|
||||
}),
|
||||
"thread/rollback": () => ({
|
||||
__jsonRpcError: {
|
||||
code: -32600,
|
||||
message: "Invalid request: unknown variant `thread/rollback`",
|
||||
},
|
||||
}),
|
||||
});
|
||||
const session = new CodexAppServerAgentSession(
|
||||
createConfig({ cwd: "/workspace/project" }),
|
||||
null,
|
||||
createTestLogger(),
|
||||
async () => appServer.child,
|
||||
);
|
||||
|
||||
await session.startTurn("remember first");
|
||||
emitCodexUserMessage(appServer, {
|
||||
id: "codex-first",
|
||||
text: "remember first",
|
||||
turnId: "turn-first",
|
||||
});
|
||||
appServer.completeTurn();
|
||||
await session.startTurn("remember second");
|
||||
emitCodexUserMessage(appServer, {
|
||||
id: "codex-second",
|
||||
text: "remember second",
|
||||
turnId: "turn-second",
|
||||
});
|
||||
appServer.completeTurn();
|
||||
|
||||
await session.revertConversation({ messageId: "codex-second" });
|
||||
|
||||
const forkRequests = appServer
|
||||
.requests()
|
||||
.filter((request) => request.method === "thread/fork")
|
||||
.map((request) => request.params);
|
||||
expect(forkRequests).toEqual([
|
||||
{
|
||||
threadId: "thread-1",
|
||||
beforeTurnId: "turn-second",
|
||||
cwd: "/workspace/project",
|
||||
model: "gpt-5.4",
|
||||
serviceTier: null,
|
||||
excludeTurns: false,
|
||||
persistExtendedHistory: true,
|
||||
},
|
||||
]);
|
||||
expect(appServer.recordedRollbacks).toEqual([]);
|
||||
await expect(session.getRuntimeInfo()).resolves.toMatchObject({
|
||||
sessionId: "forked-thread",
|
||||
});
|
||||
appServer.assertNoErrors();
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test("rewinds a paginated conversation through the public session capability", async () => {
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"thread/read": () => ({
|
||||
@@ -2290,12 +2162,7 @@ describe("Codex app-server provider", () => {
|
||||
throw new Error(`resumeSession timed out; thread requests: ${threadRequests.join(", ")}`);
|
||||
}
|
||||
|
||||
expect(threadRequests).toEqual([
|
||||
"model/list",
|
||||
"config/read",
|
||||
"thread/loaded/list",
|
||||
"thread/resume",
|
||||
]);
|
||||
expect(threadRequests).toEqual(["config/read", "thread/loaded/list", "thread/resume"]);
|
||||
expect(outcome).toBe("rejected");
|
||||
appServer.assertNoErrors();
|
||||
});
|
||||
@@ -2469,71 +2336,6 @@ describe("Codex app-server provider", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("keeps an output field named properties as a field", () => {
|
||||
const input = {
|
||||
type: "object",
|
||||
properties: { properties: { type: "string" } },
|
||||
required: ["properties"],
|
||||
additionalProperties: false,
|
||||
};
|
||||
|
||||
expect(normalizeCodexOutputSchema(input)).toEqual(input);
|
||||
});
|
||||
|
||||
test("normalizes schemas under keywords and leaves literal values alone", () => {
|
||||
const literal = { type: "object", properties: { type: "string" } };
|
||||
const input = {
|
||||
type: "object",
|
||||
properties: {
|
||||
result: { $ref: "#/$defs/result" },
|
||||
choice: { anyOf: [{ type: "object", properties: { id: { type: "string" } } }] },
|
||||
},
|
||||
$defs: {
|
||||
properties: { type: "string" },
|
||||
result: {
|
||||
type: "object",
|
||||
properties: { value: { type: "string" } },
|
||||
default: literal,
|
||||
examples: [literal],
|
||||
enum: [literal],
|
||||
const: literal,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
expect(normalizeCodexOutputSchema(input)).toEqual({
|
||||
type: "object",
|
||||
properties: {
|
||||
result: { $ref: "#/$defs/result" },
|
||||
choice: {
|
||||
anyOf: [
|
||||
{
|
||||
type: "object",
|
||||
properties: { id: { type: "string" } },
|
||||
required: ["id"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
required: ["result", "choice"],
|
||||
additionalProperties: false,
|
||||
$defs: {
|
||||
properties: { type: "string" },
|
||||
result: {
|
||||
type: "object",
|
||||
properties: { value: { type: "string" } },
|
||||
default: literal,
|
||||
examples: [literal],
|
||||
enum: [literal],
|
||||
const: literal,
|
||||
required: ["value"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test("passes a normalized output schema to turn/start", async () => {
|
||||
const session = createSession();
|
||||
const request = vi.fn(async (method: string) => {
|
||||
@@ -2659,29 +2461,6 @@ describe("Codex app-server provider", () => {
|
||||
expect(JSON.stringify(turnStart?.params)).toContain("from the provider home");
|
||||
});
|
||||
|
||||
test("inserts custom prompt arguments literally", async () => {
|
||||
await expect(
|
||||
expandCustomPrompt("Implement this exact request: $ARGUMENTS", "Preserve $1 unchanged"),
|
||||
).resolves.toBe("Implement this exact request: Preserve $1 unchanged");
|
||||
await expect(
|
||||
expandCustomPrompt("Treat this as literal replacement text: $VALUE.", 'VALUE="$&"'),
|
||||
).resolves.toBe("Treat this as literal replacement text: $&.");
|
||||
await expect(expandCustomPrompt("$1 then $2", '"$2" two')).resolves.toBe("$2 then two");
|
||||
await expect(expandCustomPrompt("$A and $B", 'A="$B" B=b')).resolves.toBe("$B and b");
|
||||
await expect(
|
||||
expandCustomPrompt("$ARGUMENTS", "keep __CODEX_DOLLAR_PLACEHOLDER__ as typed"),
|
||||
).resolves.toBe("keep __CODEX_DOLLAR_PLACEHOLDER__ as typed");
|
||||
});
|
||||
|
||||
test("expands custom prompt placeholders and escapes", async () => {
|
||||
await expect(
|
||||
expandCustomPrompt("$1/$2 $NAME costs $$5, all: $ARGUMENTS, $MISSING", "one NAME=n two"),
|
||||
).resolves.toBe("one/two n costs $5, all: one NAME=n two, $MISSING");
|
||||
await expect(
|
||||
expandCustomPrompt("$$ARGUMENTS $$1 $$NAME $9|$NAME_SUFFIX", "first NAME=value"),
|
||||
).resolves.toBe("$ARGUMENTS $1 $NAME |$NAME_SUFFIX");
|
||||
});
|
||||
|
||||
test("deduplicates Codex skill slash commands returned from multiple skill roots", async () => {
|
||||
const commands = await listCommandsFromFakeCodex([
|
||||
{
|
||||
|
||||
@@ -73,12 +73,7 @@ import {
|
||||
import { createPathEquivalenceMatcher } from "../../../utils/path.js";
|
||||
import { spawnProcess } from "../../../utils/spawn.js";
|
||||
import { extractCodexTerminalSessionId, nonEmptyString } from "./tool-call-mapper-utils.js";
|
||||
import {
|
||||
buildCodexFeatures,
|
||||
CodexServiceTierSchema,
|
||||
readCodexServiceTier,
|
||||
type CodexServiceTier,
|
||||
} from "./codex-feature-definitions.js";
|
||||
import { buildCodexFeatures, codexModelSupportsFastMode } from "./codex-feature-definitions.js";
|
||||
import {
|
||||
CodexAppServerClient,
|
||||
CodexAppServerRpcError,
|
||||
@@ -174,9 +169,6 @@ const CODEX_PLAN_IMPLEMENTATION_PROMPT_PREFIX =
|
||||
// (and the /goal slash command) when the binary is too old.
|
||||
const CODEX_GOALS_MIN_VERSION: readonly [number, number, number] = [0, 128, 0];
|
||||
const CODEX_AUTO_REVIEW_MIN_VERSION: readonly [number, number, number] = [0, 115, 0];
|
||||
// Codex removed `thread/rollback` in 0.156.0, so rewinding a legacy thread there
|
||||
// has to fork before the target turn instead.
|
||||
const CODEX_THREAD_ROLLBACK_REMOVED_VERSION: readonly [number, number, number] = [0, 156, 0];
|
||||
|
||||
function parseCodexVersion(versionOutput: string): [number, number, number] | null {
|
||||
const match = versionOutput.match(/(\d+)\.(\d+)\.(\d+)/);
|
||||
@@ -197,15 +189,6 @@ function codexVersionAtLeast(
|
||||
return true;
|
||||
}
|
||||
|
||||
// The initialize userAgent starts with `<client>/<codex version>`. An agent we
|
||||
// cannot parse is treated as an older server that still has rollback.
|
||||
function codexServerHasThreadRollback(userAgent: unknown): boolean {
|
||||
return (
|
||||
typeof userAgent !== "string" ||
|
||||
!codexVersionAtLeast(userAgent, CODEX_THREAD_ROLLBACK_REMOVED_VERSION)
|
||||
);
|
||||
}
|
||||
|
||||
type GoalSubcommand =
|
||||
| { kind: "set"; objective: string }
|
||||
| { kind: "pause" }
|
||||
@@ -382,67 +365,19 @@ function isObjectSchemaNode(schema: Record<string, unknown>): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
// Keywords whose value maps names to schemas.
|
||||
const SCHEMA_MAP_KEYWORDS = [
|
||||
"properties",
|
||||
"patternProperties",
|
||||
"$defs",
|
||||
"definitions",
|
||||
"dependentSchemas",
|
||||
] as const;
|
||||
|
||||
// Keywords whose value is a schema or an array of schemas.
|
||||
const SUBSCHEMA_KEYWORDS = [
|
||||
"items",
|
||||
"prefixItems",
|
||||
"additionalItems",
|
||||
"contains",
|
||||
"additionalProperties",
|
||||
"unevaluatedProperties",
|
||||
"unevaluatedItems",
|
||||
"propertyNames",
|
||||
"allOf",
|
||||
"anyOf",
|
||||
"oneOf",
|
||||
"not",
|
||||
"if",
|
||||
"then",
|
||||
"else",
|
||||
] as const;
|
||||
|
||||
function normalizeCodexOutputSubschema(schema: unknown, schemaPath: string): unknown {
|
||||
function normalizeCodexOutputSchemaNode(schema: unknown, schemaPath: string): unknown {
|
||||
if (Array.isArray(schema)) {
|
||||
return schema.map((entry, index) =>
|
||||
normalizeCodexOutputSchemaNode(entry, `${schemaPath}[${index}]`),
|
||||
);
|
||||
}
|
||||
return normalizeCodexOutputSchemaNode(schema, schemaPath);
|
||||
}
|
||||
|
||||
function normalizeCodexOutputSchemaNode(schema: unknown, schemaPath: string): unknown {
|
||||
if (!isSchemaRecord(schema)) {
|
||||
return schema;
|
||||
}
|
||||
|
||||
const normalized: Record<string, unknown> = { ...schema };
|
||||
for (const keyword of SCHEMA_MAP_KEYWORDS) {
|
||||
const schemas = schema[keyword];
|
||||
if (isSchemaRecord(schemas)) {
|
||||
normalized[keyword] = Object.fromEntries(
|
||||
Object.entries(schemas).map(([name, child]) => [
|
||||
name,
|
||||
normalizeCodexOutputSchemaNode(child, `${schemaPath}.${keyword}.${name}`),
|
||||
]),
|
||||
);
|
||||
}
|
||||
}
|
||||
for (const keyword of SUBSCHEMA_KEYWORDS) {
|
||||
if (keyword in schema) {
|
||||
normalized[keyword] = normalizeCodexOutputSubschema(
|
||||
schema[keyword],
|
||||
`${schemaPath}.${keyword}`,
|
||||
);
|
||||
}
|
||||
const normalized: Record<string, unknown> = {};
|
||||
for (const [key, value] of Object.entries(schema)) {
|
||||
normalized[key] = normalizeCodexOutputSchemaNode(value, `${schemaPath}.${key}`);
|
||||
}
|
||||
|
||||
if (!isObjectSchemaNode(normalized)) {
|
||||
@@ -851,21 +786,25 @@ function expandCodexCustomPrompt(template: string, args: string | undefined): st
|
||||
positional.push(token);
|
||||
}
|
||||
|
||||
// Match every placeholder in one pass, so inserted argument text is never expanded again.
|
||||
const namedPlaceholders = Object.keys(named)
|
||||
.sort((a, b) => b.length - a.length)
|
||||
.map((key) => `${escapeRegExp(key)}\\b`);
|
||||
const placeholder = new RegExp(
|
||||
`\\$(${["\\$", "ARGUMENTS", "[1-9]", ...namedPlaceholders].join("|")})`,
|
||||
"g",
|
||||
);
|
||||
const dollarPlaceholder = "__CODEX_DOLLAR_PLACEHOLDER__";
|
||||
let out = template.split("$$").join(dollarPlaceholder);
|
||||
|
||||
return template.replace(placeholder, (match, name: string) => {
|
||||
if (name === "$") return "$";
|
||||
if (name === "ARGUMENTS") return trimmedArgs;
|
||||
if (/^[1-9]$/.test(name)) return positional[Number(name) - 1] ?? "";
|
||||
return named[name] ?? match;
|
||||
});
|
||||
out = out.split("$ARGUMENTS").join(trimmedArgs);
|
||||
|
||||
for (let i = 1; i <= 9; i += 1) {
|
||||
const value = positional[i - 1] ?? "";
|
||||
out = out.split(`$${i}`).join(value);
|
||||
}
|
||||
|
||||
const namedKeys = Object.keys(named).sort((a, b) => b.length - a.length);
|
||||
for (const key of namedKeys) {
|
||||
const value = named[key] ?? "";
|
||||
const re = new RegExp(`\\$${escapeRegExp(key)}\\b`, "g");
|
||||
out = out.replace(re, value);
|
||||
}
|
||||
|
||||
out = out.split(dollarPlaceholder).join("$");
|
||||
return out;
|
||||
}
|
||||
|
||||
interface CodexMcpServerConfig {
|
||||
@@ -946,7 +885,6 @@ interface CodexModel {
|
||||
model?: string;
|
||||
defaultReasoningEffort?: string;
|
||||
supportedReasoningEfforts?: CodexReasoningEffortEntry[];
|
||||
serviceTiers?: CodexServiceTier[];
|
||||
}
|
||||
|
||||
const CodexModelListResponseSchema = z.object({
|
||||
@@ -954,7 +892,6 @@ const CodexModelListResponseSchema = z.object({
|
||||
.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
serviceTiers: z.array(CodexServiceTierSchema).optional(),
|
||||
displayName: z.string().optional(),
|
||||
description: z.string().optional(),
|
||||
isDefault: z.boolean().optional(),
|
||||
@@ -3440,14 +3377,12 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
cancelRequested: boolean;
|
||||
} | null = null;
|
||||
private client: CodexAppServerClient | null = null;
|
||||
private threadRollbackAvailable = true;
|
||||
private readonly subscribers = new Set<(event: AgentStreamEvent) => void>();
|
||||
private nextTurnOrdinal = 0;
|
||||
private activeForegroundTurnId: string | null = null;
|
||||
private activeClientMessageId: string | null = null;
|
||||
private cachedRuntimeInfo: AgentRuntimeInfo | null = null;
|
||||
private serviceTier: string | null = null;
|
||||
private speedModels: CodexModel[] = [];
|
||||
private serviceTier: "fast" | null = null;
|
||||
private planModeEnabled = false;
|
||||
private historyPending = false;
|
||||
private persistedHistory: PersistedTimelineEntry[] = [];
|
||||
@@ -3521,7 +3456,6 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
private readonly autoReviewEnabled: boolean = false,
|
||||
private readonly agentId?: string,
|
||||
private readonly initialResumePurpose: "interactive" | "history" = "interactive",
|
||||
private readonly usageEnv: NodeJS.ProcessEnv = process.env,
|
||||
) {
|
||||
this.logger = logger.child({
|
||||
module: "agent",
|
||||
@@ -3538,7 +3472,9 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
this.asyncQuestions = new CodexAsyncQuestions(resumeHandle?.metadata?.asyncQuestions);
|
||||
this.codexHome = deps.codexHome ?? resolveCodexHomeDir(process.env);
|
||||
this.config.thinkingOptionId = normalizeCodexThinkingOptionId(this.config.thinkingOptionId);
|
||||
this.serviceTier = readCodexServiceTier(this.config.featureValues);
|
||||
if (this.config.featureValues?.fast_mode && codexModelSupportsFastMode(this.config.model)) {
|
||||
this.serviceTier = "fast";
|
||||
}
|
||||
if (this.config.featureValues?.plan_mode) {
|
||||
this.planModeEnabled = true;
|
||||
}
|
||||
@@ -3549,25 +3485,14 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
}
|
||||
}
|
||||
|
||||
async getUsageReference() {
|
||||
if (this.usageEnv.OPENAI_BASE_URL) return null;
|
||||
return {
|
||||
source: "codex",
|
||||
input: {
|
||||
codexHome:
|
||||
this.usageEnv.CODEX_HOME || path.join(this.usageEnv.HOME || os.homedir(), ".codex"),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
get id(): string | null {
|
||||
return this.currentThreadId;
|
||||
}
|
||||
|
||||
get features(): AgentFeature[] {
|
||||
return buildCodexFeatures({
|
||||
serviceTiers: this.currentServiceTiers(),
|
||||
serviceTier: this.serviceTier ?? "default",
|
||||
modelId: this.config.model,
|
||||
fastModeEnabled: this.serviceTier === "fast",
|
||||
planModeEnabled: this.planModeEnabled,
|
||||
planModeAvailable: this.hasPlanCollaborationMode(),
|
||||
});
|
||||
@@ -3620,15 +3545,9 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
this.registerRequestHandlers();
|
||||
|
||||
try {
|
||||
const initialized = toObjectRecord(
|
||||
await client.request("initialize", buildCodexAppServerInitializeParams()),
|
||||
);
|
||||
this.threadRollbackAvailable = codexServerHasThreadRollback(initialized?.userAgent);
|
||||
await client.request("initialize", buildCodexAppServerInitializeParams());
|
||||
client.notify("initialized", {});
|
||||
|
||||
this.speedModels =
|
||||
CodexModelListResponseSchema.parse(await client.request("model/list", {})).data ?? [];
|
||||
this.reconcileServiceTier();
|
||||
await this.loadResolvedWorkspaceWrite();
|
||||
await this.loadCollaborationModes();
|
||||
await this.loadSkills();
|
||||
@@ -3636,7 +3555,6 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
if (this.currentThreadId) {
|
||||
await this.ensureThreadLoaded();
|
||||
await this.loadPersistedHistory(this.client);
|
||||
await this.applyDefaultModelAndThinking();
|
||||
}
|
||||
|
||||
if (this.closed) {
|
||||
@@ -3833,30 +3751,18 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
this.resolvedCollaborationMode = this.resolveCollaborationMode();
|
||||
}
|
||||
|
||||
private currentServiceTiers(): CodexServiceTier[] {
|
||||
const selectedModel = this.config.model
|
||||
? this.speedModels.find(
|
||||
(model) => model.id === this.config.model || model.model === this.config.model,
|
||||
)
|
||||
: (this.speedModels.find((model) => model.isDefault) ?? this.speedModels[0]);
|
||||
return selectedModel?.serviceTiers ?? [];
|
||||
}
|
||||
private applyFeatureValue(featureId: "fast_mode" | "plan_mode", value: boolean): void {
|
||||
this.config.featureValues = {
|
||||
...this.config.featureValues,
|
||||
[featureId]: value,
|
||||
};
|
||||
|
||||
private reconcileServiceTier(): void {
|
||||
const tiers = this.currentServiceTiers();
|
||||
// COMPAT(codexFastPreference): added in v0.10.0, remove after 2027-03-29 once saved Fast preferences have migrated.
|
||||
if (this.serviceTier === "fast" && !tiers.some((tier) => tier.id === "fast")) {
|
||||
this.serviceTier = tiers.find((tier) => tier.name.toLowerCase() === "fast")?.id ?? null;
|
||||
if (featureId === "fast_mode") {
|
||||
this.serviceTier = value ? "fast" : null;
|
||||
this.cachedRuntimeInfo = null;
|
||||
return;
|
||||
}
|
||||
if (this.serviceTier !== "default" && !tiers.some((tier) => tier.id === this.serviceTier)) {
|
||||
this.serviceTier = null;
|
||||
}
|
||||
const { fast_mode: _legacyFast, ...values } = this.config.featureValues ?? {};
|
||||
this.config.featureValues = { ...values, service_tier: this.serviceTier ?? "default" };
|
||||
}
|
||||
|
||||
private applyFeatureValue(featureId: "plan_mode", value: boolean): void {
|
||||
this.config.featureValues = { ...this.config.featureValues, [featureId]: value };
|
||||
this.planModeEnabled = value;
|
||||
this.refreshResolvedCollaborationMode();
|
||||
this.cachedRuntimeInfo = null;
|
||||
@@ -4187,7 +4093,9 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
if (thinkingOptionId) {
|
||||
params.effort = thinkingOptionId;
|
||||
}
|
||||
params.serviceTier = this.serviceTier ?? "default";
|
||||
if (this.serviceTier) {
|
||||
params.serviceTier = this.serviceTier;
|
||||
}
|
||||
if (this.resolvedCollaborationMode) {
|
||||
params.collaborationMode = {
|
||||
mode: this.resolvedCollaborationMode.mode,
|
||||
@@ -4605,7 +4513,9 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
|
||||
async setModel(modelId: string | null): Promise<void> {
|
||||
this.config.model = modelId ?? undefined;
|
||||
this.reconcileServiceTier();
|
||||
if (!codexModelSupportsFastMode(this.config.model)) {
|
||||
this.serviceTier = null;
|
||||
}
|
||||
this.refreshResolvedCollaborationMode();
|
||||
this.cachedRuntimeInfo = null;
|
||||
}
|
||||
@@ -4620,27 +4530,13 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
}
|
||||
|
||||
async setFeature(featureId: string, value: unknown): Promise<void> {
|
||||
// COMPAT(codexFastPreference): added in v0.10.0, remove after 2027-03-29 once clients use service_tier.
|
||||
if (featureId === "fast_mode") {
|
||||
const fast = this.currentServiceTiers().find((tier) => tier.name.toLowerCase() === "fast");
|
||||
if (value && !fast)
|
||||
if (Boolean(value) && !codexModelSupportsFastMode(this.config.model)) {
|
||||
throw new Error(
|
||||
`Codex fast mode is not available for model '${this.config.model ?? "default"}'`,
|
||||
);
|
||||
return this.setFeature("service_tier", value ? fast!.id : "default");
|
||||
}
|
||||
if (featureId === "service_tier") {
|
||||
if (
|
||||
typeof value !== "string" ||
|
||||
(value !== "default" && !this.currentServiceTiers().some((tier) => tier.id === value))
|
||||
) {
|
||||
throw new Error(
|
||||
`Codex speed '${String(value)}' is not available for model '${this.config.model ?? "default"}'`,
|
||||
);
|
||||
}
|
||||
this.serviceTier = value;
|
||||
this.reconcileServiceTier();
|
||||
this.cachedRuntimeInfo = null;
|
||||
this.applyFeatureValue("fast_mode", Boolean(value));
|
||||
return;
|
||||
}
|
||||
if (featureId === "plan_mode") {
|
||||
@@ -4943,7 +4839,6 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
serviceTier: this.serviceTier,
|
||||
config: this.buildCodexInnerConfig(),
|
||||
userMessageTurns: this.codexUserMessageTurns(),
|
||||
threadRollbackAvailable: this.threadRollbackAvailable,
|
||||
setThreadId: async (threadId) => {
|
||||
this.currentThreadId = threadId;
|
||||
this.cachedRuntimeInfo = null;
|
||||
@@ -5257,21 +5152,13 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
return { model, thinkingOptionId };
|
||||
}
|
||||
|
||||
// A session without a model or effort runs on Codex's configured defaults, whether its
|
||||
// thread is new or resumed after a restart.
|
||||
private async applyDefaultModelAndThinking(): Promise<string> {
|
||||
const { model, thinkingOptionId } = await this.resolveModelAndThinking();
|
||||
this.config.model = model;
|
||||
this.reconcileServiceTier();
|
||||
this.config.thinkingOptionId = thinkingOptionId;
|
||||
return model;
|
||||
}
|
||||
|
||||
private async ensureThread(): Promise<void> {
|
||||
if (!this.client) return;
|
||||
if (this.currentThreadId) return;
|
||||
|
||||
const model = await this.applyDefaultModelAndThinking();
|
||||
const { model, thinkingOptionId } = await this.resolveModelAndThinking();
|
||||
this.config.model = model;
|
||||
this.config.thinkingOptionId = thinkingOptionId;
|
||||
|
||||
const { params, approvalPolicy, sandbox } = this.buildThreadStartRequest(model);
|
||||
const rawResponse = await this.client.request("thread/start", params);
|
||||
@@ -7141,6 +7028,15 @@ export class CodexAppServerAgentClient implements AgentClient {
|
||||
private readonly deps: CodexAppServerAgentDeps = {},
|
||||
) {}
|
||||
|
||||
async resolveUsageReference() {
|
||||
const env = buildCodexAppServerEnv(this.runtimeSettings);
|
||||
if (env.OPENAI_BASE_URL) return null;
|
||||
return {
|
||||
source: "codex",
|
||||
input: { codexHome: env.CODEX_HOME || path.join(env.HOME || os.homedir(), ".codex") },
|
||||
};
|
||||
}
|
||||
|
||||
private sessionDeps(launchEnv: Record<string, string> | undefined): CodexAppServerAgentDeps {
|
||||
return {
|
||||
...this.deps,
|
||||
@@ -7262,7 +7158,6 @@ export class CodexAppServerAgentClient implements AgentClient {
|
||||
autoReviewEnabled,
|
||||
launchContext?.agentId,
|
||||
"interactive",
|
||||
buildCodexAppServerEnv(this.runtimeSettings, launchContext?.env),
|
||||
);
|
||||
await session.connect();
|
||||
return session;
|
||||
@@ -7295,7 +7190,6 @@ export class CodexAppServerAgentClient implements AgentClient {
|
||||
autoReviewEnabled,
|
||||
launchContext?.agentId,
|
||||
options?.purpose ?? "interactive",
|
||||
buildCodexAppServerEnv(this.runtimeSettings, launchContext?.env),
|
||||
);
|
||||
await session.connect();
|
||||
return session;
|
||||
|
||||
@@ -1,33 +1,27 @@
|
||||
import type { AgentFeature, AgentFeatureToggle } from "../agent-sdk-types.js";
|
||||
|
||||
import { z } from "zod";
|
||||
// Codex Fast is distinct from API Priority processing. Keep model support aligned with
|
||||
// https://developers.openai.com/codex/speed and https://developers.openai.com/codex/models.
|
||||
const CODEX_FAST_MODE_SUPPORTED_MODELS = new Set([
|
||||
"gpt-6-astra",
|
||||
"gpt-6-sol",
|
||||
"gpt-6-luna",
|
||||
"gpt-5.6",
|
||||
"gpt-5.6-sol",
|
||||
"gpt-5.6-terra",
|
||||
"gpt-5.6-luna",
|
||||
"gpt-5.5",
|
||||
"gpt-5.4",
|
||||
]);
|
||||
|
||||
export const CodexServiceTierSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
description: z.string(),
|
||||
});
|
||||
export type CodexServiceTier = z.infer<typeof CodexServiceTierSchema>;
|
||||
|
||||
function buildCodexSpeedFeature(tiers: CodexServiceTier[], value: string): AgentFeature[] {
|
||||
if (tiers.length === 0) return [];
|
||||
return [
|
||||
{
|
||||
type: "select",
|
||||
id: "service_tier",
|
||||
label: "Speed",
|
||||
description: "Choose processing speed. Faster tiers increase usage.",
|
||||
tooltip: "Select speed",
|
||||
icon: "zap",
|
||||
desktopTrigger: "icon",
|
||||
value,
|
||||
options: [
|
||||
{ id: "default", label: "Normal", isDefault: true },
|
||||
...tiers.map((tier) => ({ id: tier.id, label: tier.name })),
|
||||
],
|
||||
},
|
||||
];
|
||||
}
|
||||
export const CODEX_FAST_MODE_FEATURE: Omit<AgentFeatureToggle, "value"> = {
|
||||
type: "toggle",
|
||||
id: "fast_mode",
|
||||
label: "Fast",
|
||||
description: "Priority inference at increased usage",
|
||||
tooltip: "Toggle fast mode",
|
||||
icon: "zap",
|
||||
};
|
||||
|
||||
export const CODEX_PLAN_MODE_FEATURE: Omit<AgentFeatureToggle, "value"> = {
|
||||
type: "toggle",
|
||||
@@ -38,22 +32,40 @@ export const CODEX_PLAN_MODE_FEATURE: Omit<AgentFeatureToggle, "value"> = {
|
||||
icon: "list-todo",
|
||||
};
|
||||
|
||||
function normalizeCodexModelId(modelId: string | null | undefined): string | null {
|
||||
const normalized = typeof modelId === "string" ? modelId.trim() : "";
|
||||
return normalized.length > 0 ? normalized : null;
|
||||
}
|
||||
|
||||
export function codexModelSupportsFastMode(modelId: string | null | undefined): boolean {
|
||||
const normalizedModelId = normalizeCodexModelId(modelId);
|
||||
if (!normalizedModelId) {
|
||||
return false;
|
||||
}
|
||||
return CODEX_FAST_MODE_SUPPORTED_MODELS.has(normalizedModelId);
|
||||
}
|
||||
|
||||
export function buildCodexFeatures(input: {
|
||||
serviceTiers: CodexServiceTier[];
|
||||
serviceTier: string;
|
||||
modelId: string | null | undefined;
|
||||
fastModeEnabled: boolean;
|
||||
planModeEnabled: boolean;
|
||||
planModeAvailable?: boolean;
|
||||
}): AgentFeature[] {
|
||||
const features = buildCodexSpeedFeature(input.serviceTiers, input.serviceTier);
|
||||
if (input.planModeAvailable !== false) {
|
||||
features.push({ ...CODEX_PLAN_MODE_FEATURE, value: input.planModeEnabled });
|
||||
const features: AgentFeature[] = [];
|
||||
|
||||
if (codexModelSupportsFastMode(input.modelId)) {
|
||||
features.push({
|
||||
...CODEX_FAST_MODE_FEATURE,
|
||||
value: input.fastModeEnabled,
|
||||
});
|
||||
}
|
||||
|
||||
if (input.planModeAvailable !== false) {
|
||||
features.push({
|
||||
...CODEX_PLAN_MODE_FEATURE,
|
||||
value: input.planModeEnabled,
|
||||
});
|
||||
}
|
||||
|
||||
return features;
|
||||
}
|
||||
|
||||
export function readCodexServiceTier(values: Record<string, unknown> | undefined): string | null {
|
||||
const tier = values?.service_tier;
|
||||
if (typeof tier === "string") return tier;
|
||||
// COMPAT(codexFastPreference): added in v0.10.0, remove after 2027-03-29 once saved Fast preferences have migrated.
|
||||
return values?.fast_mode ? "fast" : null;
|
||||
}
|
||||
|
||||
@@ -96,7 +96,6 @@ describe("Codex Rewind", () => {
|
||||
model: "gpt-5.4-mini",
|
||||
serviceTier: null,
|
||||
userMessageTurns,
|
||||
threadRollbackAvailable: true,
|
||||
setThreadId: (threadId) => {
|
||||
reboundThreadId = threadId;
|
||||
},
|
||||
@@ -132,7 +131,6 @@ describe("Codex Rewind", () => {
|
||||
threadId: "source-thread",
|
||||
messageId: "codex-second",
|
||||
userMessageTurns,
|
||||
threadRollbackAvailable: true,
|
||||
setThreadId: (threadId) => {
|
||||
reboundThreadId = threadId;
|
||||
},
|
||||
@@ -177,7 +175,6 @@ describe("Codex Rewind", () => {
|
||||
model: "gpt-5.4-mini",
|
||||
serviceTier: null,
|
||||
userMessageTurns,
|
||||
threadRollbackAvailable: true,
|
||||
setThreadId: (threadId) => {
|
||||
reboundThreadId = threadId;
|
||||
},
|
||||
@@ -221,7 +218,6 @@ describe("Codex Rewind", () => {
|
||||
model: "gpt-5.4-mini",
|
||||
serviceTier: null,
|
||||
userMessageTurns,
|
||||
threadRollbackAvailable: true,
|
||||
setThreadId: (threadId) => {
|
||||
reboundThreadId = threadId;
|
||||
},
|
||||
@@ -243,7 +239,6 @@ describe("Codex Rewind", () => {
|
||||
threadId: "source-thread",
|
||||
messageId: "missing-message",
|
||||
userMessageTurns,
|
||||
threadRollbackAvailable: true,
|
||||
setThreadId: () => undefined,
|
||||
}),
|
||||
).rejects.toThrow("Codex could not find user message missing-message");
|
||||
|
||||
@@ -69,7 +69,6 @@ export async function revertCodexConversation(input: {
|
||||
serviceTier?: string | null;
|
||||
config?: Record<string, unknown> | null;
|
||||
userMessageTurns: CodexUserMessageTurnIndex;
|
||||
threadRollbackAvailable: boolean;
|
||||
setThreadId: (threadId: string) => void | Promise<void>;
|
||||
}): Promise<void> {
|
||||
if (!input.threadId) {
|
||||
@@ -99,10 +98,8 @@ export async function revertCodexConversation(input: {
|
||||
persistExtendedHistory: true,
|
||||
};
|
||||
|
||||
if (
|
||||
!input.threadRollbackAvailable ||
|
||||
(await readCodexThreadHistoryMode(input.client, input.threadId)) === "paginated"
|
||||
) {
|
||||
const historyMode = await readCodexThreadHistoryMode(input.client, input.threadId);
|
||||
if (historyMode === "paginated") {
|
||||
if (!targetTurn.turnId) {
|
||||
throw new Error(`Codex could not find the turn containing user message ${input.messageId}`);
|
||||
}
|
||||
@@ -114,8 +111,7 @@ export async function revertCodexConversation(input: {
|
||||
return;
|
||||
}
|
||||
|
||||
// Legacy threads on Codex before 0.156 fork and then roll back. Fork is
|
||||
// non-destructive: the old thread file stays on disk and remains
|
||||
// Fork is non-destructive: the old thread file stays on disk and remains
|
||||
// recoverable with `codex resume <old-uuid>` if the rewind target was wrong.
|
||||
const forked = await forkCodexThread(input.client, forkParams);
|
||||
const forkedThreadId = forked.thread.id;
|
||||
|
||||
@@ -1,64 +0,0 @@
|
||||
import { mkdtemp, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { expect, test } from "vitest";
|
||||
|
||||
import { createTestLogger } from "../../../../test-utils/test-logger.js";
|
||||
import type { AgentPersistenceHandle } from "../../agent-sdk-types.js";
|
||||
import { OmpAgentClient } from "./agent.js";
|
||||
import { FakeOmp } from "./test-utils/fake-omp.js";
|
||||
|
||||
test("archived OMP history replays messages and todos without leaving a runtime", async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "paseo-omp-history-purpose-"));
|
||||
const sessionFile = join(directory, "session.jsonl");
|
||||
const entries = [
|
||||
{ type: "session", id: "root", parentId: null },
|
||||
{
|
||||
type: "message",
|
||||
id: "user-1",
|
||||
parentId: "root",
|
||||
message: { role: "user", content: "make a plan" },
|
||||
},
|
||||
{
|
||||
type: "message",
|
||||
id: "todo-1",
|
||||
parentId: "user-1",
|
||||
message: {
|
||||
role: "toolResult",
|
||||
toolName: "todo",
|
||||
toolCallId: "call-1",
|
||||
content: [{ type: "text", text: "one task" }],
|
||||
details: {
|
||||
phases: [{ name: "Tasks", tasks: [{ content: "Check history", status: "pending" }] }],
|
||||
},
|
||||
},
|
||||
},
|
||||
];
|
||||
await writeFile(sessionFile, entries.map((entry) => JSON.stringify(entry)).join("\n"));
|
||||
const runtime = new FakeOmp();
|
||||
const client = new OmpAgentClient({ logger: createTestLogger(), runtime });
|
||||
const handle: AgentPersistenceHandle = {
|
||||
provider: "omp",
|
||||
sessionId: "history-1",
|
||||
nativeHandle: sessionFile,
|
||||
metadata: { cwd: directory },
|
||||
};
|
||||
|
||||
const session = await client.resumeSession(handle, undefined, undefined, { purpose: "history" });
|
||||
const events = [];
|
||||
try {
|
||||
for await (const event of session.streamHistory()) events.push(event);
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
|
||||
expect(runtime.recordedLaunches).toHaveLength(0);
|
||||
expect(events).toContainEqual({
|
||||
type: "timeline",
|
||||
provider: "omp",
|
||||
item: {
|
||||
type: "todo",
|
||||
items: [{ text: "Check history", status: "pending", completed: false }],
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,9 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { setImmediate as waitForImmediate } from "node:timers/promises";
|
||||
import { mkdtempSync, mkdirSync, rmSync } from "node:fs";
|
||||
import { mkdtemp, mkdir, writeFile } from "node:fs/promises";
|
||||
import { createRequire } from "node:module";
|
||||
import { tmpdir } from "node:os";
|
||||
import path, { join } from "node:path";
|
||||
import { join } from "node:path";
|
||||
|
||||
import type { AgentStreamEvent } from "../../agent-sdk-types.js";
|
||||
import type { PaseoToolCatalog } from "../../tools/types.js";
|
||||
@@ -14,9 +13,6 @@ import type { OmpUsagePollScheduler } from "./usage-poller.js";
|
||||
import { resolveOmpProviderParams } from "./provider-config.js";
|
||||
import { OmpRuntimeEventSchema } from "./rpc-types.js";
|
||||
import { OmpHarness } from "./test-utils/omp-harness.js";
|
||||
import { OmpAgentClient } from "./agent.js";
|
||||
import { FakeOmp } from "./test-utils/fake-omp.js";
|
||||
import { createTestLogger } from "../../../../test-utils/test-logger.js";
|
||||
|
||||
const TURN_LIFECYCLE_EVENTS = new Set<AgentStreamEvent["type"]>([
|
||||
"turn_started",
|
||||
@@ -51,26 +47,6 @@ test("OMP ready timeout defaults to 20 seconds and RPC timeout overrides both",
|
||||
rpcTimeoutMs: 90_000,
|
||||
});
|
||||
});
|
||||
|
||||
test("OMP import uses the runtime's custom agent directory without a configured sessionDir", async () => {
|
||||
const root = await mkdtemp(path.join(tmpdir(), "paseo-omp-import-dir-"));
|
||||
const agentDir = path.join(root, "agent");
|
||||
const sessionFile = path.join(agentDir, "sessions", "project", "session.jsonl");
|
||||
await mkdir(path.dirname(sessionFile), { recursive: true });
|
||||
await writeFile(
|
||||
sessionFile,
|
||||
JSON.stringify({ type: "session", id: "custom-dir", cwd: root, timestamp: "2026-09-28" }),
|
||||
);
|
||||
const client = new OmpAgentClient({
|
||||
logger: createTestLogger(),
|
||||
runtime: new FakeOmp(),
|
||||
runtimeSettings: { env: { PI_CODING_AGENT_DIR: agentDir } },
|
||||
});
|
||||
|
||||
expect(await client.listImportableSessions({ cwd: root })).toEqual([
|
||||
expect.objectContaining({ providerHandleId: sessionFile }),
|
||||
]);
|
||||
});
|
||||
class ManualIdleScheduler implements OmpProviderIdleScheduler {
|
||||
private readonly retries: Array<() => void> = [];
|
||||
private readonly waiters: Array<{ count: number; resolve: () => void }> = [];
|
||||
@@ -218,14 +194,20 @@ describe("OMP agent client and session", () => {
|
||||
expires: Date.now() + 60_000,
|
||||
}),
|
||||
);
|
||||
db.prepare("INSERT INTO cache (key, value, expires_at) VALUES (?, ?, ?)").run(
|
||||
"session:sticky:openai-codex:omp-session-1",
|
||||
JSON.stringify({ type: "oauth", credentialId: 1 }),
|
||||
Math.floor(Date.now() / 1000) + 100,
|
||||
);
|
||||
db.close();
|
||||
try {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start({}, undefined, {
|
||||
const env = {
|
||||
OMP_PROFILE: "",
|
||||
PI_CODING_AGENT_DIR: agentDir,
|
||||
XDG_DATA_HOME: "",
|
||||
});
|
||||
};
|
||||
const omp = new OmpHarness({ env });
|
||||
await omp.start({}, undefined, env);
|
||||
const runtime = omp.runtime();
|
||||
runtime.state = { ...runtime.state, model: { provider: "openai-codex", id: "codex-model" } };
|
||||
const requestsBefore = runtime.getStateRequestCount;
|
||||
@@ -240,6 +222,20 @@ describe("OMP agent client and session", () => {
|
||||
input: { accessToken: "claude-fixture" },
|
||||
});
|
||||
expect(runtime.getStateRequestCount).toBe(requestsBefore + 2);
|
||||
const beforeClosed = runtime.getStateRequestCount;
|
||||
expect(
|
||||
await omp.getStoredUsageReference("openai-codex/codex-model", "omp-session-1"),
|
||||
).toEqual({
|
||||
source: "codex",
|
||||
input: { accessToken: "codex-fixture", accountId: "codex-account" },
|
||||
});
|
||||
expect(
|
||||
await omp.getStoredUsageReference("openai-codex/codex-model", "omp-session-1", null),
|
||||
).toEqual({
|
||||
source: "codex",
|
||||
input: { accessToken: "codex-fixture", accountId: "codex-account" },
|
||||
});
|
||||
expect(runtime.getStateRequestCount).toBe(beforeClosed);
|
||||
await omp.close();
|
||||
} finally {
|
||||
rmSync(home, { recursive: true, force: true });
|
||||
@@ -259,7 +255,7 @@ describe("OMP agent client and session", () => {
|
||||
[expect.objectContaining({ name: "create_agent" })],
|
||||
]);
|
||||
expect(omp.capabilities()).toMatchObject({
|
||||
supportsMcpServers: true,
|
||||
supportsMcpServers: false,
|
||||
supportsNativePaseoTools: true,
|
||||
});
|
||||
});
|
||||
@@ -271,26 +267,6 @@ describe("OMP agent client and session", () => {
|
||||
expect(omp.launchConfiguration().argv).toEqual(expect.arrayContaining(["--thinking", "max"]));
|
||||
});
|
||||
|
||||
test("launches with auto thinking when auto is selected", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start({ thinkingOptionId: "auto" });
|
||||
|
||||
expect(omp.launchConfiguration().argv).toEqual(expect.arrayContaining(["--thinking", "auto"]));
|
||||
});
|
||||
|
||||
test("keeps auto thinking when resuming a session", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.resume(
|
||||
{
|
||||
user: { id: "user-auto", text: "continue" },
|
||||
assistant: { id: "assistant-auto", text: "ready" },
|
||||
},
|
||||
{ thinkingOptionId: "auto" },
|
||||
);
|
||||
|
||||
expect(omp.launchConfiguration().argv).toEqual(expect.arrayContaining(["--thinking", "auto"]));
|
||||
});
|
||||
|
||||
test("launches with write approval mode", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start({ modeId: "write" });
|
||||
@@ -487,182 +463,6 @@ describe("OMP agent client and session", () => {
|
||||
await expect(completion).resolves.toMatchObject({ finalText: "first done" });
|
||||
});
|
||||
|
||||
test("fails a turn when the provider idle gate passes its deadline", async () => {
|
||||
const scheduler = new ManualIdleScheduler();
|
||||
const omp = new OmpHarness({ providerIdleScheduler: scheduler, providerIdleDeadlineMs: 1 });
|
||||
await omp.start();
|
||||
const { completion } = await omp.startPromptUntilProviderIdle("first", "first done", {
|
||||
isStreaming: true,
|
||||
isCompacting: false,
|
||||
});
|
||||
await scheduler.waitForWaits(1);
|
||||
omp.runtime().emit({
|
||||
type: "tool_execution_start",
|
||||
toolCallId: "tool-at-deadline",
|
||||
toolName: "bash",
|
||||
args: { command: "sleep 30" },
|
||||
});
|
||||
expect(omp.runningToolCallIds()).toEqual(["tool-at-deadline"]);
|
||||
await new Promise((resolve) => setTimeout(resolve, 2));
|
||||
scheduler.retry();
|
||||
await expect(completion).rejects.toThrow(/provider idle/i);
|
||||
expect(omp.runningToolCallIds()).toEqual([]);
|
||||
});
|
||||
|
||||
test("steers a running turn and correlates a template-expanded echo exactly once", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
const session = omp.requireSession();
|
||||
const { turnId } = await session.startTurn("first", { clientMessageId: "client-first" });
|
||||
const runtime = omp.runtime();
|
||||
runtime.beginTurn();
|
||||
runtime.acceptPrompt("first", "native-first");
|
||||
await expect(
|
||||
session.steerActiveTurn?.("expand template", {
|
||||
expectedTurnId: turnId,
|
||||
clientMessageId: "client-steer",
|
||||
}),
|
||||
).resolves.toEqual({ status: "accepted" });
|
||||
runtime.acceptPrompt("expanded prompt", "native-steer");
|
||||
runtime.acceptPrompt("expanded prompt", "native-steer");
|
||||
expect(omp.timeline().filter((item) => item.type === "user_message")).toEqual([
|
||||
expect.objectContaining({ messageId: "native-first", clientMessageId: "client-first" }),
|
||||
expect.objectContaining({ messageId: "native-steer", clientMessageId: "client-steer" }),
|
||||
]);
|
||||
});
|
||||
|
||||
test("reports a rejected steer as unavailable", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
const session = omp.requireSession();
|
||||
const { turnId } = await session.startTurn("first");
|
||||
omp.runtime().steerError = new Error("extension command cannot be steered");
|
||||
await expect(
|
||||
session.steerActiveTurn?.("extension input", { expectedTurnId: turnId }),
|
||||
).resolves.toEqual({ status: "unavailable" });
|
||||
});
|
||||
|
||||
test("propagates an OMP steer transport timeout", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
const session = omp.requireSession();
|
||||
const { turnId } = await session.startTurn("first");
|
||||
const timeout = new Error(
|
||||
"OMP RPC request timed out phase=steer elapsedMs=60000 timeoutMs=60000",
|
||||
);
|
||||
omp.runtime().steerError = timeout;
|
||||
await expect(session.steerActiveTurn?.("second", { expectedTurnId: turnId })).rejects.toBe(
|
||||
timeout,
|
||||
);
|
||||
});
|
||||
|
||||
test("shows OMP's fallback model without persisting it as the selected model", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start({ model: "openrouter/google/gemini-3.8-flash" });
|
||||
const runtime = omp.runtime();
|
||||
runtime.state = {
|
||||
...runtime.state,
|
||||
model: { provider: "openrouter", id: "google/gemini-3.8-flash" },
|
||||
};
|
||||
runtime.emit({
|
||||
type: "retry_fallback_applied",
|
||||
from: "openrouter/google/gemini-3.8-flash",
|
||||
to: "openrouter/other/model",
|
||||
role: "primary",
|
||||
});
|
||||
runtime.state = { ...runtime.state, model: { provider: "openrouter", id: "other/model" } };
|
||||
runtime.state = { ...runtime.state, fastModeEnabled: true, fastModeActive: false };
|
||||
runtime.emit({ type: "model_changed" });
|
||||
await waitForImmediate();
|
||||
expect(omp.eventTypes()).toContain("model_changed");
|
||||
expect((await omp.requireSession().getRuntimeInfo()).model).toBe("openrouter/other/model");
|
||||
expect(omp.requireSession().describePersistence()?.metadata?.model).toBe(
|
||||
"openrouter/google/gemini-3.8-flash",
|
||||
);
|
||||
expect(omp.requireSession().features).toEqual([
|
||||
expect.objectContaining({
|
||||
value: true,
|
||||
description: expect.stringMatching(/does not apply/i),
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
test("Fast stays selected when OMP says it is inactive for the current model", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start({ model: "openrouter/google/gemini-3.8-flash" });
|
||||
const session = omp.requireSession();
|
||||
omp.runtime().fastModeResult = { enabled: true, active: false };
|
||||
await session.setFeature?.("fast_mode", true);
|
||||
expect(omp.runtime().setFastModeRequests).toEqual([true]);
|
||||
expect(session.features).toEqual([
|
||||
expect.objectContaining({
|
||||
id: "fast_mode",
|
||||
value: true,
|
||||
description: expect.stringMatching(/does not apply to this model/i),
|
||||
tooltip: expect.stringMatching(/does not apply to this model/i),
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
test("shows Fast only when OMP reports its state fields", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
const session = omp.requireSession();
|
||||
const {
|
||||
fastModeEnabled: _enabled,
|
||||
fastModeActive: _active,
|
||||
...olderState
|
||||
} = omp.runtime().state;
|
||||
omp.runtime().state = olderState;
|
||||
await session.getRuntimeInfo();
|
||||
expect(session.features).toEqual([]);
|
||||
await expect(session.setFeature?.("fast_mode", true)).rejects.toThrow(/unavailable/i);
|
||||
omp.runtime().state = { ...olderState, fastModeEnabled: false, fastModeActive: false };
|
||||
await session.getRuntimeInfo();
|
||||
expect(session.features).toHaveLength(1);
|
||||
});
|
||||
|
||||
test("switching model refreshes whether Fast applies", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start({ model: "openrouter/google/gemini-3.8-flash" });
|
||||
const session = omp.requireSession();
|
||||
omp.runtime().fastModeResult = { enabled: true, active: true };
|
||||
await session.setFeature?.("fast_mode", true);
|
||||
expect(session.features).toEqual([expect.objectContaining({ value: true })]);
|
||||
|
||||
omp.runtime().setModelResult = { provider: "openrouter", id: "other/model" };
|
||||
omp.runtime().queueStateReports([
|
||||
{
|
||||
...omp.runtime().state,
|
||||
model: omp.runtime().setModelResult,
|
||||
fastModeEnabled: true,
|
||||
fastModeActive: false,
|
||||
},
|
||||
]);
|
||||
await session.setModel?.("openrouter/other/model");
|
||||
expect(session.features).toEqual([
|
||||
expect.objectContaining({
|
||||
value: true,
|
||||
description: expect.stringMatching(/does not apply/i),
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
test("restores Fast from the initial OMP state on create and resume", async () => {
|
||||
const created = new OmpHarness();
|
||||
await created.start({ featureValues: { fast_mode: true } });
|
||||
expect(created.runtime().setFastModeRequests).toEqual([true]);
|
||||
expect(created.runtime().getStateRequestCount).toBe(1);
|
||||
|
||||
const resumed = new OmpHarness();
|
||||
await resumed.resume(
|
||||
{ user: { id: "user-1", text: "hello" }, assistant: { id: "assistant-1", text: "hi" } },
|
||||
{ featureValues: { fast_mode: true } },
|
||||
);
|
||||
expect(resumed.runtime().setFastModeRequests).toEqual([true]);
|
||||
expect(resumed.runtime().getStateRequestCount).toBe(1);
|
||||
});
|
||||
|
||||
test("does not complete on OMP's extension-notice agent_end", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
@@ -735,162 +535,13 @@ describe("OMP agent client and session", () => {
|
||||
message: "Background job DocsSmokeTwo completed",
|
||||
},
|
||||
]);
|
||||
// Non-notice custom messages still fall through as assistant messages with
|
||||
// their own id so the stream coalescer never glues them onto the open reply.
|
||||
expect(omp.timeline().filter((item) => item.type === "assistant_message")).toEqual([
|
||||
{ type: "assistant_message", text: "done", messageId: "omp-assistant-1" },
|
||||
{ type: "assistant_message", text: "plain custom status text", messageId: "omp-custom-1" },
|
||||
// Non-notice custom messages still fall through as assistant messages.
|
||||
expect(omp.timeline().filter((item) => item.type === "assistant_message")).toMatchObject([
|
||||
{ text: "done" },
|
||||
{ text: "plain custom status text" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("shows a concise error for a failed tool while keeping shell output", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
omp.emit({
|
||||
type: "tool_execution_start",
|
||||
toolCallId: "failed-shell",
|
||||
toolName: "bash",
|
||||
args: { command: "false" },
|
||||
});
|
||||
omp.emit({
|
||||
type: "tool_execution_end",
|
||||
toolCallId: "failed-shell",
|
||||
toolName: "bash",
|
||||
result: {
|
||||
content: [{ type: "text", text: "Command exited with code 1" }],
|
||||
details: {},
|
||||
isError: true,
|
||||
exitCode: 1,
|
||||
},
|
||||
isError: true,
|
||||
});
|
||||
expect(omp.timeline().at(-1)).toMatchObject({
|
||||
type: "tool_call",
|
||||
status: "failed",
|
||||
error: "Command exited with code 1",
|
||||
detail: { type: "shell", command: "false", exitCode: 1 },
|
||||
});
|
||||
});
|
||||
|
||||
test("uses the exit message when a failed shell has no output", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
omp.emit({
|
||||
type: "tool_execution_start",
|
||||
toolCallId: "empty-shell",
|
||||
toolName: "bash",
|
||||
args: { command: "false" },
|
||||
});
|
||||
omp.emit({
|
||||
type: "tool_execution_end",
|
||||
toolCallId: "empty-shell",
|
||||
toolName: "bash",
|
||||
result: {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "(no output)\n\nWall time: 0.02 seconds\n\nCommand exited with code 1",
|
||||
},
|
||||
],
|
||||
isError: true,
|
||||
},
|
||||
isError: true,
|
||||
});
|
||||
expect(omp.timeline().at(-1)).toMatchObject({ error: "Command exited with code 1" });
|
||||
});
|
||||
|
||||
test("does not duplicate the typed invocation for a live skill expansion", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
await omp.runPromptWithCustomMessage(
|
||||
"hello",
|
||||
{
|
||||
role: "custom",
|
||||
content: "[IMPORTANT] Full skill body",
|
||||
customType: "skill-prompt",
|
||||
attribution: "user",
|
||||
details: { name: "commit" },
|
||||
display: true,
|
||||
id: "skill-1",
|
||||
},
|
||||
"done",
|
||||
);
|
||||
expect(omp.timeline().filter((item) => item.type === "user_message")).toEqual([
|
||||
{ type: "user_message", text: "hello", messageId: "user-1" },
|
||||
]);
|
||||
expect(omp.timeline()).not.toContainEqual(
|
||||
expect.objectContaining({ text: "[IMPORTANT] Full skill body" }),
|
||||
);
|
||||
});
|
||||
|
||||
test.each([
|
||||
{ kind: "initial", priorPrompt: false },
|
||||
{ kind: "follow-up", priorPrompt: true },
|
||||
])("correlates a $kind skill invocation without a user echo", async ({ priorPrompt }) => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
if (priorPrompt) {
|
||||
await omp.runPrompt("Reply OK", "OK");
|
||||
}
|
||||
|
||||
const typed = "/skill:tldr Summarize: hi.";
|
||||
const runtime = omp.runtime();
|
||||
const promptStarted = runtime.nextPrompt();
|
||||
const run = omp.requireSession().run(typed, { clientMessageId: "client-skill" });
|
||||
await promptStarted;
|
||||
runtime.beginTurn();
|
||||
runtime.emit({
|
||||
type: "message_end",
|
||||
message: {
|
||||
role: "custom",
|
||||
content: "[IMPORTANT] Full skill body",
|
||||
customType: "skill-prompt",
|
||||
attribution: "user",
|
||||
details: { name: "tldr", args: "Summarize: hi." },
|
||||
display: true,
|
||||
id: "skill-1",
|
||||
},
|
||||
});
|
||||
runtime.streamAssistantText("done");
|
||||
runtime.finishTurn();
|
||||
await run;
|
||||
|
||||
expect(omp.timeline().filter((item) => item.type === "user_message")).toEqual([
|
||||
...(priorPrompt ? [{ type: "user_message", text: "Reply OK", messageId: "user-1" }] : []),
|
||||
{ type: "user_message", text: typed, clientMessageId: "client-skill" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("marks an OMP web search details error as failed even without isError", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
omp.emit({
|
||||
type: "tool_execution_start",
|
||||
toolCallId: "search-failed",
|
||||
toolName: "web_search",
|
||||
args: { query: "Paseo" },
|
||||
});
|
||||
omp.emit({
|
||||
type: "tool_execution_end",
|
||||
toolCallId: "search-failed",
|
||||
toolName: "web_search",
|
||||
result: {
|
||||
content: [{ type: "text", text: "Error: All web search providers failed" }],
|
||||
details: {
|
||||
response: { provider: "mojeek", sources: [] },
|
||||
error: "All web search providers failed",
|
||||
},
|
||||
},
|
||||
isError: false,
|
||||
});
|
||||
expect(omp.timeline().at(-1)).toMatchObject({
|
||||
type: "tool_call",
|
||||
status: "failed",
|
||||
error: "All web search providers failed",
|
||||
detail: { type: "search", query: "Paseo" },
|
||||
});
|
||||
});
|
||||
|
||||
test("does not complete a queued model turn from OMP's local-only hint", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
@@ -909,28 +560,6 @@ describe("OMP agent client and session", () => {
|
||||
expect(omp.completedTurnCount()).toBe(1);
|
||||
});
|
||||
|
||||
test("completes a no-turn notify with one notification and no assistant text", async () => {
|
||||
const scheduler = new ManualNoTurnScheduler();
|
||||
const omp = new OmpHarness({ noTurnScheduler: scheduler });
|
||||
await omp.start();
|
||||
const prompt = await omp.startPromptWithFalseLocalOnlyResult("/autoresearch off");
|
||||
omp.emit({
|
||||
type: "extension_ui_request",
|
||||
id: "local-notify",
|
||||
method: "notify",
|
||||
message: "Autoresearch mode disabled",
|
||||
notifyType: "info",
|
||||
});
|
||||
|
||||
scheduler.settle();
|
||||
await expect(prompt.completion).resolves.toMatchObject({ finalText: "" });
|
||||
expect(omp.completedTurnCount()).toBe(1);
|
||||
expect(omp.timeline().filter((item) => item.type === "notification")).toEqual([
|
||||
{ type: "notification", level: "info", message: "Autoresearch mode disabled" },
|
||||
]);
|
||||
expect(omp.timeline().filter((item) => item.type === "assistant_message")).toEqual([]);
|
||||
});
|
||||
|
||||
test("waits for a delayed queued model turn after OMP's local-only result", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
@@ -1050,33 +679,6 @@ describe("OMP agent client and session", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
test("shows OMP notifications during a turn and while idle with their levels", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
await omp.startTurn("work");
|
||||
omp.runtime().beginTurn();
|
||||
omp.emit({
|
||||
type: "extension_ui_request",
|
||||
id: "n1",
|
||||
method: "notify",
|
||||
message: "Working",
|
||||
notifyType: "warning",
|
||||
});
|
||||
omp.runtime().finishTurn();
|
||||
omp.emit({
|
||||
type: "extension_ui_request",
|
||||
id: "n2",
|
||||
method: "notify",
|
||||
message: "Done",
|
||||
notifyType: "info",
|
||||
});
|
||||
expect(omp.timeline().filter((item) => item.type === "notification")).toEqual([
|
||||
{ type: "notification", level: "warning", message: "Working" },
|
||||
{ type: "notification", level: "info", message: "Done" },
|
||||
]);
|
||||
expect(omp.timeline().filter((item) => item.type === "assistant_message")).toEqual([]);
|
||||
});
|
||||
|
||||
test("maps legacy select options without descriptions and preserves ordinary responses", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
@@ -1142,6 +744,41 @@ describe("OMP agent client and session", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
test("preserves combined selection descriptions and freeform sentinel behavior", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
omp.emit({
|
||||
type: "tool_execution_start",
|
||||
toolCallId: "ask-user-1",
|
||||
toolName: "ask_user",
|
||||
args: { allowComment: true, allowFreeform: true, allowMultiple: false },
|
||||
});
|
||||
omp.emit({
|
||||
type: "extension_ui_request",
|
||||
id: "select-combined",
|
||||
method: "select",
|
||||
title: "Choose",
|
||||
options: ["First", "✏️ Type custom response..."],
|
||||
optionDetails: [{ description: "First detail" }, { description: "ignored" }],
|
||||
});
|
||||
|
||||
const combinedInput = omp.pendingPermissions()[0]?.input;
|
||||
expect(combinedInput?.questions?.[0]?.options).toStrictEqual([
|
||||
{ label: "First", description: "First detail" },
|
||||
]);
|
||||
expect(combinedInput).toMatchObject({
|
||||
questions: [{ allowOther: true }, { header: "Comment" }],
|
||||
});
|
||||
await omp.respondToPermission("select-combined", {
|
||||
behavior: "allow",
|
||||
updatedInput: { answers: { Response: "custom", Comment: "note" } },
|
||||
});
|
||||
expect(omp.extensionUiResponses()).toContainEqual({
|
||||
id: "select-combined",
|
||||
response: { value: "✏️ Type custom response..." },
|
||||
});
|
||||
});
|
||||
|
||||
test("exposes OMP modes and commands through the domain session", async () => {
|
||||
const omp = new OmpHarness();
|
||||
omp.queueCommands([{ name: "review", description: "Review changes", source: "skill" }]);
|
||||
@@ -1158,99 +795,10 @@ describe("OMP agent client and session", () => {
|
||||
expect.objectContaining({ name: "review", kind: "skill" }),
|
||||
]),
|
||||
);
|
||||
await expect(omp.setMode("ask")).resolves.toBeUndefined();
|
||||
await expect(omp.currentMode()).resolves.toBe("ask");
|
||||
expect(omp.runtimeLaunches()[1]?.argv).toContain("--approval-mode");
|
||||
expect(omp.runtimeLaunches()[1]?.argv).toContain("always-ask");
|
||||
});
|
||||
|
||||
test("restarts the same conversation after an idle process exit", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start({ modeId: "full" });
|
||||
const previousId = omp.runtime().state.sessionId;
|
||||
omp.processExit("OMP RPC process exited with code null and signal SIGKILL\nBun crashed");
|
||||
expect(omp.turnFailures()).toEqual([
|
||||
"OMP RPC process exited with code null and signal SIGKILL\nBun crashed",
|
||||
]);
|
||||
|
||||
await omp.startTurn("remember the conversation");
|
||||
expect(omp.runtimeLaunches()).toHaveLength(2);
|
||||
expect(omp.runtimeLaunches()[1]?.session).toBe("/tmp/omp-session");
|
||||
expect(omp.runtime().state.sessionId).toBe(previousId);
|
||||
expect(omp.threadStartedSessionIds()).toEqual([]);
|
||||
expect(omp.runtime().prompts).toEqual([
|
||||
{ message: "remember the conversation", imageCount: 0 },
|
||||
]);
|
||||
});
|
||||
|
||||
test("reports a mid-turn process exit and resumes on the following prompt", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
await omp.requireStartTurn("sleep 30");
|
||||
omp.runtime().beginTurn();
|
||||
omp.processExit("OMP RPC process exited with code 137 and signal null\nOOM");
|
||||
expect(omp.turnFailures()).toEqual([
|
||||
"OMP RPC process exited with code 137 and signal null\nOOM",
|
||||
]);
|
||||
await omp.startTurn("continue");
|
||||
expect(omp.runtimeLaunches()).toHaveLength(2);
|
||||
expect(omp.runtime().prompts).toEqual([{ message: "continue", imageCount: 0 }]);
|
||||
});
|
||||
|
||||
test("reports an immediate relaunch failure without retrying in a loop", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
omp.processExit("OMP RPC process exited with code null and signal SIGKILL");
|
||||
omp.failNextStart(new Error("Bun failed during startup"));
|
||||
await omp.startTurn("continue");
|
||||
expect(omp.turnFailures()).toEqual([
|
||||
"OMP RPC process exited with code null and signal SIGKILL",
|
||||
"Bun failed during startup",
|
||||
]);
|
||||
expect(omp.runtimeLaunches()).toHaveLength(1);
|
||||
});
|
||||
|
||||
test("closes a replacement process if the session closes during relaunch", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
omp.processExit("OMP RPC process exited with code 1 and signal null");
|
||||
const turn = omp.startTurnDetached("continue");
|
||||
await omp.close();
|
||||
await turn;
|
||||
await waitForImmediate();
|
||||
expect(omp.runtimeSessions().every((session) => session.closed)).toBe(true);
|
||||
});
|
||||
|
||||
test("announces a fresh native session when an internal agent recovers", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start({ internal: true });
|
||||
const previousId = omp.runtime().state.sessionId;
|
||||
omp.processExit("OMP RPC process exited with code 1 and signal null");
|
||||
await omp.startTurn("continue");
|
||||
expect(omp.runtimeLaunches()[1]?.argv).toContain("--no-session");
|
||||
expect(omp.runtime().state.sessionId).not.toBe(previousId);
|
||||
expect(omp.threadStartedSessionIds()).toEqual([omp.runtime().state.sessionId]);
|
||||
});
|
||||
|
||||
test("leaves the current approval mode in place when relaunch fails", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start({ modeId: "full" });
|
||||
omp.failNextStart(new Error("OMP launch failed"));
|
||||
await expect(omp.setMode("ask")).rejects.toThrow("OMP launch failed");
|
||||
expect(await omp.currentMode()).toBe("full");
|
||||
expect(omp.runtimeLaunches()).toHaveLength(1);
|
||||
});
|
||||
|
||||
test("rejects a running approval-mode change until the turn ends", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start({ modeId: "full" });
|
||||
await omp.requireStartTurn("work");
|
||||
await expect(omp.setMode("ask")).resolves.toEqual({
|
||||
type: "warning",
|
||||
message: "Change approval mode once the current turn ends",
|
||||
message: "Start a new OMP session to change approval mode",
|
||||
});
|
||||
expect(omp.runtimeLaunches()).toHaveLength(1);
|
||||
expect(await omp.currentMode()).toBe("full");
|
||||
});
|
||||
|
||||
test("rewinds natively, interrupts, and shuts down", async () => {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,311 +0,0 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import { OmpHarness } from "./test-utils/omp-harness.js";
|
||||
|
||||
function startAsk(omp: OmpHarness, multi: boolean): void {
|
||||
omp.emit({
|
||||
type: "tool_execution_start",
|
||||
toolCallId: "ask-1",
|
||||
toolName: "ask",
|
||||
args: {
|
||||
questions: [
|
||||
{
|
||||
id: "colors",
|
||||
question: "Which colors?",
|
||||
multi,
|
||||
options: [
|
||||
{ label: "Red", description: "Warm" },
|
||||
{ label: "Blue", description: "Cool" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function select(omp: OmpHarness, id: string, title: string, options: string[]): void {
|
||||
omp.emit({ type: "extension_ui_request", id, method: "select", title, options });
|
||||
}
|
||||
|
||||
describe("OMP ask RPC UI", () => {
|
||||
test("recognizes ask arguments from the assistant message before the UI request", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
omp.emit({
|
||||
type: "message_end",
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: [
|
||||
{
|
||||
type: "toolCall",
|
||||
id: "ask-1",
|
||||
name: "ask",
|
||||
arguments: {
|
||||
questions: [
|
||||
{
|
||||
id: "colors",
|
||||
question: "Which colors?",
|
||||
multi: true,
|
||||
options: [
|
||||
{ label: "Red", description: "Warm" },
|
||||
{ label: "Blue", description: "Cool" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
select(omp, "select-1", "Which colors?", ["Red", "Blue", "Other (type your own)"]);
|
||||
expect(omp.pendingPermissions()[0]?.input?.questions?.[0]).toMatchObject({
|
||||
multiSelect: true,
|
||||
allowOther: true,
|
||||
});
|
||||
startAsk(omp, true);
|
||||
});
|
||||
test("answers the multi-select loop from one Paseo question", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
startAsk(omp, true);
|
||||
select(omp, "select-1", "Which colors?", ["Red", "Blue", "Other (type your own)"]);
|
||||
|
||||
expect(omp.pendingPermissions()).toHaveLength(1);
|
||||
expect(omp.pendingPermissions()[0]).toMatchObject({
|
||||
kind: "question",
|
||||
input: {
|
||||
questions: [
|
||||
{
|
||||
question: "Which colors?",
|
||||
multiSelect: true,
|
||||
allowOther: true,
|
||||
options: [{ label: "Red" }, { label: "Blue" }],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
await omp.respondToPermission("select-1", {
|
||||
behavior: "allow",
|
||||
updatedInput: { answers: { Response: "Blue, Red" } },
|
||||
});
|
||||
select(omp, "select-2", "(1 selected) Which colors?", [
|
||||
"Red",
|
||||
"Blue",
|
||||
"✓ Done selecting",
|
||||
"Other (type your own)",
|
||||
]);
|
||||
select(omp, "select-3", "(2 selected) Which colors?", [
|
||||
"Red",
|
||||
"Blue",
|
||||
"✔ Done selecting",
|
||||
"Other (type your own)",
|
||||
]);
|
||||
|
||||
expect(omp.pendingPermissions()).toHaveLength(0);
|
||||
expect(omp.extensionUiResponses()).toEqual([
|
||||
{ id: "select-1", response: { value: "Blue" } },
|
||||
{ id: "select-2", response: { value: "Red" } },
|
||||
{ id: "select-3", response: { value: "✔ Done selecting" } },
|
||||
]);
|
||||
});
|
||||
|
||||
test("passes a single-select Other answer through OMP's editor", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
startAsk(omp, false);
|
||||
select(omp, "select-1", "Which colors?", ["Red", "Blue", "Other (type your own)"]);
|
||||
expect(omp.pendingPermissions()[0]?.input?.questions?.[0]).toMatchObject({ allowOther: true });
|
||||
await omp.respondToPermission("select-1", {
|
||||
behavior: "allow",
|
||||
updatedInput: { answers: { Response: "Violet" } },
|
||||
});
|
||||
omp.emit({
|
||||
type: "extension_ui_request",
|
||||
id: "editor-1",
|
||||
method: "editor",
|
||||
title: "Which colors? ○ Red ○ Blue ◉ Other (type your own) Enter your response:",
|
||||
});
|
||||
|
||||
expect(omp.pendingPermissions()).toHaveLength(0);
|
||||
expect(omp.extensionUiResponses()).toEqual([
|
||||
{ id: "select-1", response: { value: "Other (type your own)" } },
|
||||
{ id: "editor-1", response: { value: "Violet" } },
|
||||
]);
|
||||
});
|
||||
|
||||
test("passes multi-select choices and Other through the same editor flow", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
startAsk(omp, true);
|
||||
select(omp, "select-1", "Which colors?", ["Red", "Blue", "Other (type your own)"]);
|
||||
await omp.respondToPermission("select-1", {
|
||||
behavior: "allow",
|
||||
updatedInput: { answers: { Response: "Red, Violet" } },
|
||||
});
|
||||
select(omp, "select-2", "(1 selected) Which colors?", [
|
||||
"Red",
|
||||
"Blue",
|
||||
"✓ Done selecting",
|
||||
"Other (type your own)",
|
||||
]);
|
||||
omp.emit({
|
||||
type: "extension_ui_request",
|
||||
id: "editor-1",
|
||||
method: "editor",
|
||||
title: "(1 selected) Which colors?",
|
||||
});
|
||||
|
||||
expect(omp.pendingPermissions()).toHaveLength(0);
|
||||
expect(omp.extensionUiResponses()).toEqual([
|
||||
{ id: "select-1", response: { value: "Red" } },
|
||||
{ id: "select-2", response: { value: "Other (type your own)" } },
|
||||
{ id: "editor-1", response: { value: "Violet" } },
|
||||
]);
|
||||
});
|
||||
|
||||
test("cancels an ask without leaving replay state behind", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
startAsk(omp, true);
|
||||
select(omp, "select-1", "Which colors?", ["Red", "Blue", "Other (type your own)"]);
|
||||
await omp.respondToPermission("select-1", { behavior: "deny" });
|
||||
select(omp, "select-after-cancel", "Another question", ["One", "Two"]);
|
||||
|
||||
expect(omp.extensionUiResponses()).toEqual([{ id: "select-1", response: { cancelled: true } }]);
|
||||
expect(omp.pendingPermissions()).toHaveLength(1);
|
||||
expect(omp.pendingPermissions()[0]?.id).toBe("select-after-cancel");
|
||||
});
|
||||
|
||||
test("keeps single choices, tool approvals, and free-form input independent", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
startAsk(omp, false);
|
||||
select(omp, "select-1", "Which colors?", ["Red", "Blue", "Other (type your own)"]);
|
||||
await omp.respondToPermission("select-1", {
|
||||
behavior: "allow",
|
||||
updatedInput: { answers: { Response: "Blue" } },
|
||||
});
|
||||
expect(omp.extensionUiResponses()).toContainEqual({
|
||||
id: "select-1",
|
||||
response: { value: "Blue" },
|
||||
});
|
||||
|
||||
omp.emit({
|
||||
type: "tool_execution_end",
|
||||
toolCallId: "ask-1",
|
||||
toolName: "ask",
|
||||
result: "Blue",
|
||||
isError: false,
|
||||
});
|
||||
omp.requestToolApproval({ id: "approval", tool: "bash", detail: "echo hi" });
|
||||
expect(omp.pendingPermissions()[0]).toMatchObject({ id: "approval", kind: "tool" });
|
||||
await omp.respondToPermission("approval", { behavior: "allow" });
|
||||
expect(omp.extensionUiResponses()).toContainEqual({
|
||||
id: "approval",
|
||||
response: { value: "Approve" },
|
||||
});
|
||||
|
||||
omp.emit({ type: "extension_ui_request", id: "input", method: "input", title: "Type a value" });
|
||||
expect(omp.pendingPermissions()[0]).toMatchObject({ id: "input", kind: "question" });
|
||||
await omp.respondToPermission("input", {
|
||||
behavior: "allow",
|
||||
updatedInput: { answers: { Response: "typed value" } },
|
||||
});
|
||||
expect(omp.extensionUiResponses()).toContainEqual({
|
||||
id: "input",
|
||||
response: { value: "typed value" },
|
||||
});
|
||||
});
|
||||
|
||||
test("recognizes OMP's numbered question title", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
startAsk(omp, true);
|
||||
select(omp, "select-1", "Which colors? (1/2)", ["Red", "Blue", "Other (type your own)"]);
|
||||
expect(omp.pendingPermissions()[0]?.input?.questions?.[0]).toMatchObject({ multiSelect: true });
|
||||
});
|
||||
|
||||
test("keeps descriptions with their labels when a select event reorders rows", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
startAsk(omp, true);
|
||||
select(omp, "select-1", "Which colors?", ["Blue", "Red", "Other (type your own)"]);
|
||||
|
||||
expect(omp.pendingPermissions()[0]?.input?.questions?.[0]?.options).toEqual([
|
||||
{ label: "Blue", description: "Cool" },
|
||||
{ label: "Red", description: "Warm" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("keeps a recommended option's description with its display label", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
startAsk(omp, false);
|
||||
select(omp, "select-1", "Which colors?", [
|
||||
"Red (Recommended)",
|
||||
"Blue",
|
||||
"Other (type your own)",
|
||||
]);
|
||||
expect(omp.pendingPermissions()[0]?.input?.questions?.[0]?.options).toEqual([
|
||||
{ label: "Red (Recommended)", description: "Warm" },
|
||||
{ label: "Blue", description: "Cool" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("cancels cleanly when OMP omits Done selecting in a multi-question ask", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
omp.emit({
|
||||
type: "tool_execution_start",
|
||||
toolCallId: "ask-1",
|
||||
toolName: "ask",
|
||||
args: {
|
||||
questions: [
|
||||
{
|
||||
id: "colors",
|
||||
question: "Which colors?",
|
||||
multi: true,
|
||||
options: [{ label: "Red" }, { label: "Blue" }],
|
||||
},
|
||||
{
|
||||
id: "shape",
|
||||
question: "Which shape?",
|
||||
options: [{ label: "Round" }, { label: "Square" }],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
select(omp, "select-1", "Which colors? (1/2)", ["Red", "Blue", "Other (type your own)"]);
|
||||
await omp.respondToPermission("select-1", {
|
||||
behavior: "allow",
|
||||
updatedInput: { answers: { Response: "Red" } },
|
||||
});
|
||||
// OMP's RPC select omits the right-arrow navigation callback and, with
|
||||
// allowForward true, also omits its Done row on every follow-up request.
|
||||
select(omp, "select-2", "(1 selected) Which colors? (1/2)", [
|
||||
"Red",
|
||||
"Blue",
|
||||
"Other (type your own)",
|
||||
]);
|
||||
|
||||
expect(omp.extensionUiResponses()).toEqual([
|
||||
{ id: "select-1", response: { value: "Red" } },
|
||||
{ id: "select-2", response: { cancelled: true } },
|
||||
]);
|
||||
expect(omp.pendingPermissions()).toHaveLength(0);
|
||||
omp.emit({
|
||||
type: "tool_execution_end",
|
||||
toolCallId: "ask-1",
|
||||
toolName: "ask",
|
||||
result: "Ask tool was cancelled by the user",
|
||||
isError: true,
|
||||
});
|
||||
expect(omp.timeline()).toContainEqual(
|
||||
expect.objectContaining({
|
||||
type: "tool_call",
|
||||
name: "ask",
|
||||
status: "failed",
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -98,14 +98,6 @@ function replyToCommands(
|
||||
});
|
||||
}
|
||||
|
||||
function capturePendingCommand(child: OmpChild, type: string): Promise<Record<string, unknown>> {
|
||||
return new Promise((resolve) => {
|
||||
onOmpCommand(child, (command) => {
|
||||
if (command.type === type) resolve(command);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** Kill the child the moment it receives `type`, so the request is in flight when it dies. */
|
||||
function exitOnCommand(child: OmpChild, type: string): void {
|
||||
onOmpCommand(child, (command) => {
|
||||
@@ -121,22 +113,6 @@ function withoutRequestId(command: Record<string, unknown>): Record<string, unkn
|
||||
}
|
||||
|
||||
describe("OMP CLI runtime", () => {
|
||||
test("steer waits for OMP's response and surfaces rejection", async () => {
|
||||
const child = createOmpChild();
|
||||
let pending: Record<string, unknown> | null = null;
|
||||
onOmpCommand(child, (command) => {
|
||||
if (command.type === "steer") pending = command;
|
||||
});
|
||||
const session = await createRuntime(child).startSession({ cwd: "/workspace/project" });
|
||||
const result = session.steer("change direction");
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
expect(pending).toMatchObject({ type: "steer", message: "change direction" });
|
||||
child.stdout.write(
|
||||
`${JSON.stringify({ id: pending!.id, type: "response", command: "steer", success: false, error: "rejected" })}\n`,
|
||||
);
|
||||
await expect(result).rejects.toThrow("rejected");
|
||||
await session.close();
|
||||
});
|
||||
test("uses the configured RPC timeout and attributes the pending phase", async () => {
|
||||
vi.useFakeTimers();
|
||||
const child = createOmpChild();
|
||||
@@ -317,27 +293,6 @@ describe("OMP CLI runtime", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
test("compact waits beyond the control-plane timeout for a late response", async () => {
|
||||
vi.useFakeTimers();
|
||||
const child = createOmpChild();
|
||||
const pending = capturePendingCommand(child, "compact");
|
||||
const session = await createRuntime(child, [], { requestTimeoutMs: 100 }).startSession({
|
||||
cwd: "/workspace/project",
|
||||
});
|
||||
try {
|
||||
const compact = session.compact("focus on tests");
|
||||
const command = await pending;
|
||||
await vi.advanceTimersByTimeAsync(101);
|
||||
child.stdout.write(
|
||||
`${JSON.stringify({ id: command.id, type: "response", command: "compact", success: true, data: {} })}\n`,
|
||||
);
|
||||
await expect(compact).resolves.toBeUndefined();
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("accepts the empty prompt acknowledgement emitted by OMP 17", async () => {
|
||||
const child = createOmpChild();
|
||||
replyToCommands(child, () => undefined);
|
||||
|
||||
@@ -1,13 +1,8 @@
|
||||
import type { ChildProcessWithoutNullStreams } from "node:child_process";
|
||||
import type { Logger } from "pino";
|
||||
import { z } from "zod";
|
||||
|
||||
import type { ProviderRuntimeSettings } from "../../provider-launch-config.js";
|
||||
import {
|
||||
JSONL_RPC_NO_TIMEOUT,
|
||||
JsonlRpcProcess,
|
||||
type JsonlRpcLaunch,
|
||||
} from "../jsonl-rpc-process.js";
|
||||
import { JsonlRpcProcess, type JsonlRpcLaunch } from "../jsonl-rpc-process.js";
|
||||
import { establishOmpProtocol } from "./protocol-session.js";
|
||||
import {
|
||||
buildOmpLaunch,
|
||||
@@ -149,13 +144,10 @@ class OmpCliRuntimeSession implements OmpRuntimeSession {
|
||||
}
|
||||
|
||||
async compact(customInstructions?: string): Promise<void> {
|
||||
await this.request(
|
||||
{
|
||||
type: "compact",
|
||||
...(customInstructions ? { customInstructions } : {}),
|
||||
},
|
||||
JSONL_RPC_NO_TIMEOUT,
|
||||
);
|
||||
await this.request({
|
||||
type: "compact",
|
||||
...(customInstructions ? { customInstructions } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
async setAutoCompaction(enabled: boolean): Promise<void> {
|
||||
@@ -170,11 +162,6 @@ class OmpCliRuntimeSession implements OmpRuntimeSession {
|
||||
return OmpSessionStateSchema.parse(await this.request({ type: "get_state" }));
|
||||
}
|
||||
|
||||
async setFastMode(enabled: boolean): Promise<{ enabled: boolean; active: boolean }> {
|
||||
const result = await this.request({ type: "set_fast_mode", enabled });
|
||||
return z.object({ enabled: z.boolean(), active: z.boolean() }).parse(result);
|
||||
}
|
||||
|
||||
async getMessages(): Promise<OmpAgentMessage[]> {
|
||||
const data = OmpMessagesResultSchema.parse(await this.request({ type: "get_messages" }));
|
||||
return data.messages ?? [];
|
||||
@@ -268,11 +255,8 @@ class OmpCliRuntimeSession implements OmpRuntimeSession {
|
||||
return data.messages ?? [];
|
||||
}
|
||||
|
||||
async steer(
|
||||
message: string,
|
||||
images?: Array<{ type: "image"; data: string; mimeType: string }>,
|
||||
): Promise<void> {
|
||||
await this.request({ type: "steer", message, ...(images?.length ? { images } : {}) });
|
||||
steer(message: string, images?: Array<{ type: "image"; data: string; mimeType: string }>): void {
|
||||
this.process.send({ type: "steer", message, ...(images?.length ? { images } : {}) });
|
||||
}
|
||||
|
||||
followUp(
|
||||
|
||||
@@ -5,30 +5,3 @@ type OmpCustomMessage = Extract<OmpAgentMessage, { role: "custom" }>;
|
||||
export function shouldDisplayOmpCustomMessage(message: OmpCustomMessage): boolean {
|
||||
return Reflect.get(message, "display") !== false;
|
||||
}
|
||||
|
||||
// injected rows need their own message id so the stream coalescer never glues them
|
||||
// onto the assistant reply they arrive next to
|
||||
export function ompCustomMessageId(message: OmpCustomMessage, nextIndex: () => number): string {
|
||||
const id = Reflect.get(message, "id");
|
||||
return `omp-custom-${typeof id === "string" && id ? id : nextIndex()}`;
|
||||
}
|
||||
|
||||
// omp does not persist the typed /skill:<name> as a user message, only the expansion
|
||||
// it injected on the user's behalf; rebuild the bubble from the expansion's details
|
||||
export function ompSkillPromptUserText(message: OmpCustomMessage): string | null {
|
||||
if (
|
||||
Reflect.get(message, "customType") !== "skill-prompt" ||
|
||||
Reflect.get(message, "attribution") !== "user"
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const details = Reflect.get(message, "details");
|
||||
const name = details && typeof details === "object" ? Reflect.get(details, "name") : undefined;
|
||||
if (typeof name !== "string" || !name) {
|
||||
return null;
|
||||
}
|
||||
const args = Reflect.get(details as object, "args");
|
||||
return typeof args === "string" && args.trim()
|
||||
? `/skill:${name} ${args.trim()}`
|
||||
: `/skill:${name}`;
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import { streamOmpCoreHistory, type OmpCapturedUserMessageEntry } from "./messag
|
||||
import type { OmpAgentMessage } from "./rpc-types.js";
|
||||
import { FakeOmp } from "./test-utils/fake-omp.js";
|
||||
import { OMP_HISTORY_MAPPER_HOOKS } from "./history-hooks.js";
|
||||
import { readOmpHistoryTodoState, streamOmpHistory } from "./history.js";
|
||||
import { streamOmpHistory } from "./history.js";
|
||||
|
||||
async function collectHistory(
|
||||
messages: OmpAgentMessage[],
|
||||
@@ -27,117 +27,6 @@ async function collectHistory(
|
||||
}
|
||||
|
||||
describe("OMP history mapper", () => {
|
||||
test("replays a web search details error as failed when OMP sets isError false", async () => {
|
||||
const events = await collectHistory([
|
||||
{
|
||||
role: "assistant",
|
||||
content: [
|
||||
{ type: "toolCall", id: "web-1", name: "web_search", arguments: { query: "Paseo" } },
|
||||
],
|
||||
},
|
||||
{
|
||||
role: "toolResult",
|
||||
toolCallId: "web-1",
|
||||
toolName: "web_search",
|
||||
content: [{ type: "text", text: "Error: All web search providers failed" }],
|
||||
details: {
|
||||
error: "All web search providers failed",
|
||||
response: { provider: "none", sources: [] },
|
||||
},
|
||||
isError: false,
|
||||
},
|
||||
]);
|
||||
expect(events.at(-1)?.item).toMatchObject({
|
||||
type: "tool_call",
|
||||
status: "failed",
|
||||
error: "All web search providers failed",
|
||||
});
|
||||
});
|
||||
|
||||
test("restores blocked and abandoned todo state from a session file", async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "omp-todo-state-history-"));
|
||||
const sessionFile = join(dir, "session.jsonl");
|
||||
writeFileSync(
|
||||
sessionFile,
|
||||
[
|
||||
{ type: "session", id: "root" },
|
||||
{
|
||||
type: "message",
|
||||
id: "todos",
|
||||
parentId: "root",
|
||||
message: {
|
||||
role: "toolResult",
|
||||
toolName: "todo",
|
||||
details: {
|
||||
phases: [
|
||||
{
|
||||
name: "Tasks",
|
||||
tasks: [
|
||||
{ content: "Wait for approval", status: "blocked", blocker: "review" },
|
||||
{ content: "Old route", status: "abandoned" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
]
|
||||
.map((entry) => JSON.stringify(entry))
|
||||
.join("\n"),
|
||||
);
|
||||
expect(await readOmpHistoryTodoState(sessionFile)).toEqual({
|
||||
type: "todo",
|
||||
items: [{ text: "Wait for approval (blocked: review)", status: "pending", completed: false }],
|
||||
});
|
||||
});
|
||||
|
||||
test("hides persisted developer reminders and shows other developer messages", async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "omp-developer-history-"));
|
||||
const sessionFile = join(dir, "session.jsonl");
|
||||
writeFileSync(
|
||||
sessionFile,
|
||||
[
|
||||
{ type: "session", id: "root" },
|
||||
{
|
||||
type: "message",
|
||||
id: "reminder",
|
||||
parentId: "root",
|
||||
message: {
|
||||
role: "developer",
|
||||
attribution: "agent",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "<system-reminder>\nContinue unfinished tasks\n</system-reminder>",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "message",
|
||||
id: "other",
|
||||
parentId: "reminder",
|
||||
message: {
|
||||
role: "developer",
|
||||
content: [{ type: "text", text: "External instruction" }],
|
||||
},
|
||||
},
|
||||
]
|
||||
.map((entry) => JSON.stringify(entry))
|
||||
.join("\n"),
|
||||
);
|
||||
const events: AgentStreamEvent[] = [];
|
||||
for await (const event of streamOmpHistory({ sessionFile, provider: "omp" }))
|
||||
events.push(event);
|
||||
expect(events.map((event) => event.item)).toEqual([
|
||||
{
|
||||
type: "assistant_message",
|
||||
text: "[developer] External instruction",
|
||||
messageId: "omp-custom-1",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("coalesces replayed subagent poll calls by target set", async () => {
|
||||
const events = await collectHistory([
|
||||
{
|
||||
@@ -334,20 +223,12 @@ describe("OMP history mapper", () => {
|
||||
{
|
||||
type: "timeline",
|
||||
provider: "omp",
|
||||
item: {
|
||||
type: "assistant_message",
|
||||
text: "visible explicit custom",
|
||||
messageId: "omp-custom-1",
|
||||
},
|
||||
item: { type: "assistant_message", text: "visible explicit custom" },
|
||||
},
|
||||
{
|
||||
type: "timeline",
|
||||
provider: "omp",
|
||||
item: {
|
||||
type: "assistant_message",
|
||||
text: "visible legacy custom",
|
||||
messageId: "omp-custom-2",
|
||||
},
|
||||
item: { type: "assistant_message", text: "visible legacy custom" },
|
||||
},
|
||||
{
|
||||
type: "timeline",
|
||||
@@ -485,17 +366,6 @@ describe("OMP history mapper", () => {
|
||||
},
|
||||
},
|
||||
});
|
||||
// The running row must share the completed row's detail type, or the timeline merge keeps
|
||||
// the running detail and drops the result.
|
||||
expect(
|
||||
events.flatMap((event) =>
|
||||
event.type === "timeline" &&
|
||||
event.item.type === "tool_call" &&
|
||||
event.item.callId === "xd-write-call"
|
||||
? [event.item.detail.type]
|
||||
: [],
|
||||
),
|
||||
).toEqual(["plain_text", "unknown"]);
|
||||
});
|
||||
|
||||
test("maps only the active JSONL chain with native user ids and visible unknown roles", async () => {
|
||||
@@ -577,12 +447,8 @@ describe("OMP history mapper", () => {
|
||||
}
|
||||
expect(events.map((event) => event.item)).toEqual([
|
||||
{ type: "user_message", text: "active branch", messageId: "user-active" },
|
||||
{
|
||||
type: "assistant_message",
|
||||
text: "[future_control] Unsupported history record",
|
||||
messageId: "omp-custom-1",
|
||||
},
|
||||
{ type: "assistant_message", text: "[developer] developer note", messageId: "omp-custom-2" },
|
||||
{ type: "assistant_message", text: "[future_control] Unsupported history record" },
|
||||
{ type: "assistant_message", text: "[developer] developer note" },
|
||||
]);
|
||||
|
||||
const omp = new FakeOmp();
|
||||
@@ -608,163 +474,6 @@ describe("OMP history mapper", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
test("maps omp 18.1 custom_message entries like live custom messages", async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "omp-custom-message-history-"));
|
||||
const sessionFile = join(dir, "session.jsonl");
|
||||
const skillPrompt =
|
||||
'[IMPORTANT: User invoked the "commit" skill; follow its instructions. Full skill below.]\n\n# Commit';
|
||||
const ircMessage = "<irc>\n<from>worker-1</from>\n<message>ready for review</message>\n</irc>";
|
||||
writeFileSync(
|
||||
sessionFile,
|
||||
[
|
||||
{ type: "session", id: "root", parentId: null },
|
||||
{
|
||||
type: "message",
|
||||
id: "answer-1",
|
||||
parentId: "root",
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: [{ type: "text", text: "Done." }],
|
||||
responseId: "resp-1",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "custom_message",
|
||||
customType: "skill-prompt",
|
||||
content: skillPrompt,
|
||||
display: true,
|
||||
details: {
|
||||
name: "commit",
|
||||
path: "/home/me/.agents/skills/commit/SKILL.md",
|
||||
lineCount: 12,
|
||||
},
|
||||
attribution: "user",
|
||||
id: "skill-1",
|
||||
parentId: "answer-1",
|
||||
timestamp: "2026-09-13T13:11:35.811Z",
|
||||
},
|
||||
{
|
||||
type: "custom_message",
|
||||
customType: "irc:incoming",
|
||||
content: ircMessage,
|
||||
display: true,
|
||||
details: { from: "worker-1", message: "ready for review" },
|
||||
attribution: "user",
|
||||
id: "irc-1",
|
||||
parentId: "skill-1",
|
||||
timestamp: "2026-09-13T13:11:36.811Z",
|
||||
},
|
||||
{
|
||||
type: "custom_message",
|
||||
customType: "hidden-reminder",
|
||||
content: "must stay hidden",
|
||||
display: false,
|
||||
attribution: "user",
|
||||
id: "hidden-1",
|
||||
parentId: "irc-1",
|
||||
timestamp: "2026-09-13T13:11:37.811Z",
|
||||
},
|
||||
{
|
||||
type: "custom_message",
|
||||
customType: "legacy-no-display",
|
||||
content: "visible without display flag",
|
||||
attribution: "user",
|
||||
id: "legacy-1",
|
||||
parentId: "hidden-1",
|
||||
timestamp: "2026-09-13T13:11:38.811Z",
|
||||
},
|
||||
]
|
||||
.map((entry) => JSON.stringify(entry))
|
||||
.join("\n"),
|
||||
);
|
||||
|
||||
const events: AgentStreamEvent[] = [];
|
||||
for await (const event of streamOmpHistory({ sessionFile, provider: "omp" })) {
|
||||
events.push(event);
|
||||
}
|
||||
expect(events.map((event) => event.item)).toEqual([
|
||||
{ type: "assistant_message", text: "Done.", messageId: "resp-1" },
|
||||
{ type: "user_message", text: "/skill:commit", messageId: "omp-custom-skill-1-user" },
|
||||
{ type: "assistant_message", text: ircMessage, messageId: "omp-custom-irc-1" },
|
||||
{
|
||||
type: "assistant_message",
|
||||
text: "visible without display flag",
|
||||
messageId: "omp-custom-legacy-1",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("synthesises the typed /skill bubble only for user-attributed skill prompts", async () => {
|
||||
await expect(
|
||||
collectHistory([
|
||||
{
|
||||
role: "custom",
|
||||
content: '[IMPORTANT: User invoked the "improve" skill; follow its instructions.]',
|
||||
customType: "skill-prompt",
|
||||
display: true,
|
||||
details: {
|
||||
name: "improve",
|
||||
path: "/home/me/.agents/skills/improve/SKILL.md",
|
||||
lineCount: 9,
|
||||
args: "tests",
|
||||
},
|
||||
attribution: "user",
|
||||
id: "skill-args",
|
||||
},
|
||||
{
|
||||
role: "custom",
|
||||
content: '[IMPORTANT: Agent invoked the "improve" skill.]',
|
||||
customType: "skill-prompt",
|
||||
display: true,
|
||||
details: {
|
||||
name: "improve",
|
||||
path: "/home/me/.agents/skills/improve/SKILL.md",
|
||||
lineCount: 9,
|
||||
},
|
||||
attribution: "agent",
|
||||
id: "skill-agent",
|
||||
},
|
||||
{
|
||||
role: "custom",
|
||||
content: "<irc>\n<from>worker-1</from>\n<message>hi</message>\n</irc>",
|
||||
customType: "irc:incoming",
|
||||
display: true,
|
||||
details: { from: "worker-1", message: "hi" },
|
||||
attribution: "user",
|
||||
id: "irc-user",
|
||||
},
|
||||
]),
|
||||
).resolves.toEqual([
|
||||
{
|
||||
type: "timeline",
|
||||
provider: "omp",
|
||||
item: {
|
||||
type: "user_message",
|
||||
text: "/skill:improve tests",
|
||||
messageId: "omp-custom-skill-args-user",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "timeline",
|
||||
provider: "omp",
|
||||
item: {
|
||||
type: "assistant_message",
|
||||
text: '[IMPORTANT: Agent invoked the "improve" skill.]',
|
||||
messageId: "omp-custom-skill-agent",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "timeline",
|
||||
provider: "omp",
|
||||
item: {
|
||||
type: "assistant_message",
|
||||
text: "<irc>\n<from>worker-1</from>\n<message>hi</message>\n</irc>",
|
||||
messageId: "omp-custom-irc-user",
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("rehydrates structured batch and nested task transcripts with stable status and time", async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "omp-subagent-history-"));
|
||||
const parentFile = join(dir, "parent.jsonl");
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { basename, extname, join } from "node:path";
|
||||
import type { AgentProvider, AgentStreamEvent, AgentTimelineItem } from "../../agent-sdk-types.js";
|
||||
import type { AgentProvider, AgentStreamEvent } from "../../agent-sdk-types.js";
|
||||
import { normalizeProviderReplayTimestamp } from "../../provider-history-timestamps.js";
|
||||
import { OmpHistoryMapper, type OmpCapturedUserMessageEntry } from "./message-history.js";
|
||||
import type { OmpAgentMessage } from "./rpc-types.js";
|
||||
import type { OmpRuntimeSession } from "./runtime.js";
|
||||
import { OMP_HISTORY_MAPPER_HOOKS } from "./history-hooks.js";
|
||||
import type { OmpBridgedToolIdentity } from "./mcp-bridge.js";
|
||||
import { formatOmpSubagentTitle } from "./subagent-title.js";
|
||||
import { mapOmpTodoPhases } from "./todo-mapper.js";
|
||||
import { OmpTodoPhaseSchema } from "./rpc-types.js";
|
||||
|
||||
interface OmpSessionEntry {
|
||||
type?: string;
|
||||
@@ -20,24 +17,6 @@ interface OmpSessionEntry {
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export async function readOmpHistoryTodoState(
|
||||
sessionFile: string,
|
||||
): Promise<AgentTimelineItem | null> {
|
||||
const entries = await readActiveOmpEntryChain(sessionFile).catch((error: unknown) => {
|
||||
if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
|
||||
throw error;
|
||||
});
|
||||
for (let index = entries.length - 1; index >= 0; index -= 1) {
|
||||
const message = entries[index]?.message;
|
||||
if (message?.role !== "toolResult" || message.toolName !== "todo") continue;
|
||||
const details = message.details;
|
||||
if (!details || typeof details !== "object") return null;
|
||||
const phases = OmpTodoPhaseSchema.array().safeParse(Reflect.get(details, "phases"));
|
||||
return phases.success ? mapOmpTodoPhases(phases.data) : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function extractOmpSubagentModel(entries: readonly OmpSessionEntry[]): string | null {
|
||||
let resolvedModel: string | null = null;
|
||||
for (const entry of entries) {
|
||||
@@ -66,7 +45,6 @@ export async function* streamOmpHistory(input: {
|
||||
sessionFile?: string;
|
||||
runtimeSession?: OmpRuntimeSession;
|
||||
provider: AgentProvider;
|
||||
bridgedTools?: ReadonlyMap<string, OmpBridgedToolIdentity>;
|
||||
visitedSessionFiles?: Set<string>;
|
||||
}): AsyncGenerator<AgentStreamEvent> {
|
||||
if (!input.sessionFile) {
|
||||
@@ -101,12 +79,7 @@ export async function* streamOmpHistory(input: {
|
||||
userEntries.push({ id: entry.id, text: textOf(mapped.content) });
|
||||
}
|
||||
}
|
||||
const mapper = new OmpHistoryMapper(
|
||||
input.provider,
|
||||
userEntries,
|
||||
OMP_HISTORY_MAPPER_HOOKS,
|
||||
input.bridgedTools,
|
||||
);
|
||||
const mapper = new OmpHistoryMapper(input.provider, userEntries, OMP_HISTORY_MAPPER_HOOKS);
|
||||
for (let index = 0; index < messages.length; index += 1) {
|
||||
const timestamp = normalizeProviderReplayTimestamp(messageEntries[index]?.timestamp);
|
||||
for (const event of mapper.mapMessages([messages[index]!])) {
|
||||
@@ -353,52 +326,17 @@ function mapEntryMessage(entry: OmpSessionEntry): OmpAgentMessage | null {
|
||||
if (message.role === "system") {
|
||||
return null;
|
||||
}
|
||||
if (message.role === "developer") {
|
||||
const content = message.content;
|
||||
if (
|
||||
Array.isArray(content) &&
|
||||
content.length === 1 &&
|
||||
content[0]?.type === "text" &&
|
||||
typeof content[0].text === "string" &&
|
||||
content[0].text.trimStart().startsWith("<system-reminder>") &&
|
||||
content[0].text.trimEnd().endsWith("</system-reminder>")
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return visibleFallback(message.role, message);
|
||||
}
|
||||
if (["user", "assistant", "toolResult", "custom", "bashExecution"].includes(message.role)) {
|
||||
return message as unknown as OmpAgentMessage;
|
||||
}
|
||||
return visibleFallback(message.role, message);
|
||||
}
|
||||
if (entry.type === "custom_message") {
|
||||
return mapCustomMessageEntry(entry);
|
||||
}
|
||||
if (!entry.type || isControlEntryType(entry.type)) {
|
||||
return null;
|
||||
}
|
||||
return visibleFallback(entry.type, entry);
|
||||
}
|
||||
|
||||
// omp 18.1+ persists injected rows (skill prompts, hub messages, job notices) as top-level
|
||||
// custom_message entries without a message object; replay them as live custom messages
|
||||
function mapCustomMessageEntry(entry: OmpSessionEntry): OmpAgentMessage | null {
|
||||
const content = entry.content;
|
||||
if (typeof content !== "string" && !Array.isArray(content)) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
role: "custom",
|
||||
content,
|
||||
id: entry.id,
|
||||
customType: entry.customType,
|
||||
display: entry.display,
|
||||
details: entry.details,
|
||||
attribution: entry.attribution,
|
||||
} as OmpAgentMessage;
|
||||
}
|
||||
|
||||
function isControlEntryType(type: string): boolean {
|
||||
return (
|
||||
type === "session" ||
|
||||
@@ -419,8 +357,6 @@ function visibleFallback(role: string, value: Record<string, unknown>): OmpAgent
|
||||
let text = "Unsupported history record";
|
||||
if (typeof value.content === "string") {
|
||||
text = value.content;
|
||||
} else if (Array.isArray(value.content)) {
|
||||
text = textOf(value.content) || text;
|
||||
} else if (typeof value.text === "string") {
|
||||
text = value.text;
|
||||
}
|
||||
|
||||
@@ -4,9 +4,10 @@ import { z } from "zod";
|
||||
|
||||
import type { PaseoToolCatalog, PaseoToolDefinition, PaseoToolResult } from "../../tools/types.js";
|
||||
import {
|
||||
clearOmpHostToolState,
|
||||
handleOmpHostToolRuntimeEvent,
|
||||
OmpHostToolRouter,
|
||||
serializeOmpHostTools,
|
||||
waitForOmpHostToolsIdle,
|
||||
} from "./host-tools.js";
|
||||
import type { OmpRpcHostToolResult } from "./rpc-types.js";
|
||||
import { FakeOmp } from "./test-utils/fake-omp.js";
|
||||
@@ -32,14 +33,11 @@ class OmpHostToolHarness {
|
||||
private readonly controlledStart = new Promise<void>((resolve) => {
|
||||
this.resolveControlledStart = resolve;
|
||||
});
|
||||
private readonly router: OmpHostToolRouter;
|
||||
|
||||
private constructor(
|
||||
private readonly catalog: PaseoToolCatalog,
|
||||
private readonly runtimeSession: Awaited<ReturnType<FakeOmp["startSession"]>>,
|
||||
) {
|
||||
this.router = new OmpHostToolRouter({ runtimeSession, catalog, logger: this.logger });
|
||||
}
|
||||
) {}
|
||||
|
||||
static async withTools(tools: PaseoToolDefinition[]): Promise<OmpHostToolHarness> {
|
||||
const omp = new FakeOmp();
|
||||
@@ -71,12 +69,7 @@ class OmpHostToolHarness {
|
||||
arguments: Record<string, unknown>;
|
||||
}): Promise<OmpRpcHostToolResult> {
|
||||
const result = this.runtimeSession.nextHostToolResult();
|
||||
handleOmpHostToolRuntimeEvent(
|
||||
{ type: "host_tool_call", ...input },
|
||||
this.router,
|
||||
this.runtimeSession,
|
||||
this.logger,
|
||||
);
|
||||
handleOmpHostToolRuntimeEvent({ type: "host_tool_call", ...input }, this.routerInput());
|
||||
return await result;
|
||||
}
|
||||
|
||||
@@ -89,9 +82,7 @@ class OmpHostToolHarness {
|
||||
toolName: "wait_for_agent",
|
||||
arguments: { agentId: "child-1" },
|
||||
},
|
||||
this.router,
|
||||
this.runtimeSession,
|
||||
this.logger,
|
||||
this.routerInput(),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -102,9 +93,7 @@ class OmpHostToolHarness {
|
||||
cancelControlledCall(): void {
|
||||
handleOmpHostToolRuntimeEvent(
|
||||
{ type: "host_tool_cancel", id: "cancel-1", targetId: "host-cancel" },
|
||||
this.router,
|
||||
this.runtimeSession,
|
||||
this.logger,
|
||||
this.routerInput(),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -114,7 +103,7 @@ class OmpHostToolHarness {
|
||||
}
|
||||
|
||||
async waitForIdle(): Promise<void> {
|
||||
await this.router.waitForIdle();
|
||||
await waitForOmpHostToolsIdle(this.runtimeSession);
|
||||
}
|
||||
|
||||
wasControlledCallAborted(): boolean {
|
||||
@@ -130,7 +119,11 @@ class OmpHostToolHarness {
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.router.clear();
|
||||
clearOmpHostToolState(this.runtimeSession);
|
||||
}
|
||||
|
||||
private routerInput() {
|
||||
return { runtimeSession: this.runtimeSession, paseoTools: this.catalog, logger: this.logger };
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
} from "../../tools/paseo-tool-serialization.js";
|
||||
import type { PaseoToolCatalog, PaseoToolResult } from "../../tools/types.js";
|
||||
import type { OmpRuntimeSession } from "./runtime.js";
|
||||
import type { OmpMcpBridge } from "./mcp-bridge.js";
|
||||
import {
|
||||
OmpRpcHostToolCallRequestSchema,
|
||||
OmpRpcHostToolCancelRequestSchema,
|
||||
@@ -25,11 +24,12 @@ interface PendingOmpHostToolCall {
|
||||
|
||||
interface OmpHostToolRouterInput {
|
||||
runtimeSession: OmpRuntimeSession;
|
||||
catalog?: PaseoToolCatalog;
|
||||
bridge?: OmpMcpBridge;
|
||||
catalog: PaseoToolCatalog;
|
||||
logger: Logger;
|
||||
}
|
||||
|
||||
const routersByRuntimeSession = new WeakMap<OmpRuntimeSession, OmpHostToolRouter>();
|
||||
|
||||
export function serializeOmpHostTools(catalog: PaseoToolCatalog): OmpRpcHostToolDefinition[] {
|
||||
return [...catalog.tools.values()].map((tool) => {
|
||||
const definition: OmpRpcHostToolDefinition = {
|
||||
@@ -45,11 +45,20 @@ export function serializeOmpHostTools(catalog: PaseoToolCatalog): OmpRpcHostTool
|
||||
});
|
||||
}
|
||||
|
||||
export async function setOmpHostTools(
|
||||
runtimeSession: OmpRuntimeSession,
|
||||
catalog: PaseoToolCatalog,
|
||||
): Promise<string[]> {
|
||||
return await runtimeSession.setHostTools(serializeOmpHostTools(catalog));
|
||||
}
|
||||
|
||||
export function handleOmpHostToolRuntimeEvent(
|
||||
event: unknown,
|
||||
router: OmpHostToolRouter | undefined,
|
||||
runtimeSession: OmpRuntimeSession,
|
||||
logger: Logger,
|
||||
input: {
|
||||
runtimeSession: OmpRuntimeSession;
|
||||
paseoTools?: PaseoToolCatalog;
|
||||
logger: Logger;
|
||||
},
|
||||
): boolean {
|
||||
if (!isRecord(event) || typeof event.type !== "string" || !isOmpHostToolEventType(event.type)) {
|
||||
return false;
|
||||
@@ -57,8 +66,9 @@ export function handleOmpHostToolRuntimeEvent(
|
||||
|
||||
const call = OmpRpcHostToolCallRequestSchema.safeParse(event);
|
||||
if (call.success) {
|
||||
const router = getRouter(input);
|
||||
if (!router) {
|
||||
sendMissingCatalogResult(runtimeSession, call.data);
|
||||
sendMissingCatalogResult(input.runtimeSession, call.data);
|
||||
return true;
|
||||
}
|
||||
router.handleCall(call.data);
|
||||
@@ -67,17 +77,17 @@ export function handleOmpHostToolRuntimeEvent(
|
||||
|
||||
const cancel = OmpRpcHostToolCancelRequestSchema.safeParse(event);
|
||||
if (cancel.success) {
|
||||
router?.handleCancel(cancel.data.targetId);
|
||||
getRouter(input)?.handleCancel(cancel.data.targetId);
|
||||
return true;
|
||||
}
|
||||
|
||||
const update = OmpRpcHostToolUpdateSchema.safeParse(event);
|
||||
if (update.success) {
|
||||
logger.debug({ id: update.data.id }, "Ignoring unexpected inbound OMP host tool update");
|
||||
input.logger.debug({ id: update.data.id }, "Ignoring unexpected inbound OMP host tool update");
|
||||
return true;
|
||||
}
|
||||
|
||||
logger.debug({ event }, "Dropped malformed OMP host tool frame");
|
||||
input.logger.debug({ event }, "Dropped malformed OMP host tool frame");
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -85,6 +95,36 @@ function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
export function clearOmpHostToolState(runtimeSession: OmpRuntimeSession): void {
|
||||
routersByRuntimeSession.get(runtimeSession)?.clear();
|
||||
routersByRuntimeSession.delete(runtimeSession);
|
||||
}
|
||||
|
||||
export async function waitForOmpHostToolsIdle(runtimeSession: OmpRuntimeSession): Promise<void> {
|
||||
await routersByRuntimeSession.get(runtimeSession)?.waitForIdle();
|
||||
}
|
||||
|
||||
function getRouter(input: {
|
||||
runtimeSession: OmpRuntimeSession;
|
||||
paseoTools?: PaseoToolCatalog;
|
||||
logger: Logger;
|
||||
}): OmpHostToolRouter | null {
|
||||
if (!input.paseoTools) {
|
||||
return null;
|
||||
}
|
||||
const existing = routersByRuntimeSession.get(input.runtimeSession);
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
const router = new OmpHostToolRouter({
|
||||
runtimeSession: input.runtimeSession,
|
||||
catalog: input.paseoTools,
|
||||
logger: input.logger,
|
||||
});
|
||||
routersByRuntimeSession.set(input.runtimeSession, router);
|
||||
return router;
|
||||
}
|
||||
|
||||
function sendMissingCatalogResult(
|
||||
runtimeSession: OmpRuntimeSession,
|
||||
request: OmpRpcHostToolCallRequest,
|
||||
@@ -101,10 +141,9 @@ function isOmpHostToolEventType(type: string): boolean {
|
||||
return type === "host_tool_call" || type === "host_tool_cancel" || type === "host_tool_update";
|
||||
}
|
||||
|
||||
export class OmpHostToolRouter {
|
||||
class OmpHostToolRouter {
|
||||
private readonly runtimeSession: OmpRuntimeSession;
|
||||
private readonly catalog?: PaseoToolCatalog;
|
||||
readonly bridge?: OmpMcpBridge;
|
||||
private readonly catalog: PaseoToolCatalog;
|
||||
private readonly logger: Logger;
|
||||
private readonly pendingCalls = new Map<string, PendingOmpHostToolCall>();
|
||||
private readonly idleWaiters = new Set<() => void>();
|
||||
@@ -112,17 +151,9 @@ export class OmpHostToolRouter {
|
||||
constructor(input: OmpHostToolRouterInput) {
|
||||
this.runtimeSession = input.runtimeSession;
|
||||
this.catalog = input.catalog;
|
||||
this.bridge = input.bridge;
|
||||
this.logger = input.logger;
|
||||
}
|
||||
|
||||
async register(): Promise<string[]> {
|
||||
return await this.runtimeSession.setHostTools([
|
||||
...(this.catalog ? serializeOmpHostTools(this.catalog) : []),
|
||||
...(this.bridge?.definitions ?? []),
|
||||
]);
|
||||
}
|
||||
|
||||
handleCall(request: OmpRpcHostToolCallRequest): void {
|
||||
const entry: PendingOmpHostToolCall = {
|
||||
controller: new AbortController(),
|
||||
@@ -152,11 +183,6 @@ export class OmpHostToolRouter {
|
||||
this.resolveIdleWaiters();
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
this.clear();
|
||||
await this.bridge?.close();
|
||||
}
|
||||
|
||||
waitForIdle(): Promise<void> {
|
||||
if (this.pendingCalls.size === 0) return Promise.resolve();
|
||||
return new Promise((resolve) => this.idleWaiters.add(resolve));
|
||||
@@ -167,20 +193,15 @@ export class OmpHostToolRouter {
|
||||
entry: PendingOmpHostToolCall,
|
||||
): Promise<void> {
|
||||
try {
|
||||
const result = this.bridge?.tool(request.toolName)
|
||||
? await this.bridge.execute(request.toolName, request.arguments, entry.controller.signal)
|
||||
: ((await this.catalog?.executeTool(request.toolName, request.arguments, {
|
||||
signal: entry.controller.signal,
|
||||
sendUpdate: (update) => {
|
||||
if (entry.canceled || entry.controller.signal.aborted) {
|
||||
return;
|
||||
}
|
||||
this.sendUpdate(request.id, update);
|
||||
},
|
||||
})) ?? {
|
||||
content: [{ type: "text", text: `Unknown host tool: ${request.toolName}` }],
|
||||
isError: true,
|
||||
});
|
||||
const result = await this.catalog.executeTool(request.toolName, request.arguments, {
|
||||
signal: entry.controller.signal,
|
||||
sendUpdate: (update) => {
|
||||
if (entry.canceled || entry.controller.signal.aborted) {
|
||||
return;
|
||||
}
|
||||
this.sendUpdate(request.id, update);
|
||||
},
|
||||
});
|
||||
if (entry.canceled || entry.controller.signal.aborted) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ describe("mapOmpModel thinking options", () => {
|
||||
|
||||
const result = mapOmpModel(model, "omp");
|
||||
|
||||
expect(result.thinkingOptions?.map((option) => option.id)).toEqual(["auto", "high", "xhigh"]);
|
||||
expect(result.thinkingOptions?.map((option) => option.id)).toEqual(["high", "xhigh"]);
|
||||
expect(result.defaultThinkingOptionId).toBe("xhigh");
|
||||
expect(result.thinkingOptions?.find((option) => option.isDefault)?.id).toBe("xhigh");
|
||||
});
|
||||
@@ -37,7 +37,6 @@ describe("mapOmpModel thinking options", () => {
|
||||
const result = mapOmpModel(model, "omp");
|
||||
|
||||
expect(result.thinkingOptions?.map((option) => option.id)).toEqual([
|
||||
"auto",
|
||||
"off",
|
||||
"minimal",
|
||||
"low",
|
||||
@@ -58,7 +57,6 @@ describe("mapOmpModel thinking options", () => {
|
||||
const result = mapOmpModel(model, "omp");
|
||||
|
||||
expect(result.thinkingOptions?.map((option) => option.id)).toEqual([
|
||||
"auto",
|
||||
"off",
|
||||
"minimal",
|
||||
"low",
|
||||
@@ -95,7 +93,7 @@ describe("mapOmpModel thinking options", () => {
|
||||
|
||||
const result = mapOmpModel(model, "omp");
|
||||
|
||||
expect(result.thinkingOptions?.map((option) => option.id)).toEqual(["auto", "low", "high"]);
|
||||
expect(result.thinkingOptions?.map((option) => option.id)).toEqual(["low", "high"]);
|
||||
expect(result.defaultThinkingOptionId).toBe("low");
|
||||
expect(result.thinkingOptions?.find((option) => option.isDefault)?.id).toBe("low");
|
||||
});
|
||||
@@ -108,12 +106,7 @@ describe("mapOmpModel thinking options", () => {
|
||||
|
||||
const result = mapOmpModel(model, "omp");
|
||||
|
||||
expect(result.thinkingOptions?.map((option) => option.id)).toEqual([
|
||||
"auto",
|
||||
"low",
|
||||
"medium",
|
||||
"high",
|
||||
]);
|
||||
expect(result.thinkingOptions?.map((option) => option.id)).toEqual(["low", "medium", "high"]);
|
||||
expect(result.defaultThinkingOptionId).toBe("low");
|
||||
});
|
||||
|
||||
@@ -126,7 +119,6 @@ describe("mapOmpModel thinking options", () => {
|
||||
const result = mapOmpModel(model, "omp");
|
||||
|
||||
expect(result.thinkingOptions?.map((option) => option.id)).toEqual([
|
||||
"auto",
|
||||
"off",
|
||||
"minimal",
|
||||
"low",
|
||||
@@ -138,22 +130,6 @@ describe("mapOmpModel thinking options", () => {
|
||||
expect(result.defaultThinkingOptionId).toBe("medium");
|
||||
});
|
||||
|
||||
test("offers auto alongside reported efforts without making it the default", () => {
|
||||
const model = baseModel({
|
||||
reasoning: true,
|
||||
thinking: { mode: "effort", efforts: ["low", "high"], defaultLevel: "high" },
|
||||
});
|
||||
|
||||
const result = mapOmpModel(model, "omp");
|
||||
|
||||
expect(result.thinkingOptions?.at(0)).toEqual({
|
||||
id: "auto",
|
||||
label: "Auto",
|
||||
description: "OMP picks the effort each turn",
|
||||
});
|
||||
expect(result.defaultThinkingOptionId).toBe("high");
|
||||
});
|
||||
|
||||
test("preserves provider and model id in the mapped definition", () => {
|
||||
const model = baseModel({
|
||||
reasoning: true,
|
||||
|
||||
@@ -13,7 +13,6 @@ export const OMP_THINKING_OPTIONS: ReadonlyArray<{
|
||||
description: string;
|
||||
isDefault?: boolean;
|
||||
}> = [
|
||||
{ id: "auto", label: "Auto", description: "OMP picks the effort each turn" },
|
||||
{ id: "off", label: "Off", description: "No extra reasoning" },
|
||||
{ id: "minimal", label: "Minimal", description: "Light reasoning" },
|
||||
{ id: "low", label: "Low", description: "Faster reasoning" },
|
||||
@@ -83,10 +82,8 @@ function resolveOmpThinkingConfig(model: OmpModel): {
|
||||
reportedDefault && filtered.some((option) => option.id === reportedDefault)
|
||||
? reportedDefault
|
||||
: (filtered[0]?.id ?? DEFAULT_OMP_THINKING_LEVEL);
|
||||
// `auto` is a session-level OMP mode, never a per-model effort, so models do not list it.
|
||||
const options = [OMP_THINKING_OPTIONS[0], ...filtered.filter((option) => option.id !== "auto")];
|
||||
return {
|
||||
thinkingOptions: options.map((option) =>
|
||||
thinkingOptions: filtered.map((option) =>
|
||||
mapThinkingOption(option, option.id === defaultThinkingOptionId),
|
||||
),
|
||||
defaultThinkingOptionId,
|
||||
|
||||
@@ -1,340 +0,0 @@
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, test, vi } from "vitest";
|
||||
import { OmpHarness } from "./test-utils/omp-harness.js";
|
||||
import type { PaseoToolCatalog } from "../../tools/types.js";
|
||||
|
||||
const fixture = fileURLToPath(new URL("./test-utils/echo-mcp-server.mjs", import.meta.url));
|
||||
const healthy = { type: "stdio" as const, command: process.execPath, args: [fixture] };
|
||||
|
||||
describe("OMP MCP host tools", () => {
|
||||
test("registers a stdio MCP tool and proxies its call", async () => {
|
||||
await mkdir("/tmp/paseo-omp-agent-test", { recursive: true });
|
||||
const omp = new OmpHarness();
|
||||
await omp.start({ mcpServers: { local: healthy } });
|
||||
try {
|
||||
const tool = omp.registeredHostTools().at(-1)?.[0];
|
||||
expect(tool?.name).toMatch(/^mcp_local__echo_secret/);
|
||||
const runtime = omp.runtime();
|
||||
const result = runtime.nextHostToolResult();
|
||||
runtime.emit({
|
||||
type: "host_tool_call",
|
||||
id: "call-1",
|
||||
toolCallId: "tool-1",
|
||||
toolName: tool!.name,
|
||||
arguments: { word: "hello" },
|
||||
});
|
||||
expect(await result).toMatchObject({
|
||||
id: "call-1",
|
||||
result: { content: [{ type: "text", text: "MANGO:hello" }] },
|
||||
});
|
||||
const failed = runtime.nextHostToolResult();
|
||||
runtime.emit({
|
||||
type: "host_tool_call",
|
||||
id: "call-2",
|
||||
toolCallId: "tool-2",
|
||||
toolName: tool!.name,
|
||||
arguments: { word: "FAIL" },
|
||||
});
|
||||
expect(await failed).toMatchObject({
|
||||
id: "call-2",
|
||||
isError: true,
|
||||
result: { isError: true, content: [{ type: "text", text: "fixture failure" }] },
|
||||
});
|
||||
runtime.emit({
|
||||
type: "tool_execution_start",
|
||||
toolCallId: "tool-1",
|
||||
toolName: tool!.name,
|
||||
args: { word: "hello" },
|
||||
});
|
||||
runtime.emit({
|
||||
type: "tool_execution_end",
|
||||
toolCallId: "tool-1",
|
||||
toolName: tool!.name,
|
||||
result: { content: [{ type: "text", text: "MANGO:hello" }] },
|
||||
});
|
||||
expect(omp.timeline().at(-1)).toMatchObject({
|
||||
type: "tool_call",
|
||||
name: "local / echo_secret",
|
||||
status: "completed",
|
||||
detail: {
|
||||
type: "unknown",
|
||||
input: { word: "hello" },
|
||||
output: { content: [{ type: "text", text: "MANGO:hello" }] },
|
||||
},
|
||||
});
|
||||
runtime.emit({
|
||||
type: "tool_execution_start",
|
||||
toolCallId: "native-1",
|
||||
toolName: "mcp__native_echo_secret",
|
||||
args: { word: "native" },
|
||||
});
|
||||
runtime.emit({
|
||||
type: "tool_execution_end",
|
||||
toolCallId: "native-1",
|
||||
toolName: "mcp__native_echo_secret",
|
||||
result: { content: [{ type: "text", text: "native result" }] },
|
||||
});
|
||||
expect(omp.timeline().at(-1)).toMatchObject({
|
||||
type: "tool_call",
|
||||
name: "mcp__native_echo_secret",
|
||||
detail: { type: "unknown", input: { word: "native" } },
|
||||
});
|
||||
} finally {
|
||||
await omp.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("skips a failed server and registers a healthy one", async () => {
|
||||
await mkdir("/tmp/paseo-omp-agent-test", { recursive: true });
|
||||
const omp = new OmpHarness();
|
||||
await omp.start({
|
||||
mcpServers: { broken: { type: "stdio", command: "/nonexistent/omp-mcp" }, local: healthy },
|
||||
});
|
||||
try {
|
||||
expect(
|
||||
omp
|
||||
.registeredHostTools()
|
||||
.at(-1)
|
||||
?.map((tool) => tool.name),
|
||||
).toEqual([expect.stringMatching(/^mcp_local__echo_secret/)]);
|
||||
const runtime = omp.runtime();
|
||||
const result = runtime.nextHostToolResult();
|
||||
runtime.emit({
|
||||
type: "host_tool_call",
|
||||
id: "healthy-call",
|
||||
toolCallId: "healthy-tool",
|
||||
toolName: omp.registeredHostTools()[0]![0]!.name,
|
||||
arguments: { word: "healthy" },
|
||||
});
|
||||
expect(await result).toMatchObject({
|
||||
result: { content: [{ type: "text", text: "MANGO:healthy" }] },
|
||||
});
|
||||
} finally {
|
||||
await omp.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("starts with a healthy server when another never answers initialize", async () => {
|
||||
await mkdir("/tmp/paseo-omp-agent-test", { recursive: true });
|
||||
const omp = new OmpHarness();
|
||||
const started = Date.now();
|
||||
await omp.start({
|
||||
mcpServers: {
|
||||
silent: {
|
||||
type: "stdio",
|
||||
command: process.execPath,
|
||||
args: ["-e", "process.stdin.resume();setInterval(()=>{},1<<30)"],
|
||||
},
|
||||
local: healthy,
|
||||
},
|
||||
});
|
||||
try {
|
||||
expect(Date.now() - started).toBeLessThan(15_000);
|
||||
expect(
|
||||
omp
|
||||
.registeredHostTools()
|
||||
.at(-1)
|
||||
?.map((tool) => tool.name),
|
||||
).toEqual([expect.stringMatching(/^mcp_local__echo_secret/)]);
|
||||
} finally {
|
||||
await omp.close();
|
||||
}
|
||||
}, 80_000);
|
||||
|
||||
test("passes runtime and launch env to stdio, then applies server env", async () => {
|
||||
await mkdir("/tmp/paseo-omp-agent-test", { recursive: true });
|
||||
const omp = new OmpHarness({
|
||||
runtimeEnv: { OMP_MCP_RUNTIME_ENV: "runtime", OMP_MCP_PRECEDENCE: "runtime" },
|
||||
});
|
||||
await omp.start(
|
||||
{
|
||||
mcpServers: {
|
||||
local: { ...healthy, env: { OMP_MCP_PRECEDENCE: "server" } },
|
||||
},
|
||||
},
|
||||
undefined,
|
||||
{ PASEO_AGENT_ID: "agent-123", OMP_MCP_PRECEDENCE: "launch" },
|
||||
);
|
||||
try {
|
||||
const runtime = omp.runtime();
|
||||
const result = runtime.nextHostToolResult();
|
||||
runtime.emit({
|
||||
type: "host_tool_call",
|
||||
id: "env-call",
|
||||
toolCallId: "env-tool",
|
||||
toolName: omp.registeredHostTools()[0]![0]!.name,
|
||||
arguments: { word: "ENV" },
|
||||
});
|
||||
expect(await result).toMatchObject({
|
||||
result: {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: '{"runtime":"runtime","agent":"agent-123","precedence":"server"}',
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await omp.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("replays the bridge label and Codex-style detail after archive", async () => {
|
||||
await mkdir("/tmp/paseo-omp-agent-test", { recursive: true });
|
||||
const omp = new OmpHarness();
|
||||
await omp.start({ mcpServers: { local: healthy } });
|
||||
try {
|
||||
const exposedName = omp.registeredHostTools()[0]![0]!.name;
|
||||
const persisted = omp.persistence();
|
||||
expect(persisted?.metadata?.bridgedTools).toEqual([
|
||||
[exposedName, { server: "local", tool: "echo_secret" }],
|
||||
]);
|
||||
const directory = await mkdtemp(join(tmpdir(), "omp-mcp-history-"));
|
||||
const sessionFile = join(directory, "session.jsonl");
|
||||
await writeFile(
|
||||
sessionFile,
|
||||
[
|
||||
{ type: "session", id: "root", parentId: null },
|
||||
{
|
||||
type: "message",
|
||||
id: "call",
|
||||
parentId: "root",
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: [
|
||||
{
|
||||
type: "toolCall",
|
||||
id: "tool-1",
|
||||
name: exposedName,
|
||||
arguments: { word: "REVIEW" },
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "message",
|
||||
id: "result",
|
||||
parentId: "call",
|
||||
message: {
|
||||
role: "toolResult",
|
||||
toolCallId: "tool-1",
|
||||
toolName: exposedName,
|
||||
content: [{ type: "text", text: "MANGO:REVIEW" }],
|
||||
},
|
||||
},
|
||||
]
|
||||
.map((entry) => JSON.stringify(entry))
|
||||
.join("\n"),
|
||||
);
|
||||
const events = await omp.replayHistory({ ...persisted!, nativeHandle: sessionFile });
|
||||
expect(events.findLast((event) => event.type === "timeline")?.item).toMatchObject({
|
||||
type: "tool_call",
|
||||
name: "local / echo_secret",
|
||||
detail: {
|
||||
type: "unknown",
|
||||
input: { word: "REVIEW" },
|
||||
output: { content: [{ type: "text", text: "MANGO:REVIEW" }] },
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await omp.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("registers Paseo and MCP tools in the same replacement set", async () => {
|
||||
await mkdir("/tmp/paseo-omp-agent-test", { recursive: true });
|
||||
const paseoTools: PaseoToolCatalog = {
|
||||
tools: new Map([
|
||||
[
|
||||
"create_agent",
|
||||
{
|
||||
name: "create_agent",
|
||||
description: "Create an agent",
|
||||
handler: async () => ({ content: [] }),
|
||||
},
|
||||
],
|
||||
]),
|
||||
getTool: () => undefined,
|
||||
executeTool: async () => ({ content: [] }),
|
||||
};
|
||||
const omp = new OmpHarness();
|
||||
await omp.start({ mcpServers: { local: healthy } }, paseoTools);
|
||||
try {
|
||||
expect(omp.registeredHostTools()).toHaveLength(1);
|
||||
expect(omp.registeredHostTools()[0]?.map((tool) => tool.name)).toEqual([
|
||||
"create_agent",
|
||||
expect.stringMatching(/^mcp_local__echo_secret_/),
|
||||
]);
|
||||
} finally {
|
||||
await omp.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("registers MCP tools after resume and crash relaunch", async () => {
|
||||
await mkdir("/tmp/paseo-omp-agent-test", { recursive: true });
|
||||
const omp = new OmpHarness();
|
||||
await omp.resume(
|
||||
{ user: { id: "user-1", text: "hello" }, assistant: { id: "assistant-1", text: "hi" } },
|
||||
{ mcpServers: { local: healthy } },
|
||||
);
|
||||
try {
|
||||
expect(omp.registeredHostTools().at(-1)?.[0]?.name).toMatch(/^mcp_local__echo_secret/);
|
||||
omp.processExit("crashed");
|
||||
await omp.startTurn("again");
|
||||
await vi.waitFor(() => {
|
||||
expect(omp.runtimeSessions()).toHaveLength(2);
|
||||
expect(omp.registeredHostTools().at(-1)?.[0]?.name).toMatch(/^mcp_local__echo_secret/);
|
||||
});
|
||||
} finally {
|
||||
await omp.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("closes the stdio MCP child with the session", async () => {
|
||||
await mkdir("/tmp/paseo-omp-agent-test", { recursive: true });
|
||||
const directory = await mkdtemp(join(tmpdir(), "omp-mcp-pid-"));
|
||||
const pidFile = join(directory, "pid");
|
||||
const omp = new OmpHarness();
|
||||
await omp.start({ mcpServers: { local: { ...healthy, env: { OMP_MCP_PID_FILE: pidFile } } } });
|
||||
const pid = Number(await readFile(pidFile, "utf8"));
|
||||
expect(() => process.kill(pid, 0)).not.toThrow();
|
||||
await omp.close();
|
||||
expect(() => process.kill(pid, 0)).toThrow();
|
||||
});
|
||||
|
||||
test("cancels an in-flight MCP call when OMP cancels its host tool", async () => {
|
||||
await mkdir("/tmp/paseo-omp-agent-test", { recursive: true });
|
||||
const directory = await mkdtemp(join(tmpdir(), "omp-mcp-cancel-"));
|
||||
const waitFile = join(directory, "waiting");
|
||||
const cancelFile = join(directory, "cancelled");
|
||||
const omp = new OmpHarness();
|
||||
await omp.start({
|
||||
mcpServers: {
|
||||
local: {
|
||||
...healthy,
|
||||
env: { OMP_MCP_WAIT_FILE: waitFile, OMP_MCP_CANCEL_FILE: cancelFile },
|
||||
},
|
||||
},
|
||||
});
|
||||
try {
|
||||
const runtime = omp.runtime();
|
||||
runtime.emit({
|
||||
type: "host_tool_call",
|
||||
id: "wait-call",
|
||||
toolCallId: "wait-tool",
|
||||
toolName: omp.registeredHostTools()[0]![0]!.name,
|
||||
arguments: { word: "WAIT" },
|
||||
});
|
||||
await vi.waitFor(async () => expect(await readFile(waitFile, "utf8")).toBe("waiting"));
|
||||
runtime.emit({ type: "host_tool_cancel", id: "cancel-1", targetId: "wait-call" });
|
||||
await vi.waitFor(async () => expect(await readFile(cancelFile, "utf8")).toBe("cancelled"));
|
||||
expect(runtime.hostToolResults).toEqual([]);
|
||||
} finally {
|
||||
await omp.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,142 +0,0 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
|
||||
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
||||
import { CallToolResultSchema } from "@modelcontextprotocol/sdk/types.js";
|
||||
import type { Logger } from "pino";
|
||||
import type { McpServerConfig } from "../../agent-sdk-types.js";
|
||||
import type { PaseoToolResult } from "../../tools/types.js";
|
||||
import type { OmpRpcHostToolDefinition } from "./rpc-types.js";
|
||||
|
||||
interface BridgedTool {
|
||||
client: Client;
|
||||
server: string;
|
||||
tool: string;
|
||||
}
|
||||
|
||||
export interface OmpBridgedToolIdentity {
|
||||
server: string;
|
||||
tool: string;
|
||||
}
|
||||
|
||||
const SERVER_TIMEOUT_MS = 10_000;
|
||||
|
||||
export class OmpMcpBridge {
|
||||
readonly definitions: OmpRpcHostToolDefinition[] = [];
|
||||
private readonly tools = new Map<string, BridgedTool>();
|
||||
private readonly clients: Client[] = [];
|
||||
private closed = false;
|
||||
|
||||
static async connect(
|
||||
servers: Record<string, McpServerConfig> | undefined,
|
||||
cwd: string,
|
||||
logger: Logger,
|
||||
env: NodeJS.ProcessEnv,
|
||||
): Promise<OmpMcpBridge> {
|
||||
const bridge = new OmpMcpBridge();
|
||||
const connections = await Promise.all(
|
||||
Object.entries(servers ?? {}).map(async ([serverName, config]) => {
|
||||
const client = new Client({ name: "paseo-omp-mcp", version: "1.0.0" });
|
||||
try {
|
||||
const transport = makeTransport(config, cwd, env);
|
||||
await client.connect(transport, { timeout: SERVER_TIMEOUT_MS });
|
||||
const listed = await client.listTools(undefined, { timeout: SERVER_TIMEOUT_MS });
|
||||
return { serverName, client, tools: listed.tools };
|
||||
} catch (error) {
|
||||
logger.warn({ err: error, server: serverName }, "OMP MCP server unavailable");
|
||||
await client.close().catch(() => undefined);
|
||||
return null;
|
||||
}
|
||||
}),
|
||||
);
|
||||
for (const connection of connections) {
|
||||
if (!connection) continue;
|
||||
const { serverName, client, tools } = connection;
|
||||
bridge.clients.push(client);
|
||||
for (const tool of tools) {
|
||||
const name = bridgeName(serverName, tool.name);
|
||||
bridge.tools.set(name, { client, server: serverName, tool: tool.name });
|
||||
bridge.definitions.push({
|
||||
name,
|
||||
label: `${serverName} / ${tool.name}`,
|
||||
description: tool.description || `${tool.name} from ${serverName}`,
|
||||
loadMode: "essential",
|
||||
parameters: tool.inputSchema,
|
||||
});
|
||||
}
|
||||
}
|
||||
return bridge;
|
||||
}
|
||||
|
||||
tool(name: string): OmpBridgedToolIdentity | undefined {
|
||||
const entry = this.tools.get(name);
|
||||
return entry ? { server: entry.server, tool: entry.tool } : undefined;
|
||||
}
|
||||
|
||||
toolIdentities(): Map<string, OmpBridgedToolIdentity> {
|
||||
return new Map(
|
||||
[...this.tools].map(([name, entry]) => [name, { server: entry.server, tool: entry.tool }]),
|
||||
);
|
||||
}
|
||||
|
||||
async execute(
|
||||
name: string,
|
||||
args: Record<string, unknown>,
|
||||
signal: AbortSignal,
|
||||
): Promise<PaseoToolResult> {
|
||||
const entry = this.tools.get(name);
|
||||
if (!entry || this.closed) throw new Error(`MCP tool ${name} is unavailable`);
|
||||
const raw = await entry.client.callTool({ name: entry.tool, arguments: args }, undefined, {
|
||||
signal,
|
||||
});
|
||||
const result = CallToolResultSchema.parse(raw);
|
||||
return {
|
||||
content: result.content.map((item) => ({ ...item })),
|
||||
...(result.structuredContent !== undefined
|
||||
? { structuredContent: result.structuredContent }
|
||||
: {}),
|
||||
...(result.isError !== undefined ? { isError: result.isError } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
if (this.closed) return;
|
||||
this.closed = true;
|
||||
await Promise.all(this.clients.map((client) => client.close().catch(() => undefined)));
|
||||
this.clients.length = 0;
|
||||
}
|
||||
}
|
||||
|
||||
function makeTransport(config: McpServerConfig, cwd: string, env: NodeJS.ProcessEnv) {
|
||||
if (config.type === "stdio") {
|
||||
return new StdioClientTransport({
|
||||
command: config.command,
|
||||
args: config.args,
|
||||
cwd,
|
||||
env: { ...env, ...config.env } as Record<string, string>,
|
||||
stderr: "ignore",
|
||||
});
|
||||
}
|
||||
if (config.type === "http") {
|
||||
return new StreamableHTTPClientTransport(new URL(config.url), {
|
||||
requestInit: { headers: config.headers },
|
||||
});
|
||||
}
|
||||
return new SSEClientTransport(new URL(config.url), {
|
||||
requestInit: { headers: config.headers },
|
||||
eventSourceInit: {
|
||||
fetch: (url, init) =>
|
||||
fetch(url, { ...init, headers: { ...init?.headers, ...config.headers } }),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function bridgeName(server: string, tool: string): string {
|
||||
const key = `${server}\0${tool}`;
|
||||
const hash = createHash("sha256").update(key).digest("hex").slice(0, 12);
|
||||
const clean = (name: string, length: number) =>
|
||||
name.replace(/[^A-Za-z0-9_-]/g, "_").slice(0, length);
|
||||
// 64 characters also fits the stricter model tool-name limits OMP can reach.
|
||||
return `mcp_${clean(server, 20)}__${clean(tool, 25)}_${hash}`;
|
||||
}
|
||||
@@ -1,18 +1,12 @@
|
||||
import type { AgentStreamEvent, AgentTimelineItem, ToolCallDetail } from "../../agent-sdk-types.js";
|
||||
import type { OmpAgentMessage, OmpImageContent, OmpTextContent } from "./rpc-types.js";
|
||||
import type { OmpBridgedToolIdentity } from "./mcp-bridge.js";
|
||||
import {
|
||||
ompCustomMessageId,
|
||||
ompSkillPromptUserText,
|
||||
shouldDisplayOmpCustomMessage,
|
||||
} from "./custom-message.js";
|
||||
import { shouldDisplayOmpCustomMessage } from "./custom-message.js";
|
||||
import {
|
||||
extractTextFromToolResult,
|
||||
mapToolDetail,
|
||||
parseToolArgs,
|
||||
parseToolResult,
|
||||
resolveToolCallName,
|
||||
toolFailureMessage,
|
||||
isOmpToolFailure,
|
||||
type OmpToolResult,
|
||||
type OmpTrackedToolCall,
|
||||
} from "./tool-call-detail.js";
|
||||
@@ -32,7 +26,7 @@ export interface OmpHistoryMapperHooks {
|
||||
mapToolDetail?: (
|
||||
toolCall: OmpTrackedToolCall,
|
||||
result: OmpToolResult,
|
||||
context: { toolCallId: string; bridgedTool?: OmpBridgedToolIdentity },
|
||||
context: { toolCallId: string },
|
||||
) => ToolCallDetail | null;
|
||||
}
|
||||
|
||||
@@ -64,13 +58,11 @@ export class OmpHistoryMapper {
|
||||
private readonly pendingToolCalls = new Map<string, OmpTrackedToolCall>();
|
||||
private userIndex = 0;
|
||||
private assistantIndex = 0;
|
||||
private customIndex = 0;
|
||||
|
||||
constructor(
|
||||
private readonly provider: string,
|
||||
private readonly userEntries: readonly OmpCapturedUserMessageEntry[] = [],
|
||||
private readonly hooks: OmpHistoryMapperHooks = {},
|
||||
private readonly bridgedTools: ReadonlyMap<string, OmpBridgedToolIdentity> = new Map(),
|
||||
) {}
|
||||
|
||||
mapMessages(messages: readonly OmpAgentMessage[]): AgentStreamEvent[] {
|
||||
@@ -134,30 +126,15 @@ export class OmpHistoryMapper {
|
||||
if (mappedEvent) {
|
||||
return [mappedEvent];
|
||||
}
|
||||
if (!text) {
|
||||
return [];
|
||||
}
|
||||
const messageId = ompCustomMessageId(message, () => {
|
||||
this.customIndex += 1;
|
||||
return this.customIndex;
|
||||
});
|
||||
const skillPrompt = ompSkillPromptUserText(message);
|
||||
if (skillPrompt) {
|
||||
return [
|
||||
{
|
||||
type: "timeline",
|
||||
provider: this.provider,
|
||||
item: { type: "user_message", text: skillPrompt, messageId: `${messageId}-user` },
|
||||
},
|
||||
];
|
||||
}
|
||||
return [
|
||||
{
|
||||
type: "timeline",
|
||||
provider: this.provider,
|
||||
item: { type: "assistant_message", text, messageId },
|
||||
},
|
||||
];
|
||||
return text
|
||||
? [
|
||||
{
|
||||
type: "timeline",
|
||||
provider: this.provider,
|
||||
item: { type: "assistant_message", text },
|
||||
},
|
||||
]
|
||||
: [];
|
||||
}
|
||||
|
||||
private mapAssistantMessage(
|
||||
@@ -197,7 +174,7 @@ export class OmpHistoryMapper {
|
||||
item: {
|
||||
type: "tool_call",
|
||||
callId: this.resolveToolCallId(content.id, tracked),
|
||||
name: this.toolName(tracked, null),
|
||||
name: tracked.toolName,
|
||||
status: "running",
|
||||
detail,
|
||||
error: null,
|
||||
@@ -224,10 +201,10 @@ export class OmpHistoryMapper {
|
||||
provider: this.provider,
|
||||
item: toToolResultTimelineItem({
|
||||
callId: this.resolveToolCallId(message.toolCallId, tracked),
|
||||
name: this.toolName(tracked, result),
|
||||
isError: isOmpToolFailure(tracked, result, Boolean(message.isError)),
|
||||
name: resolveToolCallName(tracked, result),
|
||||
isError: Boolean(message.isError),
|
||||
detail,
|
||||
errorText: toolFailureMessage(result),
|
||||
errorText: extractTextFromToolResult(result) ?? "Tool call failed",
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -265,17 +242,7 @@ export class OmpHistoryMapper {
|
||||
result: OmpToolResult,
|
||||
): ToolCallDetail | null {
|
||||
const hook = this.hooks.mapToolDetail;
|
||||
return hook
|
||||
? hook(toolCall, result, {
|
||||
toolCallId,
|
||||
bridgedTool: this.bridgedTools.get(toolCall.toolName),
|
||||
})
|
||||
: mapToolDetail(toolCall, result);
|
||||
}
|
||||
|
||||
private toolName(toolCall: OmpTrackedToolCall, result: OmpToolResult): string {
|
||||
const bridged = this.bridgedTools.get(toolCall.toolName);
|
||||
return bridged ? `${bridged.server} / ${bridged.tool}` : resolveToolCallName(toolCall, result);
|
||||
return hook ? hook(toolCall, result, { toolCallId }) : mapToolDetail(toolCall, result);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import { z } from "zod";
|
||||
|
||||
import type { ProviderRuntimeSettings } from "../../provider-launch-config.js";
|
||||
|
||||
const OMP_SESSION_DIR = "~/.omp/agent/sessions";
|
||||
const DEFAULT_OMP_MODE_ID = "full";
|
||||
const DEFAULT_OMP_READY_TIMEOUT_MS = 20_000;
|
||||
const DEFAULT_OMP_RPC_TIMEOUT_MS = 60_000;
|
||||
@@ -24,7 +25,7 @@ export const OmpProviderParamsSchema = z
|
||||
.strict();
|
||||
|
||||
export interface OmpRuntimeProviderParams {
|
||||
sessionDir?: string;
|
||||
sessionDir: string;
|
||||
readyTimeoutMs: number;
|
||||
rpcTimeoutMs: number;
|
||||
}
|
||||
@@ -136,7 +137,7 @@ export function resolveOmpProviderParams(providerParams: unknown): {
|
||||
const configuredRpcTimeoutMs = params.rpcTimeoutMs;
|
||||
return {
|
||||
runtimeProviderParams: {
|
||||
sessionDir: params.sessionDir,
|
||||
sessionDir: params.sessionDir ?? OMP_SESSION_DIR,
|
||||
readyTimeoutMs: configuredRpcTimeoutMs ?? DEFAULT_OMP_READY_TIMEOUT_MS,
|
||||
rpcTimeoutMs: configuredRpcTimeoutMs ?? DEFAULT_OMP_RPC_TIMEOUT_MS,
|
||||
},
|
||||
|
||||
@@ -1,355 +0,0 @@
|
||||
import type {
|
||||
AgentPermissionRequest,
|
||||
AgentPermissionResponse,
|
||||
AgentProvider,
|
||||
} from "../../agent-sdk-types.js";
|
||||
import type { OmpAgentMessage, OmpRuntimeEvent } from "./rpc-types.js";
|
||||
|
||||
type UiRequest = Extract<OmpRuntimeEvent, { type: "extension_ui_request" }>;
|
||||
interface UiResponse {
|
||||
value?: string;
|
||||
confirmed?: boolean;
|
||||
cancelled?: boolean;
|
||||
}
|
||||
type SendResponse = (id: string, response: UiResponse) => void;
|
||||
|
||||
const OTHER = "Other (type your own)";
|
||||
const ANSWER_HEADER = "Response";
|
||||
|
||||
interface SelectOption {
|
||||
label: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
interface AskQuestion {
|
||||
title: string;
|
||||
multi: boolean;
|
||||
options: SelectOption[];
|
||||
}
|
||||
|
||||
interface PendingAnswer {
|
||||
question: AskQuestion;
|
||||
selected: string[];
|
||||
custom: string | null;
|
||||
next: "select" | "editor";
|
||||
}
|
||||
|
||||
function record(value: unknown): Record<string, unknown> | null {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value)
|
||||
? (value as Record<string, unknown>)
|
||||
: null;
|
||||
}
|
||||
|
||||
function string(value: unknown): string | undefined {
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
|
||||
function readSelectOptions(event: UiRequest): SelectOption[] {
|
||||
const details = Array.isArray(event.optionDetails) ? event.optionDetails : [];
|
||||
return (event.options ?? []).map((label, index) => {
|
||||
const description = string(record(details[index])?.description);
|
||||
return description?.trim() ? { label, description } : { label };
|
||||
});
|
||||
}
|
||||
|
||||
function isOptionalInput(placeholder: string | undefined): boolean {
|
||||
return /\boptional\b|\bskip\b/i.test(placeholder ?? "");
|
||||
}
|
||||
|
||||
function inputTitle(title: string | undefined, placeholder: string | undefined): string {
|
||||
if (!isOptionalInput(placeholder)) return title ?? "Enter a value";
|
||||
return /\bcomment\b/i.test(`${title ?? ""}\n${placeholder ?? ""}`)
|
||||
? "Optional comment"
|
||||
: "Optional response";
|
||||
}
|
||||
|
||||
function genericQuestion(
|
||||
event: UiRequest,
|
||||
provider: AgentProvider,
|
||||
title: string,
|
||||
options: SelectOption[],
|
||||
input: { placeholder?: string; allowEmpty?: boolean; dismissLabel?: string } = {},
|
||||
): AgentPermissionRequest {
|
||||
return {
|
||||
id: event.id,
|
||||
provider,
|
||||
name: `OMP ${event.method}`,
|
||||
kind: "question",
|
||||
title,
|
||||
input: {
|
||||
questions: [
|
||||
{ question: title, header: ANSWER_HEADER, options, multiSelect: false, ...input },
|
||||
],
|
||||
},
|
||||
metadata: { extensionUiMethod: event.method, answerHeader: ANSWER_HEADER },
|
||||
};
|
||||
}
|
||||
|
||||
function mapGenericQuestion(
|
||||
event: UiRequest,
|
||||
provider: AgentProvider,
|
||||
): AgentPermissionRequest | null {
|
||||
switch (event.method) {
|
||||
case "select":
|
||||
return genericQuestion(
|
||||
event,
|
||||
provider,
|
||||
event.title ?? "Select an option",
|
||||
readSelectOptions(event),
|
||||
);
|
||||
case "input": {
|
||||
const placeholder = event.placeholder;
|
||||
const optional = isOptionalInput(placeholder);
|
||||
return genericQuestion(event, provider, inputTitle(event.title, placeholder), [], {
|
||||
...(placeholder ? { placeholder } : {}),
|
||||
...(optional ? { allowEmpty: true, dismissLabel: "Skip" } : {}),
|
||||
});
|
||||
}
|
||||
case "editor":
|
||||
return genericQuestion(event, provider, event.title ?? "Edit text", []);
|
||||
case "confirm":
|
||||
return genericQuestion(
|
||||
event,
|
||||
provider,
|
||||
[event.title, event.message].filter(Boolean).join("\n\n"),
|
||||
[{ label: "Yes" }, { label: "No" }],
|
||||
);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function genericResponse(
|
||||
request: AgentPermissionRequest,
|
||||
response: AgentPermissionResponse,
|
||||
): UiResponse {
|
||||
if (response.behavior === "deny") return { cancelled: true };
|
||||
const answers = record(response.updatedInput?.answers);
|
||||
const answer = Object.values(answers ?? {}).find(
|
||||
(value): value is string => typeof value === "string",
|
||||
);
|
||||
if (answer === undefined) return { cancelled: true };
|
||||
return request.metadata?.extensionUiMethod === "confirm"
|
||||
? { confirmed: /^yes$/i.test(answer.trim()) }
|
||||
: { value: answer };
|
||||
}
|
||||
|
||||
function questionTitle(title: string): string {
|
||||
return title.replace(/^\(\d+ selected\) /, "");
|
||||
}
|
||||
|
||||
function matchesQuestion(title: string, question: AskQuestion): boolean {
|
||||
const plainTitle = questionTitle(title);
|
||||
if (plainTitle === question.title) return true;
|
||||
return (
|
||||
plainTitle.startsWith(question.title) &&
|
||||
/^ \(\d+\/\d+\)$/.test(plainTitle.slice(question.title.length))
|
||||
);
|
||||
}
|
||||
|
||||
function readQuestions(args: unknown): AskQuestion[] {
|
||||
const questions = record(args)?.questions;
|
||||
if (!Array.isArray(questions)) return [];
|
||||
return questions.flatMap((item) => {
|
||||
const question = record(item);
|
||||
if (typeof question?.question !== "string" || !Array.isArray(question.options)) return [];
|
||||
const options = question.options.flatMap((optionValue) => {
|
||||
const option = record(optionValue);
|
||||
if (typeof option?.label !== "string") return [];
|
||||
return [
|
||||
{
|
||||
label: option.label,
|
||||
...(typeof option.description === "string" ? { description: option.description } : {}),
|
||||
},
|
||||
];
|
||||
});
|
||||
return [{ title: question.question, multi: question.multi === true, options }];
|
||||
});
|
||||
}
|
||||
|
||||
function selectedAnswer(
|
||||
answer: string,
|
||||
labels: string[],
|
||||
multi: boolean,
|
||||
): { selected: string[]; custom: string | null } {
|
||||
if (!multi)
|
||||
return labels.includes(answer)
|
||||
? { selected: [answer], custom: null }
|
||||
: { selected: [], custom: answer };
|
||||
|
||||
// The shared question UI sends a comma-joined answer in click order. Consume
|
||||
// exact option labels from the front; any remaining text is the Other answer.
|
||||
let remaining = answer;
|
||||
const selected: string[] = [];
|
||||
while (remaining.length > 0) {
|
||||
const label = labels
|
||||
.filter((candidate) => !selected.includes(candidate))
|
||||
.sort((left, right) => right.length - left.length)
|
||||
.find((candidate) => remaining === candidate || remaining.startsWith(`${candidate}, `));
|
||||
if (!label) break;
|
||||
selected.push(label);
|
||||
remaining = remaining === label ? "" : remaining.slice(label.length + 2);
|
||||
}
|
||||
return { selected, custom: remaining || null };
|
||||
}
|
||||
|
||||
/** Owns OMP question mapping and the ask tool's multi-RPC answer sequence. */
|
||||
export class OmpQuestionUi {
|
||||
private questions: AskQuestion[] = [];
|
||||
private pending: PendingAnswer | null = null;
|
||||
|
||||
observeMessage(message: OmpAgentMessage): void {
|
||||
if (message.role !== "assistant") return;
|
||||
for (const item of message.content) {
|
||||
if (item.type === "toolCall" && item.name === "ask") this.start(item.name, item.arguments);
|
||||
}
|
||||
}
|
||||
|
||||
start(toolName: string, args: unknown): void {
|
||||
if (toolName === "ask") {
|
||||
this.questions = readQuestions(args);
|
||||
this.pending = null;
|
||||
}
|
||||
}
|
||||
|
||||
finish(toolName: string): void {
|
||||
if (toolName === "ask") {
|
||||
this.questions = [];
|
||||
this.pending = null;
|
||||
}
|
||||
}
|
||||
|
||||
handleRequest(
|
||||
event: UiRequest,
|
||||
provider: AgentProvider,
|
||||
send: SendResponse,
|
||||
): AgentPermissionRequest | null {
|
||||
if (this.consume(event, send)) return null;
|
||||
return this.mapAsk(event, provider) ?? mapGenericQuestion(event, provider);
|
||||
}
|
||||
|
||||
private mapAsk(event: UiRequest, provider: AgentProvider): AgentPermissionRequest | null {
|
||||
if (event.method !== "select" || typeof event.title !== "string") return null;
|
||||
const title = event.title;
|
||||
const question = this.questions.find((item) => matchesQuestion(title, item));
|
||||
if (!question || !Array.isArray(event.options) || !event.options.includes(OTHER)) return null;
|
||||
|
||||
const descriptions = new Map(
|
||||
question.options.map((option) => [option.label, option.description]),
|
||||
);
|
||||
const options = readSelectOptions(event)
|
||||
.filter((option) => option.label !== OTHER && !option.label.endsWith(" Done selecting"))
|
||||
.map((option) => {
|
||||
const description =
|
||||
descriptions.get(option.label) ??
|
||||
descriptions.get(option.label.replace(/ \(Recommended\)$/, "")) ??
|
||||
option.description;
|
||||
return description ? { label: option.label, description } : { label: option.label };
|
||||
});
|
||||
return {
|
||||
id: event.id,
|
||||
provider,
|
||||
name: "OMP ask",
|
||||
kind: "question",
|
||||
title: question.title,
|
||||
input: {
|
||||
questions: [
|
||||
{
|
||||
question: question.title,
|
||||
header: ANSWER_HEADER,
|
||||
options,
|
||||
multiSelect: question.multi,
|
||||
allowOther: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
metadata: {
|
||||
ompAsk: true,
|
||||
answerHeader: ANSWER_HEADER,
|
||||
optionLabels: options.map((option) => option.label),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
respond(
|
||||
request: AgentPermissionRequest,
|
||||
response: AgentPermissionResponse,
|
||||
send: SendResponse,
|
||||
): void {
|
||||
if (request.metadata?.ompAsk !== true) {
|
||||
send(request.id, genericResponse(request, response));
|
||||
return;
|
||||
}
|
||||
const question = this.questions.find((item) => item.title === request.title);
|
||||
const answers = record(
|
||||
response.behavior === "allow" ? response.updatedInput?.answers : undefined,
|
||||
);
|
||||
const answer = answers?.[ANSWER_HEADER];
|
||||
if (response.behavior === "deny" || typeof answer !== "string" || !question) {
|
||||
this.pending = null;
|
||||
send(request.id, { cancelled: true });
|
||||
return;
|
||||
}
|
||||
|
||||
const labels = Array.isArray(request.metadata.optionLabels)
|
||||
? request.metadata.optionLabels.filter((item): item is string => typeof item === "string")
|
||||
: [];
|
||||
const { selected, custom } = selectedAnswer(answer, labels, question.multi);
|
||||
if (selected.length === 0 && custom === null) {
|
||||
this.pending = null;
|
||||
send(request.id, { cancelled: true });
|
||||
return;
|
||||
}
|
||||
if (question.multi) {
|
||||
this.pending = { question, selected: selected.slice(1), custom, next: "select" };
|
||||
send(request.id, { value: selected[0] ?? OTHER });
|
||||
if (selected.length === 0) this.pending.next = "editor";
|
||||
} else if (custom !== null) {
|
||||
this.pending = { question, selected: [], custom, next: "editor" };
|
||||
send(request.id, { value: OTHER });
|
||||
} else {
|
||||
this.pending = null;
|
||||
send(request.id, { value: selected[0] });
|
||||
}
|
||||
}
|
||||
|
||||
consume(event: UiRequest, send: SendResponse): boolean {
|
||||
const pending = this.pending;
|
||||
if (pending?.next === "editor" && event.method === "editor" && pending.custom !== null) {
|
||||
this.pending = null;
|
||||
send(event.id, { value: pending.custom });
|
||||
return true;
|
||||
}
|
||||
if (
|
||||
!pending ||
|
||||
typeof event.title !== "string" ||
|
||||
!matchesQuestion(event.title, pending.question)
|
||||
)
|
||||
return false;
|
||||
if (pending.next !== "select" || event.method !== "select" || !Array.isArray(event.options))
|
||||
return false;
|
||||
|
||||
const choice = pending.selected[0];
|
||||
if (choice && event.options.includes(choice)) {
|
||||
pending.selected.shift();
|
||||
send(event.id, { value: choice });
|
||||
return true;
|
||||
}
|
||||
if (pending.custom !== null && event.options.includes(OTHER)) {
|
||||
pending.next = "editor";
|
||||
send(event.id, { value: OTHER });
|
||||
return true;
|
||||
}
|
||||
const done = event.options.find((option) => option.endsWith(" Done selecting"));
|
||||
if (!done) {
|
||||
// OMP omits Done for multi-question asks and expects a right-arrow
|
||||
// navigation callback, which its RPC response cannot express.
|
||||
this.pending = null;
|
||||
send(event.id, { cancelled: true });
|
||||
return true;
|
||||
}
|
||||
this.pending = null;
|
||||
send(event.id, { value: done });
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,6 @@ export const OmpThinkingLevelSchema = z.enum([
|
||||
"high",
|
||||
"xhigh",
|
||||
"max",
|
||||
"auto",
|
||||
]);
|
||||
|
||||
export const OmpImageContentSchema = z
|
||||
@@ -129,8 +128,6 @@ export const OmpSessionStateSchema = z
|
||||
isStreaming: z.boolean(),
|
||||
isCompacting: z.boolean(),
|
||||
autoCompactionEnabled: z.boolean().optional(),
|
||||
fastModeEnabled: z.boolean().optional(),
|
||||
fastModeActive: z.boolean().optional(),
|
||||
sessionFile: z.string().optional(),
|
||||
sessionId: z.string(),
|
||||
sessionName: z.string().optional(),
|
||||
@@ -336,8 +333,7 @@ export const OmpAgentSessionEventSchema = z.discriminatedUnion("type", [
|
||||
export const OmpTodoItemSchema = z
|
||||
.object({
|
||||
content: z.string(),
|
||||
status: z.enum(["pending", "in_progress", "completed", "abandoned", "blocked"]),
|
||||
blocker: z.string().optional(),
|
||||
status: z.enum(["pending", "in_progress", "completed", "abandoned"]),
|
||||
})
|
||||
.passthrough();
|
||||
export const OmpTodoPhaseSchema = z
|
||||
@@ -499,7 +495,6 @@ export const OmpRuntimeEventSchema = z.discriminatedUnion("type", [
|
||||
OmpRpcHostToolCallRequestSchema,
|
||||
OmpRpcHostToolCancelRequestSchema,
|
||||
OmpRpcHostToolUpdateSchema,
|
||||
z.object({ type: z.literal("model_changed") }).passthrough(),
|
||||
]);
|
||||
|
||||
const OmpCommandBase = { id: z.string().optional() };
|
||||
@@ -518,13 +513,6 @@ export const OmpRpcCommandSchema = z.discriminatedUnion("type", [
|
||||
z.object({ ...OmpCommandBase, type: z.literal("set_auto_compaction"), enabled: z.boolean() }),
|
||||
z.object({ ...OmpCommandBase, type: z.literal("abort") }),
|
||||
z.object({ ...OmpCommandBase, type: z.literal("get_state") }),
|
||||
z.object({
|
||||
...OmpCommandBase,
|
||||
type: z.literal("steer"),
|
||||
message: z.string(),
|
||||
images: z.array(OmpImageContentSchema).optional(),
|
||||
}),
|
||||
z.object({ ...OmpCommandBase, type: z.literal("set_fast_mode"), enabled: z.boolean() }),
|
||||
z.object({ ...OmpCommandBase, type: z.literal("get_messages") }),
|
||||
z.object({ ...OmpCommandBase, type: z.literal("get_available_models") }),
|
||||
z.object({
|
||||
|
||||
@@ -52,7 +52,6 @@ export interface OmpRuntimeSession {
|
||||
setAutoCompaction(enabled: boolean): Promise<void>;
|
||||
abort(): Promise<void>;
|
||||
getState(): Promise<OmpSessionState>;
|
||||
setFastMode(enabled: boolean): Promise<{ enabled: boolean; active: boolean }>;
|
||||
getMessages(): Promise<OmpAgentMessage[]>;
|
||||
getAvailableModels(timeoutMs?: number | null): Promise<OmpModel[]>;
|
||||
setModel(provider: string, modelId: string): Promise<OmpModel>;
|
||||
@@ -66,10 +65,7 @@ export interface OmpRuntimeSession {
|
||||
branch(entryId: string): Promise<{ text: string }>;
|
||||
getBranchMessages(): Promise<Array<{ entryId: string; text: string }>>;
|
||||
activeBranchEntryId?: string;
|
||||
steer(
|
||||
message: string,
|
||||
images?: Array<{ type: "image"; data: string; mimeType: string }>,
|
||||
): Promise<void>;
|
||||
steer(message: string, images?: Array<{ type: "image"; data: string; mimeType: string }>): void;
|
||||
followUp(
|
||||
message: string,
|
||||
images?: Array<{ type: "image"; data: string; mimeType: string }>,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user