mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-06 16:34:36 +00:00
Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a2ccad74e2 | ||
|
|
5acfbb3777 | ||
|
|
4117dce2d3 | ||
|
|
8388f16186 | ||
|
|
5c2a1552df | ||
|
|
e0de0fdf6f | ||
|
|
8d424e039e | ||
|
|
d9b874f9d0 | ||
|
|
f56c013928 | ||
|
|
208e323035 | ||
|
|
ec7446add4 | ||
|
|
b30302b630 | ||
|
|
7aa3fac069 |
+7
-1
@@ -1,9 +1,15 @@
|
||||
# Changelog
|
||||
|
||||
## 0.11.3 - 2026-10-15
|
||||
## 0.11.4 - 2026-10-15
|
||||
|
||||
[Hoplite](https://hoplite.sh) joins Paseo as our first sponsor through the company sponsorship program. Hoplite builds cloud coding agents that turn tasks from GitHub, Linear, Slack and more into pull requests. Thank you to the Hoplite team for supporting Paseo.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed Hoplite showing an error in Settings → Providers instead of discovering models in workspaces linked to a Hoplite project
|
||||
|
||||
## 0.11.3 - 2026-10-15
|
||||
|
||||
### Added
|
||||
|
||||
- Added Hoplite as an opt-in provider in the ACP provider catalog ([#6953](https://github.com/getpaseo/paseo/pull/6953) by [@odinglyn0](https://github.com/odinglyn0))
|
||||
|
||||
@@ -57,7 +57,7 @@ Paseo is an open source agentic development environment for desktop, mobile, web
|
||||
<!-- Sponsors: one cell per sponsor in the order of packages/website/src/data/sponsors.ts, then "become a sponsor" cells up to three. -->
|
||||
<table>
|
||||
<tr>
|
||||
<td align="center" width="33%"><a href="https://hoplite.sh/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/hoplite-on-dark.svg"><img src="packages/website/public/sponsors/hoplite-on-light.svg" alt="Hoplite" height="40"></picture></a><br><sub>Cloud coding agents</sub></td>
|
||||
<td align="center" width="33%"><a href="https://hoplite.sh/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/hoplite-on-dark.svg"><img src="packages/website/public/sponsors/hoplite-on-light.svg" alt="Hoplite" height="56"></picture></a><br><sub>Cloud coding agents</sub></td>
|
||||
<td align="center" width="33%"><a href="https://paseo.sh/sponsor">Become a sponsor</a></td>
|
||||
<td align="center" width="33%"><a href="https://paseo.sh/sponsor">Become a sponsor</a></td>
|
||||
</tr>
|
||||
|
||||
@@ -58,12 +58,17 @@ So arrival sets a _target_ and the reveal rate is derived from the backlog inste
|
||||
through that hook; the web viewport once skipped it and history hosts of a live tool group went
|
||||
stale. A new field on `StreamLayoutItem` must be added to `areLayoutItemsEquivalent`, or sharing
|
||||
silently stops.
|
||||
- **Streaming cost must not grow with revealed history.** Reading older messages must not
|
||||
make the next reply progressively more expensive to display. Reuse unchanged history work
|
||||
while text arrives, and release obsolete window caches as the reader reveals more history;
|
||||
window caches must stay bounded while their source timeline remains loaded.
|
||||
|
||||
## Measuring
|
||||
|
||||
- **Smoothness (user-perceived):** `packages/app/e2e/browser/agent-stream-smoothness.spec.ts`, gated behind `PASEO_AGENT_STREAM_PERF_E2E=1`. Drives the mock provider's `bursty-stream` model and reports coefficient of variation of characters painted per frame (smoothness) plus p95 gap between visible updates (stalls). Both numbers are needed: a stalled stream is perfectly smooth.
|
||||
- **Reproducing bursty arrival:** the `bursty-stream` model in `mock-load-test-agent.ts` emits uneven runs of tokens separated by idle gaps. Burst sizes come from a seeded generator, so a run repeats exactly.
|
||||
- **Rate policy in isolation:** `computeRevealStep` in `packages/app/src/agent-stream/text-reveal.ts` is pure; `text-reveal.test.ts` covers convergence and burst flattening without a renderer.
|
||||
- **Per-delta cost on a long timeline:** `npx vitest bench --project unit src/agent-stream/stream-tick.bench.ts` from `packages/app` replays 200 deltas over a 2,000-item timeline through the pure model and layout pipeline, with the default mounted window and with history fully revealed. It measures the JS work per delta, not paint.
|
||||
|
||||
Healthy numbers (2026-08, Expo web against a local dev daemon, real Claude Haiku agent, ~8.5s samples during active streaming). Setting `TEXT_REVEAL_HORIZON_MS` to 0 makes the reveal paint on arrival, which is how the baseline column was taken:
|
||||
|
||||
|
||||
+4
-1
@@ -589,7 +589,10 @@ host, kinds, and ids. Opening a cached workspace uses exact workspace and projec
|
||||
directory scan. One invalid row is deleted and returned as a miss without affecting other rows.
|
||||
An invalid directory row and its affected checkpoint cursor are repaired in one transaction, so a
|
||||
later launch cannot accept a checkpoint for a partial baseline. Directory changes and their
|
||||
checkpoint are also applied in one transaction.
|
||||
checkpoint are also applied in one transaction. Reads wait for accepted changes to reach storage,
|
||||
then retry only when a requested row changes during the read. Unrelated agent streams do not
|
||||
invalidate the read. Directory baseline replacements and host removal or renaming still invalidate
|
||||
the affected reads.
|
||||
|
||||
The cache is capped at 32 MiB and evicts whole hosts in least-recently-written order. Budget
|
||||
bookkeeping may scan opaque row sizes during a deferred write, never during host registry startup or
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { mkdtemp, rm, stat } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { mkdir, mkdtemp, rm, stat } from "node:fs/promises";
|
||||
import { homedir, tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { test, expect } from "../support/fixtures";
|
||||
import {
|
||||
@@ -12,12 +12,15 @@ import {
|
||||
chooseAddProjectMethod,
|
||||
expectAddProjectPage,
|
||||
expectNewWorkspaceForAddedProject,
|
||||
expectAddProjectResultVisible,
|
||||
navigateAddProjectResults,
|
||||
openAddProjectFlow,
|
||||
openAddProjectHostSelection,
|
||||
} from "../support/helpers/add-project-flow";
|
||||
import { gotoAppShell } from "../support/helpers/app";
|
||||
import {
|
||||
addConnectedHostAndReload,
|
||||
addConnectedHostsAndReload,
|
||||
addOfflineHostAndReload,
|
||||
waitForConnectedHost,
|
||||
} from "../support/helpers/hosts";
|
||||
@@ -214,6 +217,60 @@ test.describe("Add Project command-center flow", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("filtered hosts keep the keyboard-selected row visible", async ({ page }) => {
|
||||
const hosts: IsolatedHostDaemon[] = [];
|
||||
try {
|
||||
for (let index = 1; index <= 3; index += 1) {
|
||||
hosts.push(await startIsolatedHostDaemon(`scroll-host-${index}`));
|
||||
}
|
||||
await page.setViewportSize({ width: 1280, height: 360 });
|
||||
await gotoAppShell(page);
|
||||
await addConnectedHostsAndReload(
|
||||
page,
|
||||
hosts.map((host, index) => ({
|
||||
serverId: host.serverId,
|
||||
port: host.port,
|
||||
label: index < 2 ? `Fleet 0${index + 1}` : "Other host",
|
||||
})),
|
||||
{ primaryLabel: "Fleet 00" },
|
||||
);
|
||||
for (const host of hosts) {
|
||||
await waitForConnectedHost(page, {
|
||||
serverId: host.serverId,
|
||||
endpoint: `localhost:${host.port}`,
|
||||
});
|
||||
}
|
||||
await openAddProjectHostSelection(page);
|
||||
await expect(
|
||||
addProjectFlow(page).getByRole("button").filter({ hasText: "Other host" }),
|
||||
).toBeVisible();
|
||||
|
||||
await addProjectFlowInput(page).fill("Fleet");
|
||||
await expect(addProjectFlowHost(page, hosts[2]!.serverId)).toHaveCount(0);
|
||||
await navigateAddProjectResults(page, "ArrowDown", 2);
|
||||
await expectAddProjectResultVisible(page, "Fleet 02");
|
||||
|
||||
// Filtering out the first host moves retained rows to new positions.
|
||||
await addProjectFlowInput(page).fill("scroll-host");
|
||||
await expect(addProjectFlowHost(page, getServerId())).toHaveCount(0);
|
||||
await expectAddProjectResultVisible(page, "Fleet 01");
|
||||
await navigateAddProjectResults(page, "ArrowDown", 2);
|
||||
await expectAddProjectResultVisible(page, "Other host");
|
||||
await navigateAddProjectResults(page, "ArrowDown", 1);
|
||||
await expectAddProjectResultVisible(page, "Fleet 01");
|
||||
|
||||
await addProjectFlowInput(page).fill("Fleet");
|
||||
await expectAddProjectResultVisible(page, "Fleet 00");
|
||||
await navigateAddProjectResults(page, "ArrowDown", 2);
|
||||
await expectAddProjectResultVisible(page, "Fleet 02");
|
||||
await page.keyboard.press("Enter");
|
||||
await expectAddProjectPage(page, "method");
|
||||
await expect(addProjectFlow(page)).toContainText("Fleet 02");
|
||||
} finally {
|
||||
await Promise.all(hosts.map((host) => host.close()));
|
||||
}
|
||||
});
|
||||
|
||||
test("keyboard directory search adds the selected Project", async ({
|
||||
page,
|
||||
projectPickerFixture,
|
||||
@@ -241,6 +298,59 @@ test.describe("Add Project command-center flow", () => {
|
||||
await expectProjectHasNoWorkspaces(projectId);
|
||||
});
|
||||
|
||||
test("keyboard navigation keeps the selected row inside the visible results", async ({
|
||||
page,
|
||||
}) => {
|
||||
const parentDirectory = await mkdtemp(path.join(homedir(), "paseo-e2e-scroll-"));
|
||||
const rowPath = (index: number) =>
|
||||
path.join(parentDirectory, `scroll-probe-${String(index).padStart(2, "0")}`);
|
||||
let projectId: string | null = null;
|
||||
try {
|
||||
await Promise.all(Array.from({ length: 16 }, (_, index) => mkdir(rowPath(index))));
|
||||
await gotoAppShell(page);
|
||||
await openAddProjectFlow(page);
|
||||
await chooseAddProjectMethod(page, "directory-search");
|
||||
await addProjectFlowInput(page).fill(path.basename(parentDirectory));
|
||||
const results = page.getByTestId("add-project-flow-results");
|
||||
await expect(results.getByRole("button", { name: /scroll-probe-/ })).toHaveCount(16, {
|
||||
timeout: 30_000,
|
||||
});
|
||||
|
||||
await navigateAddProjectResults(page, "ArrowDown", 12);
|
||||
await expectAddProjectResultVisible(page, rowPath(11));
|
||||
await navigateAddProjectResults(page, "ArrowUp", 12);
|
||||
await expectAddProjectResultVisible(page, parentDirectory);
|
||||
await navigateAddProjectResults(page, "ArrowUp", 1);
|
||||
await expectAddProjectResultVisible(page, rowPath(15));
|
||||
await navigateAddProjectResults(page, "ArrowDown", 1);
|
||||
await expectAddProjectResultVisible(page, parentDirectory);
|
||||
|
||||
await navigateAddProjectResults(page, "ArrowDown", 12);
|
||||
await expectAddProjectResultVisible(page, rowPath(11));
|
||||
await addProjectFlowInput(page).fill(`${path.basename(parentDirectory)}probe`);
|
||||
await expect(results.getByRole("button")).toHaveCount(16);
|
||||
await expectAddProjectResultVisible(page, rowPath(0));
|
||||
await navigateAddProjectResults(page, "ArrowDown", 12);
|
||||
await expectAddProjectResultVisible(page, rowPath(12));
|
||||
await addProjectFlowInput(page).fill(path.basename(parentDirectory));
|
||||
await expect(results.getByRole("button")).toHaveCount(17);
|
||||
await expectAddProjectResultVisible(page, parentDirectory);
|
||||
await navigateAddProjectResults(page, "ArrowDown", 12);
|
||||
await expectAddProjectResultVisible(page, rowPath(11));
|
||||
await page.keyboard.press("Enter");
|
||||
projectId = await expectOpenedProject(page, "scroll-probe-11");
|
||||
await expectNewWorkspaceForAddedProject(page, {
|
||||
serverId: getServerId(),
|
||||
projectId,
|
||||
projectName: "scroll-probe-11",
|
||||
projectPath: rowPath(11),
|
||||
});
|
||||
} finally {
|
||||
if (projectId) await removeCreatedProject(rowPath(11), projectId);
|
||||
await rm(parentDirectory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("a complete repository URL remains selectable without a GitHub search result", async ({
|
||||
page,
|
||||
}) => {
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
import { test, expect } from "../support/fixtures";
|
||||
import { awaitAssistantMessage } from "../support/helpers/agent-stream";
|
||||
import { startRunningMockAgent } from "../support/helpers/composer";
|
||||
import { startRunningMockAgent, submitMessage } from "../support/helpers/composer";
|
||||
import {
|
||||
seedLongMockAgentTimeline,
|
||||
openAgentTimeline,
|
||||
scrollTimelineUntilOlderHistoryIsReachable,
|
||||
scrollTimelineToNewestLoadedEdge,
|
||||
expectTimelinePromptVisible,
|
||||
} from "../support/helpers/timeline-pagination";
|
||||
import {
|
||||
sampleStreamFrames,
|
||||
summarizeStreamSmoothness,
|
||||
@@ -102,6 +109,40 @@ agentStreamPerfDescribe("Agent stream smoothness", () => {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps streaming work bounded after revealing older history", async ({ page }, testInfo) => {
|
||||
test.setTimeout(120_000);
|
||||
await page.addInitScript(() => {
|
||||
Reflect.set(globalThis, "__PASEO_RENDER_PROFILE_ENABLED__", true);
|
||||
});
|
||||
const agent = await seedLongMockAgentTimeline({ turns: 80, liveTurns: "thirty-minute-stream" });
|
||||
try {
|
||||
await openAgentTimeline(page, agent);
|
||||
await expect(page.getByRole("textbox", { name: "Message agent..." }).first()).toBeVisible();
|
||||
await scrollTimelineUntilOlderHistoryIsReachable(page, agent.oldestPrompt);
|
||||
await expectTimelinePromptVisible(page, agent.oldestPrompt);
|
||||
await scrollTimelineToNewestLoadedEdge(page);
|
||||
await submitMessage(page, "Stream a long answer after reading older messages.");
|
||||
await awaitAssistantMessage(page);
|
||||
|
||||
for (let sample = 0; sample < 3; sample += 1) {
|
||||
await page.evaluate(() => globalThis.__PASEO_RESET_RENDER_PROFILE__?.());
|
||||
const frames = await sampleStreamFrames(page, { sampleWindowMs: SAMPLE_WINDOW_MS });
|
||||
const smoothness = summarizeStreamSmoothness(frames, SAMPLE_WINDOW_MS);
|
||||
const react = summarizeReactCommits(await readStreamReactCommits(page));
|
||||
await testInfo.attach(`revealed-history-stream-${sample}`, {
|
||||
body: JSON.stringify({ smoothness, react }, null, 2),
|
||||
contentType: "application/json",
|
||||
});
|
||||
console.log(`[perf] Revealed history stream: ${JSON.stringify({ smoothness, react })}`);
|
||||
expect(smoothness.growthFrames).toBeGreaterThan(20);
|
||||
expect(react.count).toBeGreaterThan(20);
|
||||
expect(react.actualDurationP95Ms).toBeLessThan(REACT_COMMIT_P95_BUDGET_MS);
|
||||
}
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
async function readStreamReactCommits(
|
||||
|
||||
@@ -89,9 +89,11 @@ async function dismissStackedModelPickerWithBackdrop(page: Page) {
|
||||
.getByTestId("agent-controls-settings-list")
|
||||
.getByRole("button", { name: /Select model/ })
|
||||
.click();
|
||||
await expect(page.getByTestId("agent-controls-model-browser-sheet")).toBeVisible();
|
||||
await expect(page.getByTestId("agent-controls-model-browser-sheet")).toBeInViewport();
|
||||
await page.mouse.click(MOBILE_VIEWPORT.width / 2, 24);
|
||||
await expect(page.getByTestId("agent-controls-model-browser-sheet")).not.toBeVisible();
|
||||
// In CI, Gorhom retains the dismissed sheet below the viewport.
|
||||
// Dismissal is complete when it leaves the displayed surface.
|
||||
await expect(page.getByTestId("agent-controls-model-browser-sheet")).not.toBeInViewport();
|
||||
await expect(page.getByTestId("agent-controls-model-sheet")).toBeVisible();
|
||||
await expect(page.getByTestId("agent-controls-settings-list")).toBeVisible();
|
||||
}
|
||||
@@ -139,7 +141,7 @@ test.describe("mobile bottom sheet reopen", () => {
|
||||
await expect(sheet).toBeVisible();
|
||||
await expect(page.getByTestId("agent-controls-settings-list")).toBeVisible();
|
||||
await expect(page.getByTestId("agent-controls-model")).toContainText("Ten second stream");
|
||||
await expect(page.getByTestId("agent-controls-model-browser-sheet")).not.toBeVisible();
|
||||
await expect(page.getByTestId("agent-controls-model-browser-sheet")).not.toBeInViewport();
|
||||
});
|
||||
} finally {
|
||||
await session.cleanup();
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { expect, test, type Page } from "../support/fixtures";
|
||||
import {
|
||||
composerLocator,
|
||||
blurComposerInput,
|
||||
composerLocator,
|
||||
enterComposerFullscreen,
|
||||
exitComposerFullscreen,
|
||||
expectComposerDraft,
|
||||
@@ -25,6 +25,100 @@ import {
|
||||
swipeOpenMobileAgentSidebar,
|
||||
swipeOpenMobileExplorer,
|
||||
} from "../support/helpers/sidebar";
|
||||
import { readScrollMetrics } from "../support/helpers/agent-bottom-anchor";
|
||||
import {
|
||||
expectTimelinePromptPositionPreserved,
|
||||
rememberTimelinePromptPosition,
|
||||
seedLongMockAgentTimeline,
|
||||
waitForTimelineGeometryToSettle,
|
||||
} from "../support/helpers/timeline-pagination";
|
||||
|
||||
test("clicking chat text or background focuses the feed for keyboard paging", async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
const agent = await seedLongMockAgentTimeline({ turns: 8 });
|
||||
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
const composer = composerLocator(page);
|
||||
const feed = page.getByTestId("agent-chat-scroll").filter({ visible: true });
|
||||
await composer.fill("Keep this draft");
|
||||
await feed.getByText(agent.newestPrompt, { exact: true }).click();
|
||||
await expect(feed).toBeFocused();
|
||||
|
||||
const beforePaging = await readScrollMetrics(page);
|
||||
expect(beforePaging.offsetY).toBeGreaterThan(beforePaging.viewportHeight);
|
||||
await page.keyboard.press("PageUp");
|
||||
await expect
|
||||
.poll(async () => (await readScrollMetrics(page)).offsetY)
|
||||
.toBeLessThan(beforePaging.offsetY - beforePaging.viewportHeight / 2);
|
||||
await page.screenshot({ path: testInfo.outputPath("chat-keyboard-paging.png") });
|
||||
await page.keyboard.press("PageDown");
|
||||
await expect
|
||||
.poll(async () => (await readScrollMetrics(page)).distanceFromBottom)
|
||||
.toBeLessThanOrEqual(2);
|
||||
|
||||
await composer.click();
|
||||
await expectComposerFocused(page);
|
||||
await feed.click({ position: { x: 2, y: 40 } });
|
||||
await expect(feed).toBeFocused();
|
||||
await page.keyboard.press("PageUp");
|
||||
await expect
|
||||
.poll(async () => (await readScrollMetrics(page)).distanceFromBottom)
|
||||
.toBeGreaterThan(beforePaging.viewportHeight / 2);
|
||||
await waitForTimelineGeometryToSettle(page);
|
||||
const readingPrompt = agent.prompts[4];
|
||||
await expect(feed.getByText(readingPrompt, { exact: true })).toBeInViewport();
|
||||
const readingPosition = await rememberTimelinePromptPosition(page, readingPrompt);
|
||||
await agent.client.sendAgentMessage(agent.agentId, "emit 2 coalesced agent stream updates");
|
||||
await agent.client.waitForFinish(agent.agentId, 15_000);
|
||||
// The daemon finishing does not mean its response has reached the browser.
|
||||
await expect(feed.getByText(/stress-update-1/)).toHaveCount(1);
|
||||
await waitForTimelineGeometryToSettle(page);
|
||||
await expectTimelinePromptPositionPreserved(page, readingPosition);
|
||||
await expectComposerDraft(page, "Keep this draft");
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("focusing the feed preserves assistant text selection and code copy controls", async ({
|
||||
page,
|
||||
context,
|
||||
}) => {
|
||||
const sentence = "Select this assistant sentence.";
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "chat-focus-selection-",
|
||||
title: "Chat focus selection",
|
||||
initialPrompt: "Render text and code.",
|
||||
featureValues: {
|
||||
mockAssistantResponse: `${sentence}\n\n\`\`\`bash\necho example\n\`\`\``,
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
|
||||
await agent.client.waitForFinish(agent.agentId, 15_000);
|
||||
await openAgentRoute(page, agent);
|
||||
await composerLocator(page).fill("Keep this draft");
|
||||
|
||||
const feed = page.getByTestId("agent-chat-scroll").filter({ visible: true });
|
||||
await feed.getByText(sentence, { exact: true }).click({ clickCount: 3 });
|
||||
await expect(feed).toBeFocused();
|
||||
expect(await page.evaluate(() => window.getSelection()?.toString().trim())).toBe(sentence);
|
||||
await page.keyboard.press("ControlOrMeta+c");
|
||||
expect((await page.evaluate(() => navigator.clipboard.readText())).trim()).toBe(sentence);
|
||||
|
||||
const code = feed.locator('[data-paseo-markdown-language="bash"]');
|
||||
await code.hover();
|
||||
await code.locator("[data-paseo-markdown-ignore]").click();
|
||||
await expect(feed).not.toBeFocused();
|
||||
expect(await page.evaluate(() => navigator.clipboard.readText())).toBe("echo example");
|
||||
await expectComposerDraft(page, "Keep this draft");
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("submitting a message leaves the composer ready for the next message", async ({ page }) => {
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import path from "node:path";
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import { expect, test, type Page } from "../support/fixtures";
|
||||
import { gotoAppShell, openSettings } from "../support/helpers/app";
|
||||
import {
|
||||
closeModelPicker,
|
||||
drillIntoProvider,
|
||||
openModelPicker,
|
||||
} from "../support/helpers/agent-profiles";
|
||||
import { expectComposerVisible, expectComposerFocused } from "../support/helpers/composer";
|
||||
import { connectDaemonClient } from "../support/helpers/daemon-client-loader";
|
||||
import { clickNewChat, gotoWorkspace } from "../support/helpers/launcher";
|
||||
import { getServerId } from "../support/helpers/server-id";
|
||||
import { openSettingsHost, openSettingsHostSection } from "../support/helpers/settings";
|
||||
|
||||
// Use an existing repository linked to the signed-in user's Hoplite project.
|
||||
const cwd = process.env.E2E_HOPLITE_CWD ?? path.resolve(__dirname, "../../../..");
|
||||
|
||||
test.use({
|
||||
viewport: { width: 1440, height: 1000 },
|
||||
e2eDaemonConfig: { version: 1, agents: { providers: { hoplite: { enabled: true } } } },
|
||||
});
|
||||
|
||||
async function openHopliteSettings(page: Page): Promise<void> {
|
||||
await gotoAppShell(page);
|
||||
await openSettings(page);
|
||||
await openSettingsHost(page, getServerId());
|
||||
await openSettingsHostSection(page, getServerId(), "providers");
|
||||
await page.getByRole("button", { name: "Hoplite provider details", exact: true }).click();
|
||||
}
|
||||
|
||||
async function expectEmptyGlobalCatalog(page: Page, client: DaemonClient): Promise<void> {
|
||||
const models = await client.listProviderModels("hoplite");
|
||||
expect(models.error).toBeNull();
|
||||
expect(models.models).toEqual([]);
|
||||
const snapshot = await client.getProvidersSnapshot();
|
||||
expect(snapshot.entries.find((entry) => entry.provider === "hoplite")).toMatchObject({
|
||||
status: "ready",
|
||||
models: [],
|
||||
});
|
||||
await expect(page.getByText("No models detected", { exact: true })).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: "Retry", exact: true })).toHaveCount(0);
|
||||
}
|
||||
|
||||
async function refreshGlobalCatalog(page: Page): Promise<void> {
|
||||
await page.getByRole("button", { name: "Refresh", exact: true }).click();
|
||||
await expect(page.getByRole("button", { name: "Refresh", exact: true })).toBeEnabled({
|
||||
timeout: 120_000,
|
||||
});
|
||||
}
|
||||
|
||||
async function openWorkspaceModels(page: Page, workspaceId: string): Promise<void> {
|
||||
await gotoWorkspace(page, workspaceId);
|
||||
await clickNewChat(page);
|
||||
await expectComposerVisible(page);
|
||||
await expectComposerFocused(page);
|
||||
await openModelPicker(page);
|
||||
await page.getByTestId("sheet-header-back").click();
|
||||
await drillIntoProvider(page, "hoplite");
|
||||
}
|
||||
|
||||
test("real Hoplite has an empty global catalog and discovers models in its linked workspace", async ({
|
||||
page,
|
||||
e2eWorkerClient,
|
||||
}, testInfo) => {
|
||||
test.setTimeout(180_000);
|
||||
const client = await connectDaemonClient<DaemonClient>({ clientIdPrefix: "hoplite-discovery" });
|
||||
const created = await e2eWorkerClient.createWorkspace({
|
||||
source: { kind: "directory", path: cwd },
|
||||
title: "Hoplite discovery QA",
|
||||
});
|
||||
expect(created.error).toBeNull();
|
||||
const workspace = created.workspace!;
|
||||
try {
|
||||
await test.step("global settings succeed with no models, including refresh", async () => {
|
||||
await openHopliteSettings(page);
|
||||
await expectEmptyGlobalCatalog(page, client);
|
||||
await refreshGlobalCatalog(page);
|
||||
await expectEmptyGlobalCatalog(page, client);
|
||||
await page.screenshot({ path: testInfo.outputPath("hoplite-global-empty.png") });
|
||||
});
|
||||
|
||||
await test.step("the linked workspace discovers real models", async () => {
|
||||
const models = await client.listProviderModels("hoplite", { cwd });
|
||||
expect(models.error).toBeNull();
|
||||
expect(models.models!.length).toBeGreaterThan(0);
|
||||
await testInfo.attach("workspace-models", {
|
||||
body: JSON.stringify(models, null, 2),
|
||||
contentType: "application/json",
|
||||
});
|
||||
await openWorkspaceModels(page, workspace.id);
|
||||
await expect(page.getByText(models.models![0]!.label, { exact: true }).last()).toBeVisible();
|
||||
await page.screenshot({ path: testInfo.outputPath("hoplite-workspace-models.png") });
|
||||
await closeModelPicker(page);
|
||||
});
|
||||
|
||||
await test.step("workspace discovery does not populate the global catalog", async () => {
|
||||
await openHopliteSettings(page);
|
||||
await expectEmptyGlobalCatalog(page, client);
|
||||
await refreshGlobalCatalog(page);
|
||||
await expectEmptyGlobalCatalog(page, client);
|
||||
const models = await client.listProviderModels("hoplite", { cwd });
|
||||
expect(models.error).toBeNull();
|
||||
expect(models.models!.length).toBeGreaterThan(0);
|
||||
});
|
||||
} finally {
|
||||
await client.close();
|
||||
await e2eWorkerClient.removeProject(workspace.projectId);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
import { expect, test, type Page } from "../support/fixtures";
|
||||
import { composerLocator, submitMessageWithButton } from "../support/helpers/composer";
|
||||
import { seedMockAgentWorkspace, openAgentRoute } from "../support/helpers/mock-agent";
|
||||
import { withPopoverTimelinePlugin } from "../support/helpers/plugin-timeline";
|
||||
|
||||
async function openPreviewWhileTyping(page: Page): Promise<void> {
|
||||
await composerLocator(page).focus();
|
||||
await page.getByRole("button", { name: "Hover plugin preview", exact: true }).hover();
|
||||
await expect(page.getByRole("dialog", { name: "Plugin preview" })).toBeVisible();
|
||||
await expect(composerLocator(page)).toBeFocused();
|
||||
}
|
||||
|
||||
async function dismissPreview(page: Page): Promise<void> {
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(page.getByRole("dialog", { name: "Plugin preview" })).not.toBeVisible();
|
||||
}
|
||||
|
||||
test("Escape dismisses a plugin preview before interrupting the agent", async ({ page }) => {
|
||||
test.setTimeout(120_000);
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "plugin-popover-",
|
||||
title: "Plugin preview keyboard regression",
|
||||
model: "e2e-fast-stream",
|
||||
});
|
||||
try {
|
||||
await withPopoverTimelinePlugin(async () => {
|
||||
await openAgentRoute(page, agent);
|
||||
await submitMessageWithButton(page, "Show the plugin preview.");
|
||||
await agent.client.waitForFinish(agent.agentId, 30_000);
|
||||
await expect(page.getByRole("button", { name: "Hover plugin preview" })).toBeVisible();
|
||||
await submitMessageWithButton(page, "withhold synthetic user message until interrupted");
|
||||
const stop = page.getByRole("button", { name: "Stop agent", exact: true });
|
||||
await expect(stop).toBeVisible();
|
||||
|
||||
await openPreviewWhileTyping(page);
|
||||
await dismissPreview(page);
|
||||
await expect(stop).toBeVisible();
|
||||
await expect(composerLocator(page)).toBeFocused();
|
||||
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(stop).not.toBeVisible();
|
||||
await agent.client.waitForFinish(agent.agentId, 15_000);
|
||||
});
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
@@ -100,6 +100,40 @@ function weeklyReport(sourceId: string, usedPct: number): UsageReportEntry {
|
||||
};
|
||||
}
|
||||
|
||||
function installReversedUsageRefresh(page: Page) {
|
||||
const initial = [weeklyReport("opencode", 31), weeklyReport("openai", 12)];
|
||||
const refreshed = [weeklyReport("openai", 22), weeklyReport("opencode", 41)];
|
||||
return installUsageReportsFixture(page, {
|
||||
lists: [(request) => (request.forceRefresh ? refreshed : initial)],
|
||||
});
|
||||
}
|
||||
|
||||
async function openUsageSummaryAtWidth(page: Page, width: number) {
|
||||
await page.setViewportSize({ width, height: 900 });
|
||||
await gotoAppShell(page);
|
||||
if (width === 390) await openCompactSidebar(page);
|
||||
await expectPinnedUsage(page, ["31% Weekly", "12% Weekly"]);
|
||||
await openUsageFromItem(page);
|
||||
}
|
||||
|
||||
async function expectUsageProviderOrder(page: Page, summary: string[]) {
|
||||
const group = page.getByTestId(`usage-host-${getServerId()}`);
|
||||
await expect(group.getByText(/^(opencode|openai) plan$/)).toHaveText([
|
||||
"opencode plan",
|
||||
"openai plan",
|
||||
]);
|
||||
await expectPinnedUsage(page, summary);
|
||||
}
|
||||
|
||||
async function refreshUsageAndWaitForReports(page: Page, usage: UsageReportsFixture) {
|
||||
const requestCount = usage.listRequests().length;
|
||||
await refreshAllUsage(page);
|
||||
await usage.waitForListRequests(requestCount + 1);
|
||||
const group = page.getByTestId(`usage-host-${getServerId()}`);
|
||||
await expect(group.getByText("41%", { exact: true })).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: "Refresh all", exact: true })).toBeEnabled();
|
||||
}
|
||||
|
||||
test.describe("usage modal", () => {
|
||||
test("opens from the sidebar on the host's reports, with no host filter for one host", async ({
|
||||
page,
|
||||
@@ -152,6 +186,21 @@ test.describe("usage modal", () => {
|
||||
await expect(group.getByTestId("usage-freshness")).toHaveCount(0);
|
||||
});
|
||||
|
||||
for (const width of [1440, 390]) {
|
||||
test(`keeps sidebar and modal provider order across a reversed refresh at width ${width}`, async ({
|
||||
page,
|
||||
}) => {
|
||||
const usage = await installReversedUsageRefresh(page);
|
||||
await openUsageSummaryAtWidth(page, width);
|
||||
await expectUsageProviderOrder(page, ["31% Weekly", "12% Weekly"]);
|
||||
await qaScreenshot(page, `usage-order-${width}-before-refresh`);
|
||||
|
||||
await refreshUsageAndWaitForReports(page, usage);
|
||||
await expectUsageProviderOrder(page, ["41% Weekly", "22% Weekly"]);
|
||||
await qaScreenshot(page, `usage-order-${width}-after-refresh`);
|
||||
});
|
||||
}
|
||||
|
||||
test("refreshes one report from its card", async ({ page }) => {
|
||||
test.setTimeout(120_000);
|
||||
const serverId = getServerId();
|
||||
|
||||
@@ -30,7 +30,7 @@ import {
|
||||
openUsageFromIcon,
|
||||
openUsageFromItem,
|
||||
pinRow,
|
||||
scrollUsage,
|
||||
scrollUsageToWindow,
|
||||
setSummaryInSidebar,
|
||||
openUsageOptions,
|
||||
showUsageAs,
|
||||
@@ -146,7 +146,9 @@ test.describe("Usage item", () => {
|
||||
compact: { viewport: COMPACT, showSidebar: openCompactSidebar },
|
||||
};
|
||||
for (const [size, { viewport, showSidebar }] of Object.entries(layouts)) {
|
||||
test(`long usage reports scroll to the final window on ${size}`, async ({ page }) => {
|
||||
test(`long usage reports scroll between their first and last windows on ${size}`, async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(120_000);
|
||||
const source = await installTallUsageSource();
|
||||
try {
|
||||
@@ -161,10 +163,10 @@ test.describe("Usage item", () => {
|
||||
await waitForSettledPosition(content);
|
||||
await expect(content.getByText("Window 20", { exact: true })).not.toBeInViewport();
|
||||
await qaScreenshot(page, `${size}-usage-scroll-top`);
|
||||
await scrollUsage(page, 5_000);
|
||||
await scrollUsageToWindow(page, "Window 20");
|
||||
await expect(content.getByText("Window 20", { exact: true })).toBeInViewport();
|
||||
await qaScreenshot(page, `${size}-usage-scroll-bottom`);
|
||||
await scrollUsage(page, -5_000);
|
||||
await scrollUsageToWindow(page, "Window 1");
|
||||
await expect(content.getByText("Window 20", { exact: true })).not.toBeInViewport();
|
||||
} finally {
|
||||
await source.cleanup();
|
||||
|
||||
@@ -90,3 +90,26 @@ export async function expectNewWorkspaceForAddedProject(
|
||||
{ timeout: 30_000 },
|
||||
);
|
||||
}
|
||||
|
||||
export async function navigateAddProjectResults(
|
||||
page: Page,
|
||||
key: "ArrowDown" | "ArrowUp",
|
||||
count: number,
|
||||
): Promise<void> {
|
||||
for (let index = 0; index < count; index += 1) await page.keyboard.press(key);
|
||||
}
|
||||
|
||||
export async function expectAddProjectResultVisible(page: Page, text: string): Promise<void> {
|
||||
const results = page.getByTestId("add-project-flow-results");
|
||||
const row = results.getByRole("button").filter({ has: page.getByText(text, { exact: true }) });
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const viewport = await results.boundingBox();
|
||||
const bounds = await row.boundingBox();
|
||||
if (!viewport || !bounds) return false;
|
||||
return (
|
||||
bounds.y >= viewport.y - 1 && bounds.y + bounds.height <= viewport.y + viewport.height + 1
|
||||
);
|
||||
})
|
||||
.toBe(true);
|
||||
}
|
||||
|
||||
@@ -231,3 +231,46 @@ export async function attachPromptTimelineEvidence(page: Page, info: TestInfo):
|
||||
contentType: "image/png",
|
||||
});
|
||||
}
|
||||
|
||||
const POPOVER_CLIENT_SOURCE = `import React, { useEffect, useRef } from "react";
|
||||
import { z } from "zod";
|
||||
|
||||
function Preview() {
|
||||
const panel = useRef(null);
|
||||
useEffect(() => {
|
||||
const close = (event) => {
|
||||
if (event.key === "Escape" && panel.current.matches(":popover-open")) {
|
||||
panel.current.hidePopover();
|
||||
}
|
||||
};
|
||||
document.addEventListener("keydown", close, true);
|
||||
return () => document.removeEventListener("keydown", close, true);
|
||||
}, []);
|
||||
return <div>
|
||||
<button onMouseEnter={() => panel.current.showPopover()}>Hover plugin preview</button>
|
||||
<div ref={panel} popover="manual" role="dialog" aria-label="Plugin preview">Plugin hover preview</div>
|
||||
</div>;
|
||||
}
|
||||
|
||||
export default function contribute(client) {
|
||||
client.addTimelineTransformer({
|
||||
id: "preview", query: { itemType: "user_message" },
|
||||
transform({ item }) {
|
||||
if (item.text !== "Show the plugin preview.") return;
|
||||
return { items: [{ type: "plugin", kind: "preview", version: 1, data: {} }] };
|
||||
},
|
||||
});
|
||||
client.addTimelineRenderer({
|
||||
kind: "preview", version: 1, schema: z.object({}), Component: Preview,
|
||||
});
|
||||
return () => {};
|
||||
}`;
|
||||
|
||||
/** Installs a timeline preview that owns Escape through the DOM Popover API. */
|
||||
export async function withPopoverTimelinePlugin(run: () => Promise<void>): Promise<void> {
|
||||
await withDirectoryPlugin({
|
||||
pluginId: "timeline-popover-e2e",
|
||||
source: POPOVER_CLIENT_SOURCE,
|
||||
run,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -544,7 +544,7 @@ async function readTimelineViewport(page: Page): Promise<TimelineViewportSnapsho
|
||||
});
|
||||
}
|
||||
|
||||
async function waitForTimelineGeometryToSettle(page: Page): Promise<void> {
|
||||
export async function waitForTimelineGeometryToSettle(page: Page): Promise<void> {
|
||||
const scroll = page.locator('[data-testid="agent-chat-scroll"]:visible').first();
|
||||
await scroll.evaluate(
|
||||
(element) =>
|
||||
|
||||
@@ -212,6 +212,14 @@ export async function scrollUsage(page: Page, deltaY: number): Promise<void> {
|
||||
await page.mouse.wheel(0, deltaY);
|
||||
}
|
||||
|
||||
/** Reach a window with the wheel even when other reports follow its card. */
|
||||
export async function scrollUsageToWindow(page: Page, label: string): Promise<void> {
|
||||
const target = await usageModal(page).getByText(label, { exact: true }).boundingBox();
|
||||
const viewport = page.viewportSize();
|
||||
if (!target || !viewport) throw new Error("Usage window must exist before scrolling to it.");
|
||||
await scrollUsage(page, target.y + target.height / 2 - viewport.height / 2);
|
||||
}
|
||||
|
||||
/** The modal's own Close button. */
|
||||
export async function closeUsage(page: Page): Promise<void> {
|
||||
await visible(page, "usage-modal").getByRole("button", { name: "Close", exact: true }).click();
|
||||
|
||||
@@ -2,6 +2,9 @@ import type { ReactNode, RefObject } from "react";
|
||||
import type { StreamItem } from "@/types/stream";
|
||||
import type { StreamViewportHandle } from "../strategy";
|
||||
|
||||
export interface MountedMessageIds {
|
||||
has(messageId: string): boolean;
|
||||
}
|
||||
export interface ChatFindProps {
|
||||
agentId: string;
|
||||
serverId: string;
|
||||
@@ -9,7 +12,7 @@ export interface ChatFindProps {
|
||||
items: StreamItem[];
|
||||
viewportRef: RefObject<StreamViewportHandle | null>;
|
||||
revealLoadedMessage(messageId: string): boolean;
|
||||
visibleMessageIds: ReadonlySet<string>;
|
||||
visibleMessageIds: MountedMessageIds;
|
||||
children: ReactNode;
|
||||
}
|
||||
export interface ChatFindExpansionProps {
|
||||
|
||||
@@ -178,7 +178,7 @@ describe("useChatOutline", () => {
|
||||
timelineEpoch,
|
||||
enabled,
|
||||
viewportRef,
|
||||
visibleMessageIds: new Set(),
|
||||
mountedHistoryMessageIds: new Set(),
|
||||
onJumpError: vi.fn(),
|
||||
}),
|
||||
{
|
||||
@@ -278,7 +278,7 @@ describe("useChatOutline", () => {
|
||||
},
|
||||
];
|
||||
const { result, rerender } = renderHook(
|
||||
({ visibleMessageIds }) =>
|
||||
({ mountedHistoryMessageIds }) =>
|
||||
useChatOutline({
|
||||
agentId: "agent-1",
|
||||
serverId: "server-1",
|
||||
@@ -288,10 +288,10 @@ describe("useChatOutline", () => {
|
||||
enabled: true,
|
||||
viewportRef,
|
||||
onJumpError: vi.fn(),
|
||||
visibleMessageIds,
|
||||
mountedHistoryMessageIds,
|
||||
revealLoadedMessage,
|
||||
}),
|
||||
{ initialProps: { visibleMessageIds: new Set<string>() } },
|
||||
{ initialProps: { mountedHistoryMessageIds: new Set<string>() } },
|
||||
);
|
||||
|
||||
await waitFor(() => expect(result.current.prompts).toHaveLength(1));
|
||||
@@ -299,7 +299,7 @@ describe("useChatOutline", () => {
|
||||
expect(revealLoadedMessage).toHaveBeenCalledWith("older-prompt");
|
||||
expect(scrollToMessage).not.toHaveBeenCalled();
|
||||
|
||||
rerender({ visibleMessageIds: new Set(["older-prompt"]) });
|
||||
rerender({ mountedHistoryMessageIds: new Set(["older-prompt"]) });
|
||||
await waitFor(() => expect(scrollToMessage).toHaveBeenCalledWith("older-prompt"));
|
||||
});
|
||||
|
||||
@@ -327,7 +327,7 @@ describe("useChatOutline", () => {
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1 },
|
||||
};
|
||||
const { result, rerender } = renderHook(
|
||||
({ tail, visibleMessageIds }) =>
|
||||
({ tail, mountedHistoryMessageIds }) =>
|
||||
useChatOutline({
|
||||
agentId: "agent-1",
|
||||
serverId: "server-1",
|
||||
@@ -337,13 +337,13 @@ describe("useChatOutline", () => {
|
||||
enabled: true,
|
||||
viewportRef,
|
||||
onJumpError: vi.fn(),
|
||||
visibleMessageIds,
|
||||
mountedHistoryMessageIds,
|
||||
revealLoadedMessage,
|
||||
}),
|
||||
{
|
||||
initialProps: {
|
||||
tail: [] as (typeof fetchedPrompt)[],
|
||||
visibleMessageIds: new Set<string>(),
|
||||
mountedHistoryMessageIds: new Set<string>(),
|
||||
},
|
||||
},
|
||||
);
|
||||
@@ -352,11 +352,11 @@ describe("useChatOutline", () => {
|
||||
act(() => result.current.jumpToPrompt(1));
|
||||
await waitFor(() => expect(runtime.fetchAgentTimeline).toHaveBeenCalledOnce());
|
||||
|
||||
rerender({ tail: [fetchedPrompt], visibleMessageIds: new Set<string>() });
|
||||
rerender({ tail: [fetchedPrompt], mountedHistoryMessageIds: new Set<string>() });
|
||||
await waitFor(() => expect(revealLoadedMessage).toHaveBeenCalledWith(fetchedPrompt.id));
|
||||
expect(scrollToMessage).not.toHaveBeenCalled();
|
||||
|
||||
rerender({ tail: [fetchedPrompt], visibleMessageIds: new Set([fetchedPrompt.id]) });
|
||||
rerender({ tail: [fetchedPrompt], mountedHistoryMessageIds: new Set([fetchedPrompt.id]) });
|
||||
await waitFor(() => expect(scrollToMessage).toHaveBeenCalledOnce());
|
||||
expect(scrollToMessage).toHaveBeenCalledWith(fetchedPrompt.id);
|
||||
await act(async () => fetch.resolve());
|
||||
@@ -392,7 +392,7 @@ describe("useChatOutline", () => {
|
||||
enabled: true,
|
||||
viewportRef: { current: viewport },
|
||||
onJumpError: vi.fn(),
|
||||
visibleMessageIds: new Set([livePrompt.id]),
|
||||
mountedHistoryMessageIds: new Set<string>(),
|
||||
revealLoadedMessage,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react";
|
||||
import { useEffect, useMemo, useRef, useState, type RefObject } from "react";
|
||||
import type { AgentTimelinePromptIndexPayload } from "@getpaseo/client/internal/daemon-client";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { useStableEvent } from "@/hooks/use-stable-event";
|
||||
@@ -33,7 +33,8 @@ export interface UseChatOutlineInput {
|
||||
enabled: boolean;
|
||||
viewportRef: RefObject<StreamViewportHandle | null>;
|
||||
onJumpError: () => void;
|
||||
visibleMessageIds?: ReadonlySet<string>;
|
||||
// Message ids of the history the viewport has mounted. Live head messages are always mounted.
|
||||
mountedHistoryMessageIds?: ReadonlySet<string>;
|
||||
revealLoadedMessage?: (messageId: string) => boolean;
|
||||
}
|
||||
|
||||
@@ -44,6 +45,24 @@ export interface ChatOutline {
|
||||
reportReadingPosition: (seq: number | null) => void;
|
||||
}
|
||||
|
||||
function latestPromptSeqIn(items: StreamItem[], timelineEpoch: string | null): number {
|
||||
let latest = -1;
|
||||
for (const item of items) {
|
||||
if (item.kind === "user_message" && item.timelineCursor?.epoch === timelineEpoch) {
|
||||
latest = Math.max(latest, item.timelineCursor.seq);
|
||||
}
|
||||
}
|
||||
return latest;
|
||||
}
|
||||
|
||||
function findLoadedItem(
|
||||
tail: StreamItem[],
|
||||
head: StreamItem[],
|
||||
predicate: (item: StreamItem) => boolean,
|
||||
): StreamItem | undefined {
|
||||
return tail.find(predicate) ?? head.find(predicate);
|
||||
}
|
||||
|
||||
export function useChatOutline({
|
||||
agentId,
|
||||
serverId,
|
||||
@@ -53,7 +72,7 @@ export function useChatOutline({
|
||||
enabled,
|
||||
viewportRef,
|
||||
onJumpError,
|
||||
visibleMessageIds,
|
||||
mountedHistoryMessageIds,
|
||||
revealLoadedMessage,
|
||||
}: UseChatOutlineInput): ChatOutline {
|
||||
const [index, setIndex] = useState<AgentTimelinePromptIndexPayload | null>(null);
|
||||
@@ -62,18 +81,19 @@ export function useChatOutline({
|
||||
const readingSeqRef = useRef<number | null>(null);
|
||||
const nextJumpRequestIdRef = useRef(0);
|
||||
const nextIndexRequestIdRef = useRef(0);
|
||||
const loadedItems = useMemo(() => [...tail, ...(head ?? NO_STREAM_ITEMS)], [head, tail]);
|
||||
// A disabled outline (every native viewport) must not pay for the timeline per delta.
|
||||
const loadedTail = enabled ? tail : NO_STREAM_ITEMS;
|
||||
const loadedHead = enabled ? (head ?? NO_STREAM_ITEMS) : NO_STREAM_ITEMS;
|
||||
const prompts = enabled ? (index?.prompts ?? NO_PROMPTS) : NO_PROMPTS;
|
||||
|
||||
// The viewed timeline already owns live delivery and reconnect catch-up. Its complete
|
||||
// loaded items (including rows outside the mounted window) invalidate the prompt index.
|
||||
const latestPromptSeq = loadedItems.reduce(
|
||||
(latest, item) =>
|
||||
item.kind === "user_message" && item.timelineCursor?.epoch === timelineEpoch
|
||||
? Math.max(latest, item.timelineCursor.seq)
|
||||
: latest,
|
||||
-1,
|
||||
// Only the head changes per streamed delta, so the tail's contribution is memoized.
|
||||
const tailPromptSeq = useMemo(
|
||||
() => latestPromptSeqIn(loadedTail, timelineEpoch),
|
||||
[loadedTail, timelineEpoch],
|
||||
);
|
||||
const latestPromptSeq = Math.max(tailPromptSeq, latestPromptSeqIn(loadedHead, timelineEpoch));
|
||||
|
||||
useEffect(() => setIndex(null), [agentId, enabled, serverId, timelineEpoch]);
|
||||
|
||||
@@ -135,10 +155,18 @@ export function useChatOutline({
|
||||
|
||||
useEffect(() => {
|
||||
if (pendingJump === null) return;
|
||||
const target = loadedItems.find((item) => item.timelineCursor?.seq === pendingJump.seq);
|
||||
const target = findLoadedItem(
|
||||
loadedTail,
|
||||
loadedHead,
|
||||
(item) => item.timelineCursor?.seq === pendingJump.seq,
|
||||
);
|
||||
if (target) {
|
||||
if (pendingJump.hasScrolled) return;
|
||||
if (visibleMessageIds?.has(target.id) === false) {
|
||||
const isMounted =
|
||||
mountedHistoryMessageIds === undefined ||
|
||||
mountedHistoryMessageIds.has(target.id) ||
|
||||
loadedHead.includes(target);
|
||||
if (!isMounted) {
|
||||
revealLoadedMessage?.(target.id);
|
||||
return;
|
||||
}
|
||||
@@ -150,40 +178,48 @@ export function useChatOutline({
|
||||
return;
|
||||
}
|
||||
if (pendingJump.fetchSettled) setPendingJump(null);
|
||||
}, [loadedItems, pendingJump, revealLoadedMessage, viewportRef, visibleMessageIds]);
|
||||
}, [
|
||||
loadedHead,
|
||||
loadedTail,
|
||||
mountedHistoryMessageIds,
|
||||
pendingJump,
|
||||
revealLoadedMessage,
|
||||
viewportRef,
|
||||
]);
|
||||
|
||||
const jumpToPrompt = useCallback(
|
||||
(seq: number) => {
|
||||
nextJumpRequestIdRef.current += 1;
|
||||
setPendingJump(null);
|
||||
const loaded = loadedItems.find((item) => item.timelineCursor?.seq === seq);
|
||||
if (loaded) {
|
||||
if (revealLoadedMessage?.(loaded.id)) {
|
||||
const requestId = nextJumpRequestIdRef.current;
|
||||
setPendingJump({ requestId, seq, fetchSettled: true, hasScrolled: false });
|
||||
return;
|
||||
}
|
||||
viewportRef.current?.scrollToMessage?.(loaded.id);
|
||||
const jumpToPrompt = useStableEvent((seq: number) => {
|
||||
nextJumpRequestIdRef.current += 1;
|
||||
setPendingJump(null);
|
||||
const loaded = findLoadedItem(
|
||||
loadedTail,
|
||||
loadedHead,
|
||||
(item) => item.timelineCursor?.seq === seq,
|
||||
);
|
||||
if (loaded) {
|
||||
if (revealLoadedMessage?.(loaded.id)) {
|
||||
const requestId = nextJumpRequestIdRef.current;
|
||||
setPendingJump({ requestId, seq, fetchSettled: true, hasScrolled: false });
|
||||
return;
|
||||
}
|
||||
if (!index) return;
|
||||
const requestId = nextJumpRequestIdRef.current;
|
||||
setPendingJump({ requestId, seq, fetchSettled: false, hasScrolled: false });
|
||||
void getHostRuntimeStore()
|
||||
.fetchAgentTimeline(serverId, agentId, planTimelinePromptJump({ epoch: index.epoch, seq }))
|
||||
.catch((error: unknown) => {
|
||||
console.warn("Failed to load a Chat outline window", error);
|
||||
onJumpError();
|
||||
})
|
||||
.finally(() => {
|
||||
setPendingJump((current) => {
|
||||
if (current?.requestId !== requestId) return current;
|
||||
return { ...current, fetchSettled: true };
|
||||
});
|
||||
viewportRef.current?.scrollToMessage?.(loaded.id);
|
||||
return;
|
||||
}
|
||||
if (!index) return;
|
||||
const requestId = nextJumpRequestIdRef.current;
|
||||
setPendingJump({ requestId, seq, fetchSettled: false, hasScrolled: false });
|
||||
void getHostRuntimeStore()
|
||||
.fetchAgentTimeline(serverId, agentId, planTimelinePromptJump({ epoch: index.epoch, seq }))
|
||||
.catch((error: unknown) => {
|
||||
console.warn("Failed to load a Chat outline window", error);
|
||||
onJumpError();
|
||||
})
|
||||
.finally(() => {
|
||||
setPendingJump((current) => {
|
||||
if (current?.requestId !== requestId) return current;
|
||||
return { ...current, fetchSettled: true };
|
||||
});
|
||||
},
|
||||
[agentId, index, loadedItems, onJumpError, revealLoadedMessage, serverId, viewportRef],
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
return { prompts, activePrompt, jumpToPrompt, reportReadingPosition };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { setFlagsFromString } from "node:v8";
|
||||
import { runInNewContext } from "node:vm";
|
||||
import { buildAgentStreamRenderModel } from "./model";
|
||||
import type { StreamItem } from "@/types/stream";
|
||||
|
||||
function revealHistory(tail: StreamItem[]): WeakRef<StreamItem[]>[] {
|
||||
const windows: WeakRef<StreamItem[]>[] = [];
|
||||
for (let start = tail.length - 20; start >= 20; start -= 20) {
|
||||
const model = buildAgentStreamRenderModel({
|
||||
tail,
|
||||
head: [],
|
||||
historyStart: start,
|
||||
platform: "web",
|
||||
isMobileBreakpoint: false,
|
||||
isTurnActive: false,
|
||||
activeTurnStartedAt: null,
|
||||
});
|
||||
windows.push(new WeakRef(model.history));
|
||||
}
|
||||
return windows;
|
||||
}
|
||||
|
||||
it("releases obsolete history windows and their source timeline", async () => {
|
||||
setFlagsFromString("--expose_gc");
|
||||
const gc = runInNewContext("gc") as () => void;
|
||||
setFlagsFromString("--no-expose_gc");
|
||||
async function collect() {
|
||||
for (let i = 0; i < 3; i++) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
gc();
|
||||
}
|
||||
}
|
||||
let tail: StreamItem[] = Array.from({ length: 1000 }, (_, i) => ({
|
||||
kind: i % 2 ? "assistant_message" : "user_message",
|
||||
id: `row-${i}`,
|
||||
text: "text",
|
||||
timestamp: new Date(1700000000000 + i * 1000),
|
||||
}));
|
||||
const windows = revealHistory(tail);
|
||||
await collect();
|
||||
expect(windows.filter((ref) => ref.deref() !== undefined)).toHaveLength(1);
|
||||
|
||||
windows.push(...revealHistory(tail));
|
||||
await collect();
|
||||
expect(windows.filter((ref) => ref.deref() !== undefined)).toHaveLength(1);
|
||||
|
||||
tail = [];
|
||||
await collect();
|
||||
expect(windows.every((ref) => ref.deref() === undefined)).toBe(true);
|
||||
});
|
||||
@@ -240,4 +240,47 @@ describe("buildAgentStreamRenderModel", () => {
|
||||
|
||||
expect(model.turnTiming.byAssistantId.size).toBe(0);
|
||||
});
|
||||
|
||||
it.each(["web", "native"] as const)(
|
||||
"reuses rendered history and timing across live-head updates inside a history window on %s",
|
||||
(platform) => {
|
||||
const at = (seed: number) => new Date(Date.UTC(2026, 0, 1, 0, 0, seed));
|
||||
const tail: StreamItem[] = [];
|
||||
for (let index = 0; index < 40; index += 1) {
|
||||
tail.push(
|
||||
{ ...userMessage(`u${index}`, 0), timestamp: at(index * 2) },
|
||||
{ ...assistantMessage(`a${index}`, 0), timestamp: at(index * 2 + 1) },
|
||||
);
|
||||
}
|
||||
const live = (text: string): StreamItem => ({
|
||||
kind: "assistant_message",
|
||||
id: "live",
|
||||
text,
|
||||
timestamp: at(81),
|
||||
});
|
||||
const build = (head: StreamItem[]) =>
|
||||
buildAgentStreamRenderModel({
|
||||
isTurnActive: true,
|
||||
activeTurnStartedAt: tail.at(-2)?.timestamp ?? null,
|
||||
tail,
|
||||
head,
|
||||
platform,
|
||||
isMobileBreakpoint: false,
|
||||
historyStart: 60,
|
||||
});
|
||||
|
||||
const first = build([live("live")]);
|
||||
const second = build([live("live grows")]);
|
||||
|
||||
expect(second.history).toBe(first.history);
|
||||
expect(second.segments.historyMounted).toBe(first.segments.historyMounted);
|
||||
expect(second.turnTiming.byAssistantId).toBe(first.turnTiming.byAssistantId);
|
||||
expect(first.history).toHaveLength(20);
|
||||
expect(first.turnTiming.byAssistantId.has("a29")).toBe(false);
|
||||
expect(first.turnTiming.byAssistantId.get("a38")).toEqual({
|
||||
completedAt: tail[77]?.timestamp,
|
||||
durationMs: 1000,
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -53,11 +53,29 @@ const splitHistoryCache = new WeakMap<
|
||||
StreamItem[],
|
||||
Map<string, Pick<AgentStreamRenderModel, "history" | "segments">>
|
||||
>();
|
||||
const turnTimingCache = new WeakMap<
|
||||
// A streamed delta rebuilds the model with the same tail. Everything below is keyed on
|
||||
// the rendered tail's identity, so the slice has to be reused, not recomputed.
|
||||
const renderedTailCache = new WeakMap<
|
||||
StreamItem[],
|
||||
WeakMap<StreamItem[], Map<string, StreamTurnTiming>>
|
||||
{ historyStart: number; rendered: StreamItem[] }
|
||||
>();
|
||||
|
||||
function getRenderedTail(tail: StreamItem[], historyStart: number | undefined): StreamItem[] {
|
||||
if (!historyStart) {
|
||||
renderedTailCache.delete(tail);
|
||||
return tail;
|
||||
}
|
||||
const cached = renderedTailCache.get(tail);
|
||||
if (cached?.historyStart === historyStart) {
|
||||
return cached.rendered;
|
||||
}
|
||||
const rendered = tail.slice(historyStart);
|
||||
// Revealing older history replaces the previous window, allowing its arrays and
|
||||
// downstream layouts to be collected while the unchanged source tail stays alive.
|
||||
renderedTailCache.set(tail, { historyStart, rendered });
|
||||
return rendered;
|
||||
}
|
||||
|
||||
function getOrderedItems(params: {
|
||||
cache: WeakMap<StreamItem[], Map<string, StreamItem[]>>;
|
||||
source: StreamItem[];
|
||||
@@ -129,32 +147,6 @@ function splitOrderedTail(params: {
|
||||
return split;
|
||||
}
|
||||
|
||||
function getTurnTiming(params: {
|
||||
isTurnActive: boolean;
|
||||
activeTurnStartedAt: Date | null;
|
||||
tail: StreamItem[];
|
||||
head: StreamItem[];
|
||||
}): StreamTurnTiming {
|
||||
let cachedByHead = turnTimingCache.get(params.tail);
|
||||
if (!cachedByHead) {
|
||||
cachedByHead = new WeakMap();
|
||||
turnTimingCache.set(params.tail, cachedByHead);
|
||||
}
|
||||
let cachedByActivity = cachedByHead.get(params.head);
|
||||
if (!cachedByActivity) {
|
||||
cachedByActivity = new Map();
|
||||
cachedByHead.set(params.head, cachedByActivity);
|
||||
}
|
||||
const activityKey = `${params.isTurnActive}:${params.activeTurnStartedAt?.getTime() ?? "none"}`;
|
||||
const cached = cachedByActivity.get(activityKey);
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
const timing = deriveStreamTurnTiming(params);
|
||||
cachedByActivity.set(activityKey, timing);
|
||||
return timing;
|
||||
}
|
||||
|
||||
export function buildAgentStreamRenderModel(
|
||||
input: BuildAgentStreamRenderModelInput,
|
||||
): AgentStreamRenderModel {
|
||||
@@ -163,7 +155,7 @@ export function buildAgentStreamRenderModel(
|
||||
isMobileBreakpoint: input.isMobileBreakpoint,
|
||||
});
|
||||
const orderingCacheKey = `${input.platform}:${input.isMobileBreakpoint}`;
|
||||
const renderedTail = input.historyStart ? input.tail.slice(input.historyStart) : input.tail;
|
||||
const renderedTail = getRenderedTail(input.tail, input.historyStart);
|
||||
const orderedTail = getOrderedItems({
|
||||
cache: orderedTailCache,
|
||||
source: renderedTail,
|
||||
@@ -189,7 +181,7 @@ export function buildAgentStreamRenderModel(
|
||||
platform: input.platform,
|
||||
isMobileBreakpoint: input.isMobileBreakpoint,
|
||||
});
|
||||
const turnTiming = getTurnTiming({
|
||||
const turnTiming = deriveStreamTurnTiming({
|
||||
isTurnActive: input.isTurnActive,
|
||||
activeTurnStartedAt: input.activeTurnStartedAt,
|
||||
tail: renderedTail,
|
||||
|
||||
@@ -1298,6 +1298,8 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
<div style={viewportStyle} data-window-content>
|
||||
<div
|
||||
ref={handleScrollContainerRef}
|
||||
// Let clicks focus the feed for browser keyboard scrolling without adding a Tab stop.
|
||||
tabIndex={-1}
|
||||
data-testid="agent-chat-scroll"
|
||||
data-overlay-scrollbar={scrollEnabled && !isMobileBreakpoint ? "true" : undefined}
|
||||
id={`agent-chat-scroll-${shouldUseVirtualizer ? "web-dom-virtualized" : "web-dom-scroll"}`}
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
import { bench, describe } from "vitest";
|
||||
import type { StreamItem, ToolCallItem } from "@/types/stream";
|
||||
import {
|
||||
prepareToolCallHistory,
|
||||
projectToolCallDetailLevel,
|
||||
} from "@/tool-calls/detail-level/projection";
|
||||
import { findMountedWindowStart, getMountedRecentStreamItems } from "./history-window";
|
||||
import { layoutStream } from "./layout";
|
||||
import { buildAgentStreamRenderModel } from "./model";
|
||||
import { resolveStreamRenderStrategy } from "./strategy-resolver";
|
||||
|
||||
// One coalesced delta replaces the stream head. This is the pure work AgentStreamView
|
||||
// does per delta on a long timeline, without React:
|
||||
// npx vitest bench --project unit src/agent-stream/stream-tick.bench.ts
|
||||
|
||||
const TIMELINE_ITEMS = 2_000;
|
||||
const TICKS = 200;
|
||||
|
||||
function timestamp(seed: number): Date {
|
||||
return new Date(1_700_000_000_000 + seed * 1000);
|
||||
}
|
||||
|
||||
function toolCall(id: string, seed: number): ToolCallItem {
|
||||
return {
|
||||
kind: "tool_call",
|
||||
id,
|
||||
timestamp: timestamp(seed),
|
||||
payload: {
|
||||
source: "agent",
|
||||
data: {
|
||||
provider: "claude",
|
||||
callId: id,
|
||||
name: "shell",
|
||||
status: "completed",
|
||||
error: null,
|
||||
detail: { type: "shell", command: id },
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function buildTimeline(count: number): StreamItem[] {
|
||||
const items: StreamItem[] = [];
|
||||
let seed = 0;
|
||||
while (items.length < count) {
|
||||
const turn = items.length;
|
||||
items.push({
|
||||
kind: "user_message",
|
||||
id: `u${turn}`,
|
||||
text: "prompt",
|
||||
timestamp: timestamp(seed++),
|
||||
});
|
||||
items.push(toolCall(`t${turn}a`, seed++));
|
||||
items.push(toolCall(`t${turn}b`, seed++));
|
||||
items.push({
|
||||
kind: "assistant_message",
|
||||
id: `a${turn}`,
|
||||
text: "answer",
|
||||
timestamp: timestamp(seed++),
|
||||
});
|
||||
}
|
||||
return items.slice(0, count);
|
||||
}
|
||||
|
||||
function buildHeads(base: StreamItem[], ticks: number): StreamItem[][] {
|
||||
let text = "";
|
||||
const heads: StreamItem[][] = [];
|
||||
for (let tick = 0; tick < ticks; tick += 1) {
|
||||
text += "token ";
|
||||
heads.push([
|
||||
{
|
||||
kind: "assistant_message",
|
||||
id: "live",
|
||||
text,
|
||||
timestamp: timestamp(base.length + tick),
|
||||
},
|
||||
]);
|
||||
}
|
||||
return heads;
|
||||
}
|
||||
|
||||
function runTicks(input: { tail: StreamItem[]; historyStart: number; heads: StreamItem[][] }) {
|
||||
const { tail, historyStart, heads } = input;
|
||||
const strategy = resolveStreamRenderStrategy({ platform: "web", isMobileBreakpoint: false });
|
||||
const prepared = prepareToolCallHistory("overview", tail);
|
||||
const boundaryId = tail[historyStart]?.id ?? null;
|
||||
const activeTurnStartedAt = tail.at(-1)?.timestamp ?? null;
|
||||
for (const head of heads) {
|
||||
const projected = projectToolCallDetailLevel({
|
||||
level: "overview",
|
||||
tail,
|
||||
head,
|
||||
preparedHistory: prepared,
|
||||
isTurnActive: true,
|
||||
});
|
||||
const boundaryIndex = boundaryId
|
||||
? projected.tail.findIndex((item) => item.id === boundaryId)
|
||||
: -1;
|
||||
const model = buildAgentStreamRenderModel({
|
||||
isTurnActive: true,
|
||||
activeTurnStartedAt,
|
||||
tail: projected.tail,
|
||||
head: projected.head,
|
||||
platform: "web",
|
||||
isMobileBreakpoint: false,
|
||||
historyStart: boundaryIndex >= 0 ? boundaryIndex : historyStart,
|
||||
});
|
||||
layoutStream({
|
||||
strategy,
|
||||
isTurnActive: true,
|
||||
history: model.history,
|
||||
liveHead: model.segments.liveHead,
|
||||
timingByAssistantId: model.turnTiming.byAssistantId,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const tail = buildTimeline(TIMELINE_ITEMS);
|
||||
const heads = buildHeads(tail, TICKS);
|
||||
const defaultWindowStart = findMountedWindowStart({
|
||||
items: tail,
|
||||
minMountedCount: getMountedRecentStreamItems(),
|
||||
});
|
||||
|
||||
describe(`${TICKS} streamed deltas over a ${TIMELINE_ITEMS}-item timeline`, () => {
|
||||
bench("default mounted window (recent items only)", () => {
|
||||
runTicks({ tail, historyStart: defaultWindowStart, heads });
|
||||
});
|
||||
bench("history fully revealed (scrolled to top)", () => {
|
||||
runTicks({ tail, historyStart: 0, heads });
|
||||
});
|
||||
});
|
||||
@@ -70,10 +70,11 @@ export function useStreamHistoryWindow(input: {
|
||||
boundaryItemId: initialBoundaryItemId,
|
||||
initialized: items.length > 0,
|
||||
}));
|
||||
const boundaryIndex =
|
||||
window.agentId === agentId && window.boundaryItemId !== null
|
||||
? items.findIndex((item) => item.id === window.boundaryItemId)
|
||||
: -1;
|
||||
const boundaryItemId = window.agentId === agentId ? window.boundaryItemId : null;
|
||||
const boundaryIndex = useMemo(
|
||||
() => (boundaryItemId === null ? -1 : items.findIndex((item) => item.id === boundaryItemId)),
|
||||
[boundaryItemId, items],
|
||||
);
|
||||
let start = initialStart;
|
||||
if (window.agentId === agentId && window.initialized) {
|
||||
if (window.boundaryItemId === null) {
|
||||
|
||||
@@ -607,16 +607,21 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
toast?.error(t("agentStream.historyLoadFailed"));
|
||||
}, [t, toast]);
|
||||
// Chat find and the chat outline address messages, and an assistant message is a
|
||||
// group of block rows, so this is a set of message ids and never of row ids.
|
||||
const visibleMessageIds = useMemo(
|
||||
() =>
|
||||
new Set(
|
||||
[...baseRenderModel.history, ...baseRenderModel.segments.liveHead].map(
|
||||
getStreamItemMessageId,
|
||||
),
|
||||
),
|
||||
[baseRenderModel.history, baseRenderModel.segments.liveHead],
|
||||
// group of block rows, so these hold message ids and never row ids. Only the head
|
||||
// changes per streamed delta, so the history set is keyed on mounted history alone.
|
||||
const mountedHistoryMessageIds = useMemo(
|
||||
() => new Set(baseRenderModel.history.map(getStreamItemMessageId)),
|
||||
[baseRenderModel.history],
|
||||
);
|
||||
const mountedMessageIds = useMemo(() => {
|
||||
const liveHeadMessageIds = new Set(
|
||||
baseRenderModel.segments.liveHead.map(getStreamItemMessageId),
|
||||
);
|
||||
return {
|
||||
has: (messageId: string) =>
|
||||
mountedHistoryMessageIds.has(messageId) || liveHeadMessageIds.has(messageId),
|
||||
};
|
||||
}, [baseRenderModel.segments.liveHead, mountedHistoryMessageIds]);
|
||||
const chatOutline = useChatOutline({
|
||||
agentId,
|
||||
serverId: resolvedServerId,
|
||||
@@ -626,7 +631,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
enabled: supportsChatOutline && chatOutlineEnabled,
|
||||
viewportRef,
|
||||
onJumpError: handleTimelineHistoryLoadError,
|
||||
visibleMessageIds,
|
||||
mountedHistoryMessageIds,
|
||||
revealLoadedMessage: revealLoadedHistory,
|
||||
});
|
||||
|
||||
@@ -1105,7 +1110,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
items={findItems}
|
||||
viewportRef={viewportRef}
|
||||
revealLoadedMessage={revealLoadedHistory}
|
||||
visibleMessageIds={visibleMessageIds}
|
||||
visibleMessageIds={mountedMessageIds}
|
||||
>
|
||||
<ToolCallSheetProvider>
|
||||
<AssistantSelectionCopySurface style={stylesheet.container}>
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
useRef,
|
||||
useState,
|
||||
type ComponentType,
|
||||
type RefObject,
|
||||
} from "react";
|
||||
import {
|
||||
Modal,
|
||||
@@ -71,6 +72,7 @@ import {
|
||||
type ProjectPickerOption,
|
||||
} from "@/components/project-picker-options";
|
||||
import { Shortcut } from "@/components/ui/shortcut";
|
||||
import { useRevealActiveItem } from "@/components/ui/scroll-reveal";
|
||||
import { useKeyboardShortcutsAvailable } from "@/keyboard/availability";
|
||||
import { getIsElectronRuntime } from "@/constants/layout";
|
||||
import { isNative, isWeb } from "@/constants/platform";
|
||||
@@ -252,7 +254,17 @@ function pathTestId(path: string): string {
|
||||
return `add-project-flow-path-${encodeURIComponent(path)}`;
|
||||
}
|
||||
|
||||
function FlowRow({ option, active }: { option: FlowRowOption; active: boolean }) {
|
||||
function FlowRow({
|
||||
option,
|
||||
active,
|
||||
activeItemRef,
|
||||
onRowLayout,
|
||||
}: {
|
||||
option: FlowRowOption;
|
||||
active: boolean;
|
||||
activeItemRef: RefObject<View | null>;
|
||||
onRowLayout: () => void;
|
||||
}) {
|
||||
const accessibilityState = useMemo(
|
||||
() => ({ disabled: option.disabled === true, selected: active }),
|
||||
[active, option.disabled],
|
||||
@@ -270,6 +282,8 @@ function FlowRow({ option, active }: { option: FlowRowOption; active: boolean })
|
||||
accessibilityRole="button"
|
||||
accessibilityState={accessibilityState}
|
||||
disabled={option.disabled}
|
||||
ref={active ? activeItemRef : undefined}
|
||||
onLayout={active ? onRowLayout : undefined}
|
||||
onPress={option.select}
|
||||
style={rowStyle}
|
||||
testID={option.testID}
|
||||
@@ -384,6 +398,7 @@ export function AddProjectFlow({ request, onClose }: AddProjectFlowProps) {
|
||||
);
|
||||
const setHasHydratedWorkspaces = useSessionStore((store) => store.setHasHydratedWorkspaces);
|
||||
const inputRef = useRef<EditingTextInputHandle>(null);
|
||||
const resultsRef = useRef<ScrollView>(null);
|
||||
const submissionInFlightRef = useRef(false);
|
||||
const browseInFlightRef = useRef(false);
|
||||
const query = page.kind === "new-directory-name" || page.kind === "method" ? "" : page.query;
|
||||
@@ -715,6 +730,13 @@ export function AddProjectFlow({ request, onClose }: AddProjectFlowProps) {
|
||||
]);
|
||||
|
||||
const activeIndex = rows.length === 0 ? 0 : Math.min(page.activeIndex, rows.length - 1);
|
||||
const rowListKey = useMemo(() => rows.map((row) => row.id).join("\u0000"), [rows]);
|
||||
const { activeItemRef, contentRef, onItemLayout, onViewportLayout, onScroll } =
|
||||
useRevealActiveItem({
|
||||
activeIndex,
|
||||
listKey: rowListKey,
|
||||
scrollRef: resultsRef,
|
||||
});
|
||||
const createDirectory = useCallback(async () => {
|
||||
if (page.kind !== "new-directory-name" || !client) return;
|
||||
const name = page.name.trim();
|
||||
@@ -905,53 +927,64 @@ export function AddProjectFlow({ request, onClose }: AddProjectFlowProps) {
|
||||
) : null}
|
||||
</View>
|
||||
<ScrollView
|
||||
ref={resultsRef}
|
||||
style={styles.results}
|
||||
contentContainerStyle={styles.resultsContent}
|
||||
keyboardShouldPersistTaps="always"
|
||||
onLayout={onViewportLayout}
|
||||
onScroll={onScroll}
|
||||
scrollEventThrottle={16}
|
||||
showsVerticalScrollIndicator={false}
|
||||
testID="add-project-flow-results"
|
||||
>
|
||||
{preview ? (
|
||||
<Text style={styles.preview} testID="add-project-flow-path-preview">
|
||||
{shortenPath(preview)}
|
||||
</Text>
|
||||
) : null}
|
||||
{isSubmitting ? (
|
||||
<Text style={styles.stateText} testID="add-project-flow-progress">
|
||||
{progressText(page)}
|
||||
</Text>
|
||||
) : null}
|
||||
{!isSubmitting && page.error ? (
|
||||
<Text style={styles.errorText} testID="add-project-flow-error">
|
||||
{page.error}
|
||||
</Text>
|
||||
) : null}
|
||||
{!isSubmitting && queryError ? (
|
||||
<Text style={styles.errorText} testID="add-project-flow-query-error">
|
||||
{queryError}
|
||||
</Text>
|
||||
) : null}
|
||||
{!isSubmitting && loading ? (
|
||||
<Text style={styles.stateText} testID="add-project-flow-loading">
|
||||
Loading...
|
||||
</Text>
|
||||
) : null}
|
||||
{!isSubmitting &&
|
||||
(!loading || page.kind === "github-search") &&
|
||||
(!queryError || page.kind === "github-search")
|
||||
? rows.map((option, index) => (
|
||||
<FlowRow key={option.id} option={option} active={index === activeIndex} />
|
||||
))
|
||||
: null}
|
||||
{!isSubmitting &&
|
||||
!loading &&
|
||||
!queryError &&
|
||||
rows.length === 0 &&
|
||||
page.kind !== "new-directory-name" ? (
|
||||
<Text style={styles.stateText} testID="add-project-flow-empty">
|
||||
{emptyText(page, host ?? null)}
|
||||
</Text>
|
||||
) : null}
|
||||
<View ref={contentRef} collapsable={false} style={styles.resultsContent}>
|
||||
{preview ? (
|
||||
<Text style={styles.preview} testID="add-project-flow-path-preview">
|
||||
{shortenPath(preview)}
|
||||
</Text>
|
||||
) : null}
|
||||
{isSubmitting ? (
|
||||
<Text style={styles.stateText} testID="add-project-flow-progress">
|
||||
{progressText(page)}
|
||||
</Text>
|
||||
) : null}
|
||||
{!isSubmitting && page.error ? (
|
||||
<Text style={styles.errorText} testID="add-project-flow-error">
|
||||
{page.error}
|
||||
</Text>
|
||||
) : null}
|
||||
{!isSubmitting && queryError ? (
|
||||
<Text style={styles.errorText} testID="add-project-flow-query-error">
|
||||
{queryError}
|
||||
</Text>
|
||||
) : null}
|
||||
{!isSubmitting && loading ? (
|
||||
<Text style={styles.stateText} testID="add-project-flow-loading">
|
||||
Loading...
|
||||
</Text>
|
||||
) : null}
|
||||
{!isSubmitting &&
|
||||
(!loading || page.kind === "github-search") &&
|
||||
(!queryError || page.kind === "github-search")
|
||||
? rows.map((option, index) => (
|
||||
<FlowRow
|
||||
key={option.id}
|
||||
option={option}
|
||||
activeItemRef={activeItemRef}
|
||||
active={index === activeIndex}
|
||||
onRowLayout={onItemLayout}
|
||||
/>
|
||||
))
|
||||
: null}
|
||||
{!isSubmitting &&
|
||||
!loading &&
|
||||
!queryError &&
|
||||
rows.length === 0 &&
|
||||
page.kind !== "new-directory-name" ? (
|
||||
<Text style={styles.stateText} testID="add-project-flow-empty">
|
||||
{emptyText(page, host ?? null)}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
</ScrollView>
|
||||
<View style={styles.footer} testID="add-project-flow-footer">
|
||||
<FlowHint keys={NAVIGATION_HINT_KEYS} action="Navigate" />
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
getAutocompleteFallbackIndex,
|
||||
getAutocompleteScrollOffset,
|
||||
orderAutocompleteOptions,
|
||||
} from "./autocomplete-utils";
|
||||
import { getAutocompleteFallbackIndex, orderAutocompleteOptions } from "./autocomplete-utils";
|
||||
|
||||
const OPTIONS = ["alpha", "beta", "gamma"];
|
||||
|
||||
@@ -28,27 +24,3 @@ describe("getAutocompleteFallbackIndex", () => {
|
||||
expect(getAutocompleteFallbackIndex(3, "below-input")).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getAutocompleteScrollOffset", () => {
|
||||
it("scrolls up when the active item is above the viewport", () => {
|
||||
expect(
|
||||
getAutocompleteScrollOffset({
|
||||
currentOffset: 120,
|
||||
viewportHeight: 80,
|
||||
itemTop: 90,
|
||||
itemHeight: 20,
|
||||
}),
|
||||
).toBe(90);
|
||||
});
|
||||
|
||||
it("scrolls down when the active item is below the viewport", () => {
|
||||
expect(
|
||||
getAutocompleteScrollOffset({
|
||||
currentOffset: 0,
|
||||
viewportHeight: 100,
|
||||
itemTop: 150,
|
||||
itemHeight: 24,
|
||||
}),
|
||||
).toBe(74);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -29,28 +29,3 @@ export function getAutocompleteNextIndex(args: {
|
||||
}): number {
|
||||
return getNextActiveIndex(args);
|
||||
}
|
||||
|
||||
export function getAutocompleteScrollOffset(args: {
|
||||
currentOffset: number;
|
||||
viewportHeight: number;
|
||||
itemTop: number;
|
||||
itemHeight: number;
|
||||
}): number {
|
||||
if (args.viewportHeight <= 0) {
|
||||
return args.currentOffset;
|
||||
}
|
||||
|
||||
const itemBottom = args.itemTop + args.itemHeight;
|
||||
const viewportTop = args.currentOffset;
|
||||
const viewportBottom = args.currentOffset + args.viewportHeight;
|
||||
|
||||
if (args.itemTop < viewportTop) {
|
||||
return Math.max(0, args.itemTop);
|
||||
}
|
||||
|
||||
if (itemBottom > viewportBottom) {
|
||||
return Math.max(0, itemBottom - args.viewportHeight);
|
||||
}
|
||||
|
||||
return args.currentOffset;
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ import { StyleSheet, useUnistyles } from "react-native-unistyles";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { File, Folder } from "lucide-react-native";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import { getAutocompleteScrollOffset } from "./autocomplete-utils";
|
||||
import { getScrollOffsetToRevealItem } from "./scroll-reveal";
|
||||
|
||||
export interface AutocompleteOption {
|
||||
id: string;
|
||||
@@ -146,7 +146,7 @@ export function Autocomplete({
|
||||
return;
|
||||
}
|
||||
|
||||
const nextOffset = getAutocompleteScrollOffset({
|
||||
const nextOffset = getScrollOffsetToRevealItem({
|
||||
currentOffset: scrollOffsetRef.current,
|
||||
viewportHeight: viewportHeightRef.current,
|
||||
itemTop: layout.top,
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { getScrollOffsetToRevealItem } from "./scroll-reveal";
|
||||
|
||||
describe("getScrollOffsetToRevealItem", () => {
|
||||
it("keeps the offset when the item is already inside the viewport", () => {
|
||||
expect(
|
||||
getScrollOffsetToRevealItem({
|
||||
currentOffset: 40,
|
||||
viewportHeight: 200,
|
||||
itemTop: 100,
|
||||
itemHeight: 40,
|
||||
}),
|
||||
).toBe(40);
|
||||
});
|
||||
|
||||
it("scrolls up to the item top when the item is above the viewport", () => {
|
||||
expect(
|
||||
getScrollOffsetToRevealItem({
|
||||
currentOffset: 300,
|
||||
viewportHeight: 200,
|
||||
itemTop: 240,
|
||||
itemHeight: 40,
|
||||
}),
|
||||
).toBe(240);
|
||||
});
|
||||
|
||||
it("scrolls down just far enough to reveal the item bottom", () => {
|
||||
expect(
|
||||
getScrollOffsetToRevealItem({
|
||||
currentOffset: 0,
|
||||
viewportHeight: 200,
|
||||
itemTop: 380,
|
||||
itemHeight: 40,
|
||||
}),
|
||||
).toBe(220);
|
||||
});
|
||||
|
||||
it("stays put before the viewport has been measured", () => {
|
||||
expect(
|
||||
getScrollOffsetToRevealItem({
|
||||
currentOffset: 120,
|
||||
viewportHeight: 0,
|
||||
itemTop: 400,
|
||||
itemHeight: 40,
|
||||
}),
|
||||
).toBe(120);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,110 @@
|
||||
import { useCallback, useLayoutEffect, useRef, type RefObject } from "react";
|
||||
import type {
|
||||
LayoutChangeEvent,
|
||||
NativeScrollEvent,
|
||||
NativeSyntheticEvent,
|
||||
ScrollView,
|
||||
View,
|
||||
} from "react-native";
|
||||
|
||||
export function getScrollOffsetToRevealItem(args: {
|
||||
currentOffset: number;
|
||||
viewportHeight: number;
|
||||
itemTop: number;
|
||||
itemHeight: number;
|
||||
}): number {
|
||||
if (args.viewportHeight <= 0) {
|
||||
return args.currentOffset;
|
||||
}
|
||||
|
||||
const itemBottom = args.itemTop + args.itemHeight;
|
||||
const viewportTop = args.currentOffset;
|
||||
const viewportBottom = args.currentOffset + args.viewportHeight;
|
||||
|
||||
if (args.itemTop < viewportTop) {
|
||||
return Math.max(0, args.itemTop);
|
||||
}
|
||||
|
||||
if (itemBottom > viewportBottom) {
|
||||
return Math.max(0, itemBottom - args.viewportHeight);
|
||||
}
|
||||
|
||||
return args.currentOffset;
|
||||
}
|
||||
|
||||
export interface RevealActiveItemHandlers {
|
||||
activeItemRef: RefObject<View | null>;
|
||||
contentRef: RefObject<View | null>;
|
||||
onItemLayout: () => void;
|
||||
onViewportLayout: (event: LayoutChangeEvent) => void;
|
||||
onScroll: (event: NativeSyntheticEvent<NativeScrollEvent>) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reveals the keyboard-selected row using its current position in the scroll
|
||||
* content. Measuring on selection/list changes also covers retained rows that
|
||||
* move or keep their size without emitting another onLayout event on web.
|
||||
* A list replacement resets to the top only when selection restarts there.
|
||||
* Bottom-anchored lists share only getScrollOffsetToRevealItem.
|
||||
*/
|
||||
export function useRevealActiveItem(options: {
|
||||
activeIndex: number;
|
||||
listKey: string;
|
||||
scrollRef: RefObject<ScrollView | null>;
|
||||
}): RevealActiveItemHandlers {
|
||||
const { activeIndex, listKey, scrollRef } = options;
|
||||
const activeItemRef = useRef<View | null>(null);
|
||||
const contentRef = useRef<View | null>(null);
|
||||
const viewportHeightRef = useRef(0);
|
||||
const offsetRef = useRef(0);
|
||||
const measurementRef = useRef(0);
|
||||
|
||||
const reveal = useCallback(() => {
|
||||
const request = ++measurementRef.current;
|
||||
const item = activeItemRef.current;
|
||||
const scroll = scrollRef.current;
|
||||
const content = contentRef.current;
|
||||
if (!item || !scroll || !content) return;
|
||||
|
||||
item.measureLayout(content, (_left, top, _width, height) => {
|
||||
if (request !== measurementRef.current || activeItemRef.current !== item) return;
|
||||
const nextOffset = getScrollOffsetToRevealItem({
|
||||
currentOffset: offsetRef.current,
|
||||
viewportHeight: viewportHeightRef.current,
|
||||
itemTop: top,
|
||||
itemHeight: height,
|
||||
});
|
||||
if (Math.abs(nextOffset - offsetRef.current) < 1) return;
|
||||
offsetRef.current = nextOffset;
|
||||
scroll.scrollTo({ y: nextOffset, animated: false });
|
||||
});
|
||||
}, [scrollRef]);
|
||||
|
||||
const prevListKeyRef = useRef(listKey);
|
||||
useLayoutEffect(() => {
|
||||
if (prevListKeyRef.current !== listKey && activeIndex === 0) {
|
||||
offsetRef.current = 0;
|
||||
scrollRef.current?.scrollTo({ y: 0, animated: false });
|
||||
}
|
||||
prevListKeyRef.current = listKey;
|
||||
reveal();
|
||||
return () => {
|
||||
// Measurements are asynchronous; a previous selection must not scroll us.
|
||||
measurementRef.current += 1;
|
||||
};
|
||||
}, [activeIndex, listKey, reveal, scrollRef]);
|
||||
|
||||
const onViewportLayout = useCallback(
|
||||
(event: LayoutChangeEvent) => {
|
||||
viewportHeightRef.current = event.nativeEvent.layout.height;
|
||||
reveal();
|
||||
},
|
||||
[reveal],
|
||||
);
|
||||
|
||||
const onScroll = useCallback((event: NativeSyntheticEvent<NativeScrollEvent>) => {
|
||||
offsetRef.current = event.nativeEvent.contentOffset.y;
|
||||
}, []);
|
||||
|
||||
return { activeItemRef, contentRef, onItemLayout: reveal, onViewportLayout, onScroll };
|
||||
}
|
||||
@@ -17,6 +17,14 @@ export function getActiveMessageSubmissions(
|
||||
);
|
||||
}
|
||||
|
||||
export function hasActiveMessageSubmission(
|
||||
submissions: readonly MessageSubmissionRecord[] | null | undefined,
|
||||
): boolean {
|
||||
return (submissions ?? EMPTY_MESSAGE_SUBMISSIONS).some(
|
||||
(submission) => !submission.providerAcknowledged,
|
||||
);
|
||||
}
|
||||
|
||||
export function getSendingClientMessageIds(
|
||||
submissions: readonly MessageSubmissionRecord[] | null | undefined,
|
||||
): string[] {
|
||||
|
||||
@@ -40,7 +40,7 @@ import {
|
||||
navigateToLastWorkspace,
|
||||
useActiveWorkspaceSelection,
|
||||
} from "@/stores/navigation-active-workspace-store";
|
||||
import { dispatchTopWebOverlayKeyDown } from "@/lib/overlay-root";
|
||||
import { dispatchTopWebOverlayKeyDown, keyBelongsToDomPopover } from "@/lib/overlay-root";
|
||||
|
||||
export function useKeyboardShortcuts({
|
||||
enabled,
|
||||
@@ -321,6 +321,10 @@ export function useKeyboardShortcuts({
|
||||
return;
|
||||
}
|
||||
|
||||
if (keyBelongsToDomPopover(event)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// During IME composition, Enter confirms the candidate selection and must
|
||||
// not route through global shortcuts like message send.
|
||||
if (isImeComposingKeyboardEvent(event)) {
|
||||
|
||||
@@ -4,6 +4,7 @@ import { keyboardEventToComboString } from "./shortcut-string";
|
||||
import {
|
||||
buildKeyboardShortcutHelpSections,
|
||||
buildEffectiveBindings,
|
||||
normalizeCapturedShortcutCombo,
|
||||
getBindingIdForAction,
|
||||
getDefaultKeysForAction,
|
||||
getWorkspaceIndexJumpModifierKey,
|
||||
@@ -823,9 +824,9 @@ describe("keyboard-shortcut help sections", () => {
|
||||
expect(rowChord({}, "show-shortcuts")).toEqual([["?"]]);
|
||||
});
|
||||
|
||||
it("replaces the default-only wildcard when the index jump is rebound", () => {
|
||||
it("keeps the digit range readable when the index jump is rebound", () => {
|
||||
expect(rowChord({ [MAC_INDEX_BINDING]: "Ctrl+Digit" }, "workspace-jump-index")).toEqual([
|
||||
["ctrl", "Digit"],
|
||||
["ctrl", "1-9"],
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -1347,3 +1348,45 @@ describe("direct new-tab target shortcuts", () => {
|
||||
).toEqual([["ctrl", "shift", "H"]]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("number-group shortcut capture", () => {
|
||||
const tabBindingId = "workspace-tab-navigate-index-cmd-alt-digit-mac-desktop";
|
||||
it.each([
|
||||
{ id: tabBindingId, action: "workspace.tab.navigate.index", row: "workspace-tab-jump-index" },
|
||||
{
|
||||
id: "workspace-navigate-index-cmd-digit-mac",
|
||||
action: "workspace.navigate.index",
|
||||
row: "workspace-jump-index",
|
||||
},
|
||||
])("captures Ctrl+1 as the entire number group for $row", ({ id, action, row }) => {
|
||||
const combo = normalizeCapturedShortcutCombo(id, "Ctrl+1");
|
||||
expect(combo).toBe("Ctrl+Digit");
|
||||
const overrides = { [id]: combo };
|
||||
const bindings = buildEffectiveBindings(overrides);
|
||||
for (let index = 1; index <= 9; index++) {
|
||||
const result = resolveShortcut({
|
||||
event: { key: String(index), code: `Digit${index}`, ctrlKey: true },
|
||||
context: { isMac: true, isDesktop: true, focusScope: "message-input" },
|
||||
bindings,
|
||||
});
|
||||
expect(result.match?.action).toBe(action);
|
||||
expect(result.match?.payload).toEqual({ index });
|
||||
}
|
||||
expect(resolveShortcutKeysForAction(row, overrides, { isMac: true, isDesktop: true })).toEqual([
|
||||
["ctrl", "1-9"],
|
||||
]);
|
||||
expect(
|
||||
resolveShortcut({
|
||||
event: { key: "0", code: "Digit0", ctrlKey: true },
|
||||
context: { isMac: true, isDesktop: true },
|
||||
bindings,
|
||||
}).match,
|
||||
).toBeNull();
|
||||
});
|
||||
it("preserves literal numbers for non-index actions and existing nonnumeric combos", () => {
|
||||
expect(normalizeCapturedShortcutCombo("show-shortcuts", "Ctrl+1")).toBe("Ctrl+1");
|
||||
expect(normalizeCapturedShortcutCombo(tabBindingId, "Ctrl+K")).toBe("Ctrl+K");
|
||||
expect(normalizeCapturedShortcutCombo(tabBindingId, "Ctrl+0")).toBe("Ctrl+0");
|
||||
expect(normalizeCapturedShortcutCombo(tabBindingId, "Ctrl+9")).toBe("Ctrl+Digit");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1210,6 +1210,13 @@ export const DEFAULT_BINDINGS: readonly ParsedShortcutBinding[] =
|
||||
|
||||
export type ShortcutOverrides = Record<string, string | null>;
|
||||
|
||||
/** Keep number-group actions bound to all nine indices when recording a new modifier. */
|
||||
export function normalizeCapturedShortcutCombo(bindingId: string, combo: string): string {
|
||||
const binding = DEFAULT_BINDINGS.find((candidate) => candidate.id === bindingId);
|
||||
if (binding?.payload?.type !== "index") return combo;
|
||||
return combo.replace(/(^|\+)[1-9]$/, "$1Digit");
|
||||
}
|
||||
|
||||
export function buildEffectiveBindings(overrides: ShortcutOverrides): ParsedShortcutBinding[] {
|
||||
return DEFAULT_BINDINGS.map(function (binding) {
|
||||
const override = overrides[binding.id];
|
||||
|
||||
@@ -192,6 +192,7 @@ const MODIFIER_CODES = new Set([
|
||||
* override on a named key renders as a raw code — `ARROWLEFT`, not `←`.
|
||||
*/
|
||||
const DISPLAY_KEY_ALIASES: Record<string, string> = {
|
||||
Digit: "1-9",
|
||||
ArrowLeft: "Left",
|
||||
ArrowRight: "Right",
|
||||
ArrowUp: "Up",
|
||||
|
||||
@@ -2,7 +2,11 @@ import React, { type RefCallback } from "react";
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { useWebOverlayRegistration } from "./overlay-root";
|
||||
import {
|
||||
hasOpenDomPopover,
|
||||
keyBelongsToDomPopover,
|
||||
useWebOverlayRegistration,
|
||||
} from "./overlay-root";
|
||||
|
||||
function nextFrame(): Promise<void> {
|
||||
return new Promise((resolve) => requestAnimationFrame(() => resolve()));
|
||||
@@ -68,3 +72,35 @@ describe("useWebOverlayRegistration in the browser", () => {
|
||||
expect(openerFocusCalls).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("hasOpenDomPopover", () => {
|
||||
afterEach(() => {
|
||||
document.body.replaceChildren();
|
||||
});
|
||||
|
||||
it("is true only while a popover is shown", () => {
|
||||
const panel = document.createElement("div");
|
||||
panel.setAttribute("popover", "manual");
|
||||
document.body.append(panel);
|
||||
expect(hasOpenDomPopover()).toBe(false);
|
||||
panel.showPopover();
|
||||
expect(hasOpenDomPopover()).toBe(true);
|
||||
panel.hidePopover();
|
||||
expect(hasOpenDomPopover()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Escape with a plugin popover open", () => {
|
||||
afterEach(() => {
|
||||
document.body.replaceChildren();
|
||||
});
|
||||
|
||||
it("leaves other keys to the shortcuts while a popover is open", () => {
|
||||
const panel = document.createElement("div");
|
||||
panel.setAttribute("popover", "manual");
|
||||
document.body.append(panel);
|
||||
panel.showPopover();
|
||||
expect(keyBelongsToDomPopover({ key: "Enter" })).toBe(false);
|
||||
expect(keyBelongsToDomPopover({ key: "Escape" })).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -112,6 +112,31 @@ export function hasActiveWebOverlay(): boolean {
|
||||
return getTopWebOverlay() !== undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* True while an element shown with the Popover API is open. Such a layer
|
||||
* floats above the app like a registered overlay but lives outside the
|
||||
* registry: plugins draw their panels this way, since they cannot register.
|
||||
*/
|
||||
export function hasOpenDomPopover(): boolean {
|
||||
if (typeof document === "undefined") return false;
|
||||
try {
|
||||
return document.querySelector(":popover-open") !== null;
|
||||
} catch {
|
||||
// An engine without the Popover API rejects the selector, and has none open.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a key belongs to an open popover rather than to the app's shortcuts.
|
||||
* An open popover (a plugin's panel) is the top layer and closes on its own
|
||||
* Escape listener, which runs after the shortcut engine's capture listener:
|
||||
* Escape must not also interrupt the running agent.
|
||||
*/
|
||||
export function keyBelongsToDomPopover(event: Pick<KeyboardEvent, "key">): boolean {
|
||||
return event.key === "Escape" && hasOpenDomPopover();
|
||||
}
|
||||
|
||||
function getFocusableElements(scope: HTMLElement): HTMLElement[] {
|
||||
const selector = [
|
||||
"a[href]",
|
||||
|
||||
@@ -464,6 +464,19 @@ describe("ReplicaCache", () => {
|
||||
expect((await cache.readDirectory(SERVER_ID)).projects.size).toBe(0);
|
||||
});
|
||||
|
||||
it("does not return an accepted agent that storage rejected", async () => {
|
||||
const storage = new MemoryStorage();
|
||||
const cache = createCache(storage);
|
||||
storage.persistentWriteFailure = new Error("disk unavailable");
|
||||
commitDirectory(cache, SERVER_ID, directory());
|
||||
await cache.flush();
|
||||
|
||||
const result = await cache.readAgent(SERVER_ID, "agent-1");
|
||||
|
||||
expect(storage.rows.size).toBe(0);
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it("fails closed when an accepted deletion cannot be persisted before a read", async () => {
|
||||
const storage = new MemoryStorage();
|
||||
const cache = createCache(storage);
|
||||
@@ -504,6 +517,25 @@ describe("ReplicaCache", () => {
|
||||
expect((await cache.readWorkspace(SERVER_ID, "workspace-1"))?.workspace.id).toBe("workspace-1");
|
||||
});
|
||||
|
||||
it("discards an in-flight read across host removal and reactivation", async () => {
|
||||
const storage = new MemoryStorage();
|
||||
const cache = createCache(storage);
|
||||
commitDirectory(cache, SERVER_ID, directory());
|
||||
await cache.flush();
|
||||
const started = deferred();
|
||||
const release = deferred();
|
||||
storage.onRead = started.resolve;
|
||||
storage.readGate = release.promise;
|
||||
|
||||
const reading = cache.readAgent(SERVER_ID, "agent-1");
|
||||
await started.promise;
|
||||
cache.setHosts([]);
|
||||
cache.setHosts([SERVER_ID]);
|
||||
release.resolve();
|
||||
|
||||
expect(await reading).toBeUndefined();
|
||||
});
|
||||
|
||||
it("discards a durable read when the host changes while it is in flight", async () => {
|
||||
const storage = new MemoryStorage();
|
||||
const cache = createCache(storage);
|
||||
@@ -522,6 +554,36 @@ describe("ReplicaCache", () => {
|
||||
expect(await reading).toBeUndefined();
|
||||
});
|
||||
|
||||
it("retries a timeline read when that same timeline changes in flight", async () => {
|
||||
const storage = new MemoryStorage();
|
||||
const cache = createCache(storage);
|
||||
cache.commitTimeline(SERVER_ID, "agent-1", timeline("Old"));
|
||||
await cache.flush();
|
||||
storage.onRead = () => {
|
||||
storage.onRead = null;
|
||||
cache.commitTimeline(SERVER_ID, "agent-1", timeline("New"));
|
||||
};
|
||||
|
||||
expect((await cache.readTimeline(SERVER_ID, "agent-1"))?.items).toEqual([timelineItem("New")]);
|
||||
expect(storage.reads).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("discards a requested row removed by a directory baseline replacement in flight", async () => {
|
||||
const storage = new MemoryStorage();
|
||||
const cache = createCache(storage);
|
||||
commitDirectory(cache, SERVER_ID, directory());
|
||||
await cache.flush();
|
||||
const replacement = directory();
|
||||
replacement.agents.clear();
|
||||
storage.onRead = () => {
|
||||
storage.onRead = null;
|
||||
cache.replaceDirectoryBaseline(SERVER_ID, replacement);
|
||||
};
|
||||
|
||||
expect(await cache.readAgent(SERVER_ID, "agent-1")).toBeUndefined();
|
||||
expect(storage.reads).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("never reads a timeline older than an accepted deferred replacement", async () => {
|
||||
const storage = new MemoryStorage();
|
||||
const cache = createCache(storage);
|
||||
@@ -796,7 +858,7 @@ describe("ReplicaCache", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("retries a timeline read invalidated by a concurrent directory commit", async () => {
|
||||
it("reads a persisted timeline across a concurrent directory commit", async () => {
|
||||
const storage = new MemoryStorage();
|
||||
const cache = createCache(storage);
|
||||
cache.commitTimeline(SERVER_ID, "agent-1", timeline("Persisted timeline"));
|
||||
@@ -858,6 +920,90 @@ describe("ReplicaCache", () => {
|
||||
|
||||
expect(storage.cleanups).toBe(1);
|
||||
});
|
||||
|
||||
describe.each(["timeline", "directory"] as const)(
|
||||
"while another agent streams %s updates",
|
||||
(kind) => {
|
||||
async function streamingCache() {
|
||||
const storage = new MemoryStorage();
|
||||
const cache = createCache(storage);
|
||||
commitDirectory(cache, SERVER_ID, directory());
|
||||
cache.commitTimeline(SERVER_ID, "agent-1", timeline());
|
||||
await cache.flush();
|
||||
const readsBefore = storage.reads.length;
|
||||
const writesBefore = storage.writes;
|
||||
let chunks = 0;
|
||||
storage.onRead = () => {
|
||||
if (chunks >= 200) return;
|
||||
chunks += 1;
|
||||
if (kind === "timeline") {
|
||||
cache.commitTimeline(SERVER_ID, "agent-2", {
|
||||
...timeline(`chunk ${chunks}`),
|
||||
agentId: "agent-2",
|
||||
});
|
||||
} else {
|
||||
cache.commitDirectoryMutations(
|
||||
SERVER_ID,
|
||||
[{ type: "upsert", kind: "agent", id: "agent-2", value: agent("agent-2") }],
|
||||
{ agents: { generation: "g", afterSeq: 12 + chunks } },
|
||||
);
|
||||
}
|
||||
};
|
||||
return {
|
||||
cache,
|
||||
expectReads: (count: number, writes = 0) => {
|
||||
expect(storage.reads.length - readsBefore).toBe(count);
|
||||
expect(storage.writes - writesBefore).toBe(writes);
|
||||
expect(chunks).toBe(count);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
it("reads another cached agent without waiting for the stream to stop", async () => {
|
||||
const { cache, expectReads } = await streamingCache();
|
||||
|
||||
expect((await cache.readAgent(SERVER_ID, "agent-1"))?.title).toBe("Cached agent");
|
||||
expectReads(1);
|
||||
await cache.flush();
|
||||
});
|
||||
|
||||
it("reads another cached workspace without waiting for the stream to stop", async () => {
|
||||
const { cache, expectReads } = await streamingCache();
|
||||
|
||||
expect((await cache.readWorkspace(SERVER_ID, "workspace-1"))?.workspace.name).toBe("main");
|
||||
expectReads(2, 1);
|
||||
await cache.flush();
|
||||
});
|
||||
|
||||
it("reads another cached timeline without waiting for the stream to stop", async () => {
|
||||
const { cache, expectReads } = await streamingCache();
|
||||
|
||||
expect(await cache.readTimeline(SERVER_ID, "agent-1")).toEqual(timeline());
|
||||
expectReads(1);
|
||||
await cache.flush();
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("reads the directory after persisting a pending baseline replacement", async () => {
|
||||
const storage = new MemoryStorage();
|
||||
const cache = createCache(storage);
|
||||
commitDirectory(cache, SERVER_ID, directory());
|
||||
cache.commitTimeline(SERVER_ID, "agent-1", timeline());
|
||||
await cache.flush();
|
||||
const replacement = directory({ agents: { generation: "g2", afterSeq: 1 } });
|
||||
replacement.projects.clear();
|
||||
replacement.agents.set("agent-2", agent("agent-2"));
|
||||
cache.replaceDirectoryBaseline(SERVER_ID, replacement);
|
||||
|
||||
const read = await cache.readDirectory(SERVER_ID);
|
||||
|
||||
expect([...read.agents.keys()].sort()).toEqual(["agent-1", "agent-2"]);
|
||||
expect(read.projects.size).toBe(0);
|
||||
expect(read.checkpoint).toEqual({ agents: { generation: "g2", afterSeq: 1 } });
|
||||
expect(await cache.readTimeline(SERVER_ID, "agent-1")).toEqual(timeline());
|
||||
expect(storage.writes).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
it("retains semantic agent messages across disk-cache reconstruction", async () => {
|
||||
|
||||
@@ -880,9 +880,24 @@ function directoryEntityForRow(row: ReplicaRow): keyof DirectoryCheckpoint | und
|
||||
return undefined;
|
||||
}
|
||||
|
||||
interface ReplicaRead {
|
||||
serverId: string;
|
||||
kinds: readonly ReplicaRowKind[];
|
||||
ids?: readonly string[];
|
||||
invalidated: boolean;
|
||||
}
|
||||
|
||||
function matchesReplicaRead(read: ReplicaRead, row: ReplicaRowKey): boolean {
|
||||
return (
|
||||
read.serverId === row.serverId &&
|
||||
read.kinds.includes(row.kind) &&
|
||||
(!read.ids || read.ids.includes(row.id))
|
||||
);
|
||||
}
|
||||
|
||||
export class ReplicaCache {
|
||||
private readonly activeServerIds = new Set<string>();
|
||||
private readonly hostRevisions = new Map<string, number>();
|
||||
private readonly activeReads = new Set<ReplicaRead>();
|
||||
private readonly storedRows = new Map<string, Map<string, ReplicaRow>>();
|
||||
private readonly hostBytes = new Map<string, number>();
|
||||
private readonly hostWriteOrder = new Map<string, true>();
|
||||
@@ -1004,10 +1019,22 @@ export class ReplicaCache {
|
||||
// accepted commits to land. A store that rejects them will keep rejecting them: fail closed
|
||||
// rather than re-attempt the write on every pass. A write rejected for another host leaves
|
||||
// this host's stored rows readable.
|
||||
if (!(await this.syncPending()) && this.hasPendingHostChanges(serverId)) return [];
|
||||
const revision = this.hostRevisions.get(serverId) ?? 0;
|
||||
const rows = await this.rowStore.read(serverId, kinds, ids);
|
||||
if (this.canReadHostRevision(serverId, revision)) return rows;
|
||||
const read: ReplicaRead = { serverId, kinds, ids, invalidated: false };
|
||||
this.activeReads.add(read);
|
||||
try {
|
||||
if (!(await this.syncPending()) && this.hasPendingHostChanges(serverId)) return [];
|
||||
if (read.invalidated || this.hasPendingReadChanges(read)) continue;
|
||||
const rows = await this.rowStore.read(serverId, kinds, ids);
|
||||
if (
|
||||
this.activeServerIds.has(serverId) &&
|
||||
!read.invalidated &&
|
||||
!this.hasPendingReadChanges(read)
|
||||
) {
|
||||
return rows;
|
||||
}
|
||||
} finally {
|
||||
this.activeReads.delete(read);
|
||||
}
|
||||
}
|
||||
return [];
|
||||
} catch {
|
||||
@@ -1092,7 +1119,6 @@ export class ReplicaCache {
|
||||
): void {
|
||||
if (!this.activeServerIds.has(serverId)) return;
|
||||
if (this.invalidatedHosts.has(serverId)) return;
|
||||
this.advanceHostRevision(serverId);
|
||||
for (const mutation of mutations) {
|
||||
if (mutation.type === "delete") {
|
||||
this.queueEntityDelete(serverId, mutation.kind, mutation.id);
|
||||
@@ -1118,7 +1144,7 @@ export class ReplicaCache {
|
||||
|
||||
replaceDirectoryBaseline(serverId: string, directory: CachedDirectory): void {
|
||||
if (!this.activeServerIds.has(serverId)) return;
|
||||
this.advanceHostRevision(serverId);
|
||||
this.invalidateHostReads(serverId, ["agent", "workspace", "project", "checkpoint"]);
|
||||
// Replacing the directory must not discard independently accepted timeline changes.
|
||||
for (const [key, row] of this.pendingUpserts) {
|
||||
if (row.serverId === serverId && row.kind !== "timeline") this.pendingUpserts.delete(key);
|
||||
@@ -1150,7 +1176,6 @@ export class ReplicaCache {
|
||||
commitTimeline(serverId: string, agentId: string, timeline: CachedTimeline): void {
|
||||
if (!this.activeServerIds.has(serverId)) return;
|
||||
if (timeline.agentId !== agentId) throw new Error("Timeline cache key does not match payload");
|
||||
this.advanceHostRevision(serverId);
|
||||
this.queueUpsert({ serverId, kind: "timeline", id: agentId, value: timeline });
|
||||
this.schedulePersist();
|
||||
}
|
||||
@@ -1159,7 +1184,7 @@ export class ReplicaCache {
|
||||
const next = new Set(serverIds);
|
||||
const removed = [...this.activeServerIds].filter((serverId) => !next.has(serverId));
|
||||
const added = [...next].filter((serverId) => !this.activeServerIds.has(serverId));
|
||||
for (const serverId of [...removed, ...added]) this.advanceHostRevision(serverId);
|
||||
for (const serverId of [...removed, ...added]) this.invalidateHostReads(serverId);
|
||||
this.activeServerIds.clear();
|
||||
for (const serverId of next) this.activeServerIds.add(serverId);
|
||||
for (const serverId of removed) {
|
||||
@@ -1171,8 +1196,8 @@ export class ReplicaCache {
|
||||
}
|
||||
|
||||
reconcileServerId(oldServerId: string, newServerId: string): void {
|
||||
this.advanceHostRevision(oldServerId);
|
||||
this.advanceHostRevision(newServerId);
|
||||
this.invalidateHostReads(oldServerId);
|
||||
this.invalidateHostReads(newServerId);
|
||||
const rows = this.storedRows.get(oldServerId);
|
||||
if (rows) {
|
||||
const newRows = this.storedRows.get(newServerId) ?? new Map<string, ReplicaRow>();
|
||||
@@ -1250,12 +1275,14 @@ export class ReplicaCache {
|
||||
}
|
||||
|
||||
private queueUpsert(row: StructuredReplicaUpsert): void {
|
||||
this.invalidateRowReads(row);
|
||||
const key = pendingRowKey(row);
|
||||
this.pendingDeletes.delete(key);
|
||||
this.pendingUpserts.set(key, row);
|
||||
}
|
||||
|
||||
private queueDelete(key: ReplicaRowKey): void {
|
||||
this.invalidateRowReads(key);
|
||||
const pendingKey = pendingRowKey(key);
|
||||
this.pendingUpserts.delete(pendingKey);
|
||||
this.pendingDeletes.set(pendingKey, key);
|
||||
@@ -1267,14 +1294,36 @@ export class ReplicaCache {
|
||||
);
|
||||
}
|
||||
|
||||
private canReadHostRevision(serverId: string, revision: number): boolean {
|
||||
private hasPendingReadChanges(read: ReplicaRead): boolean {
|
||||
if (
|
||||
this.pendingBaselines.has(read.serverId) &&
|
||||
read.kinds.some((kind) => kind !== "timeline")
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
return (
|
||||
this.activeServerIds.has(serverId) &&
|
||||
(this.hostRevisions.get(serverId) ?? 0) === revision &&
|
||||
!this.hasPendingHostChanges(serverId)
|
||||
[...this.pendingUpserts.values()].some((row) => matchesReplicaRead(read, row)) ||
|
||||
[...this.pendingDeletes.values()].some((row) => matchesReplicaRead(read, row))
|
||||
);
|
||||
}
|
||||
|
||||
private invalidateRowReads(row: ReplicaRowKey): void {
|
||||
for (const read of this.activeReads) {
|
||||
if (matchesReplicaRead(read, row)) read.invalidated = true;
|
||||
}
|
||||
}
|
||||
|
||||
private invalidateHostReads(serverId: string, kinds?: readonly ReplicaRowKind[]): void {
|
||||
for (const read of this.activeReads) {
|
||||
if (
|
||||
read.serverId === serverId &&
|
||||
(!kinds || kinds.some((kind) => read.kinds.includes(kind)))
|
||||
) {
|
||||
read.invalidated = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private hasPendingHostChanges(serverId: string): boolean {
|
||||
if (this.pendingBaselines.has(serverId)) return true;
|
||||
for (const row of this.pendingUpserts.values()) {
|
||||
@@ -1286,10 +1335,6 @@ export class ReplicaCache {
|
||||
return false;
|
||||
}
|
||||
|
||||
private advanceHostRevision(serverId: string): void {
|
||||
this.hostRevisions.set(serverId, (this.hostRevisions.get(serverId) ?? 0) + 1);
|
||||
}
|
||||
|
||||
private drainPendingChanges(): PendingReplicaChanges {
|
||||
const changes = {
|
||||
upserts: [...this.pendingUpserts.values()],
|
||||
|
||||
@@ -19,6 +19,7 @@ import { useKeyboardShortcutOverrides } from "@/hooks/use-keyboard-shortcut-over
|
||||
import {
|
||||
buildKeyboardShortcutHelpSections,
|
||||
getBindingIdForAction,
|
||||
normalizeCapturedShortcutCombo,
|
||||
getDefaultKeysForAction,
|
||||
resolveShortcutKeysForAction,
|
||||
type KeyboardShortcutHelpRow,
|
||||
@@ -389,7 +390,8 @@ export function KeyboardShortcutsSection() {
|
||||
}
|
||||
|
||||
setHeldModifiers(null);
|
||||
setCapturedCombos((current) => [...current, comboString]);
|
||||
const capturedCombo = normalizeCapturedShortcutCombo(capturingBindingId!, comboString);
|
||||
setCapturedCombos((current) => [...current, capturedCombo]);
|
||||
}
|
||||
|
||||
window.addEventListener("keydown", handleKeyDown, true);
|
||||
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
import {
|
||||
acceptMessageSubmission,
|
||||
beginMessageSubmission,
|
||||
getActiveMessageSubmissions,
|
||||
hasActiveMessageSubmission,
|
||||
observeMessageSubmissionCanonical,
|
||||
rejectMessageSubmission,
|
||||
type MessageSubmissionRecord,
|
||||
@@ -348,7 +348,7 @@ export function selectAgentTurnPresentation(
|
||||
session?.agents.get(agentId)?.turn ??
|
||||
session?.agentDetails.get(agentId)?.turn ??
|
||||
TURN_LIVENESS_IDLE,
|
||||
getActiveMessageSubmissions(session?.messageSubmissions.get(agentId)).length > 0,
|
||||
hasActiveMessageSubmission(session?.messageSubmissions.get(agentId)),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -12,11 +12,11 @@ function user(id: string, timestamp: Date): StreamItem {
|
||||
};
|
||||
}
|
||||
|
||||
function assistant(id: string, timestamp: Date): StreamItem {
|
||||
function assistant(id: string, timestamp: Date, text = id): StreamItem {
|
||||
return {
|
||||
kind: "assistant_message",
|
||||
id,
|
||||
text: id,
|
||||
text,
|
||||
timestamp,
|
||||
};
|
||||
}
|
||||
@@ -125,4 +125,97 @@ describe("deriveStreamTurnTiming", () => {
|
||||
durationMs: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the timing map identity while a streamed delta grows the live head", () => {
|
||||
const tail = [
|
||||
user("u1", new Date("2026-05-15T00:00:00.000Z")),
|
||||
assistant("a1", new Date("2026-05-15T00:00:07.000Z")),
|
||||
user("u2", new Date("2026-05-15T00:01:00.000Z")),
|
||||
];
|
||||
const derive = (text: string, at: string) =>
|
||||
deriveStreamTurnTiming({
|
||||
isTurnActive: true,
|
||||
activeTurnStartedAt: tail[2]?.timestamp ?? null,
|
||||
tail,
|
||||
head: [assistant("a2", new Date(at), text)],
|
||||
});
|
||||
|
||||
const first = derive("one", "2026-05-15T00:01:04.000Z");
|
||||
const second = derive("one two", "2026-05-15T00:01:05.000Z");
|
||||
|
||||
assert.equal(second.byAssistantId, first.byAssistantId);
|
||||
assert.deepEqual(first.byAssistantId.get("a1"), {
|
||||
completedAt: tail[1]?.timestamp,
|
||||
durationMs: 7000,
|
||||
});
|
||||
assert.equal(first.byAssistantId.has("a2"), false);
|
||||
});
|
||||
|
||||
it("keeps the timing map identity when the head closed the tail's open turn", () => {
|
||||
const lastTailAt = new Date("2026-05-15T00:00:07.000Z");
|
||||
const tail = [user("u1", new Date("2026-05-15T00:00:00.000Z")), assistant("a1", lastTailAt)];
|
||||
const derive = (text: string, at: string) =>
|
||||
deriveStreamTurnTiming({
|
||||
isTurnActive: true,
|
||||
activeTurnStartedAt: null,
|
||||
tail,
|
||||
head: [
|
||||
user("u2", new Date("2026-05-15T00:01:00.000Z")),
|
||||
assistant("a2", new Date(at), text),
|
||||
],
|
||||
});
|
||||
|
||||
const first = derive("one", "2026-05-15T00:01:04.000Z");
|
||||
const second = derive("one two", "2026-05-15T00:01:05.000Z");
|
||||
|
||||
assert.equal(second.byAssistantId, first.byAssistantId);
|
||||
assert.deepEqual(first.byAssistantId.get("a1"), {
|
||||
completedAt: lastTailAt,
|
||||
durationMs: 7000,
|
||||
});
|
||||
});
|
||||
|
||||
it("produces a new timing map when the streamed turn completes", () => {
|
||||
const tail = [user("u1", new Date("2026-05-15T00:00:00.000Z"))];
|
||||
const completedAt = new Date("2026-05-15T00:00:09.000Z");
|
||||
const head = [assistant("a1", completedAt)];
|
||||
|
||||
const active = deriveStreamTurnTiming({
|
||||
isTurnActive: true,
|
||||
activeTurnStartedAt: tail[0]?.timestamp ?? null,
|
||||
tail,
|
||||
head,
|
||||
});
|
||||
const completed = deriveStreamTurnTiming({
|
||||
isTurnActive: false,
|
||||
activeTurnStartedAt: null,
|
||||
tail,
|
||||
head,
|
||||
});
|
||||
|
||||
assert.notEqual(completed.byAssistantId, active.byAssistantId);
|
||||
assert.equal(active.byAssistantId.has("a1"), false);
|
||||
assert.deepEqual(completed.byAssistantId.get("a1"), { completedAt, durationMs: 9000 });
|
||||
});
|
||||
|
||||
it("derives fresh timing when the tail itself changes", () => {
|
||||
const firstTail = [
|
||||
user("u1", new Date("2026-05-15T00:00:00.000Z")),
|
||||
assistant("a1", new Date("2026-05-15T00:00:07.000Z")),
|
||||
user("u2", new Date("2026-05-15T00:01:00.000Z")),
|
||||
];
|
||||
const secondTail = [...firstTail, assistant("a2", new Date("2026-05-15T00:01:03.000Z"))];
|
||||
const derive = (tail: StreamItem[]) =>
|
||||
deriveStreamTurnTiming({ isTurnActive: false, activeTurnStartedAt: null, tail, head: [] });
|
||||
|
||||
const first = derive(firstTail);
|
||||
const second = derive(secondTail);
|
||||
|
||||
assert.notEqual(second.byAssistantId, first.byAssistantId);
|
||||
assert.equal(first.byAssistantId.has("a2"), false);
|
||||
assert.deepEqual(second.byAssistantId.get("a2"), {
|
||||
completedAt: secondTail[3]?.timestamp,
|
||||
durationMs: 3000,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -11,61 +11,135 @@ export interface StreamTurnTiming {
|
||||
runningStartedAt: Date | null;
|
||||
}
|
||||
|
||||
interface OpenTurn {
|
||||
userAt: Date | null;
|
||||
lastItemAt: Date | null;
|
||||
assistantIds: readonly string[];
|
||||
previousItem: StreamItem | null;
|
||||
}
|
||||
|
||||
interface HeadTurnTiming {
|
||||
additions: Map<string, TurnTiming>;
|
||||
byAssistantId: Map<string, TurnTiming>;
|
||||
}
|
||||
|
||||
interface TailTurnTiming {
|
||||
completed: Map<string, TurnTiming>;
|
||||
openTurn: OpenTurn;
|
||||
lastHead: HeadTurnTiming | null;
|
||||
}
|
||||
|
||||
const EMPTY_OPEN_TURN: OpenTurn = {
|
||||
userAt: null,
|
||||
lastItemAt: null,
|
||||
assistantIds: [],
|
||||
previousItem: null,
|
||||
};
|
||||
|
||||
function closeTurn(turn: OpenTurn, into: Map<string, TurnTiming>): void {
|
||||
if (!turn.lastItemAt || turn.assistantIds.length === 0) {
|
||||
return;
|
||||
}
|
||||
const timing: TurnTiming = {
|
||||
completedAt: turn.lastItemAt,
|
||||
durationMs: turn.userAt ? Math.max(0, turn.lastItemAt.getTime() - turn.userAt.getTime()) : null,
|
||||
};
|
||||
for (const id of turn.assistantIds) {
|
||||
into.set(id, timing);
|
||||
}
|
||||
}
|
||||
|
||||
function walkTurns(
|
||||
items: readonly StreamItem[],
|
||||
from: OpenTurn,
|
||||
into: Map<string, TurnTiming>,
|
||||
): OpenTurn {
|
||||
let userAt = from.userAt;
|
||||
let lastItemAt = from.lastItemAt;
|
||||
let assistantIds = [...from.assistantIds];
|
||||
let previousItem = from.previousItem;
|
||||
for (const item of items) {
|
||||
if (startsNewTurn(item, previousItem)) {
|
||||
closeTurn({ userAt, lastItemAt, assistantIds, previousItem }, into);
|
||||
userAt = item.kind === "user_message" ? item.timestamp : null;
|
||||
lastItemAt = null;
|
||||
assistantIds = [];
|
||||
}
|
||||
lastItemAt = item.timestamp;
|
||||
if (item.kind === "assistant_message") {
|
||||
assistantIds.push(item.id);
|
||||
}
|
||||
previousItem = item;
|
||||
}
|
||||
return { userAt, lastItemAt, assistantIds, previousItem };
|
||||
}
|
||||
|
||||
function areTimingsEqual(a: Map<string, TurnTiming>, b: Map<string, TurnTiming>): boolean {
|
||||
if (a.size !== b.size) {
|
||||
return false;
|
||||
}
|
||||
for (const [id, timing] of a) {
|
||||
const other = b.get(id);
|
||||
if (
|
||||
!other ||
|
||||
other.completedAt.getTime() !== timing.completedAt.getTime() ||
|
||||
other.durationMs !== timing.durationMs
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// The tail walk is cached by array identity so a streamed delta, which only replaces the
|
||||
// head, walks the head from the carried open turn. The returned Map keeps its identity
|
||||
// while the head adds no completed turn, so memos keyed on it do not miss per tick.
|
||||
const tailTurnTimingCache = new WeakMap<StreamItem[], TailTurnTiming>();
|
||||
|
||||
function getTailTurnTiming(tail: StreamItem[]): TailTurnTiming {
|
||||
const cached = tailTurnTimingCache.get(tail);
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
const completed = new Map<string, TurnTiming>();
|
||||
const openTurn = walkTurns(tail, EMPTY_OPEN_TURN, completed);
|
||||
const timing: TailTurnTiming = { completed, openTurn, lastHead: null };
|
||||
tailTurnTimingCache.set(tail, timing);
|
||||
return timing;
|
||||
}
|
||||
|
||||
function resolveByAssistantId(
|
||||
tail: TailTurnTiming,
|
||||
additions: Map<string, TurnTiming>,
|
||||
): Map<string, TurnTiming> {
|
||||
if (additions.size === 0) {
|
||||
return tail.completed;
|
||||
}
|
||||
if (tail.lastHead && areTimingsEqual(tail.lastHead.additions, additions)) {
|
||||
return tail.lastHead.byAssistantId;
|
||||
}
|
||||
const byAssistantId = new Map(tail.completed);
|
||||
for (const [id, timing] of additions) {
|
||||
byAssistantId.set(id, timing);
|
||||
}
|
||||
tail.lastHead = { additions, byAssistantId };
|
||||
return byAssistantId;
|
||||
}
|
||||
|
||||
export function deriveStreamTurnTiming(params: {
|
||||
isTurnActive: boolean;
|
||||
activeTurnStartedAt: Date | null;
|
||||
tail: StreamItem[];
|
||||
head: StreamItem[];
|
||||
}): StreamTurnTiming {
|
||||
const byAssistantId = new Map<string, TurnTiming>();
|
||||
let currentUserAt: Date | null = null;
|
||||
let currentLastItemAt: Date | null = null;
|
||||
let currentAssistantIds: string[] = [];
|
||||
let previousItem: StreamItem | null = null;
|
||||
|
||||
const flushCompletedTurn = () => {
|
||||
if (!currentLastItemAt || currentAssistantIds.length === 0) {
|
||||
return;
|
||||
}
|
||||
const timing: TurnTiming = {
|
||||
completedAt: currentLastItemAt,
|
||||
durationMs: currentUserAt
|
||||
? Math.max(0, currentLastItemAt.getTime() - currentUserAt.getTime())
|
||||
: null,
|
||||
};
|
||||
for (const id of currentAssistantIds) {
|
||||
byAssistantId.set(id, timing);
|
||||
}
|
||||
};
|
||||
|
||||
const visitItem = (item: StreamItem) => {
|
||||
if (startsNewTurn(item, previousItem)) {
|
||||
flushCompletedTurn();
|
||||
currentUserAt = item.kind === "user_message" ? item.timestamp : null;
|
||||
currentLastItemAt = null;
|
||||
currentAssistantIds = [];
|
||||
}
|
||||
currentLastItemAt = item.timestamp;
|
||||
if (item.kind === "assistant_message") {
|
||||
currentAssistantIds.push(item.id);
|
||||
}
|
||||
previousItem = item;
|
||||
};
|
||||
|
||||
for (const item of params.tail) {
|
||||
visitItem(item);
|
||||
}
|
||||
for (const item of params.head) {
|
||||
visitItem(item);
|
||||
}
|
||||
|
||||
const runningStartedAt = params.isTurnActive ? params.activeTurnStartedAt : null;
|
||||
const tail = getTailTurnTiming(params.tail);
|
||||
const additions = new Map<string, TurnTiming>();
|
||||
const openTurn = walkTurns(params.head, tail.openTurn, additions);
|
||||
if (!params.isTurnActive) {
|
||||
flushCompletedTurn();
|
||||
closeTurn(openTurn, additions);
|
||||
}
|
||||
|
||||
return {
|
||||
byAssistantId,
|
||||
runningStartedAt,
|
||||
byAssistantId: resolveByAssistantId(tail, additions),
|
||||
runningStartedAt: params.isTurnActive ? params.activeTurnStartedAt : null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -257,6 +257,22 @@ describe("settleReports", () => {
|
||||
expect(settleReports([refreshed, beta], [alpha, beta])).toEqual([refreshed, beta]);
|
||||
});
|
||||
|
||||
it("keeps the displayed order when providers finish a refresh in reverse order", () => {
|
||||
const refreshed = entry({ sourceId: "alpha", planLabel: "New" });
|
||||
const streamed = upsertReport(upsertReport([alpha, beta], beta), refreshed);
|
||||
expect(settleReports(streamed, [beta, refreshed])).toEqual([refreshed, beta]);
|
||||
});
|
||||
|
||||
it("drops missing reports and appends new ones without moving surviving reports", () => {
|
||||
const gamma = entry({ sourceId: "gamma" });
|
||||
const delta = entry({ sourceId: "delta" });
|
||||
expect(settleReports([alpha, beta, gamma], [delta, gamma, alpha])).toEqual([
|
||||
alpha,
|
||||
gamma,
|
||||
delta,
|
||||
]);
|
||||
});
|
||||
|
||||
it("takes the finished list as is when nothing was shown yet", () => {
|
||||
expect(settleReports(undefined, [alpha, beta])).toEqual([alpha, beta]);
|
||||
});
|
||||
|
||||
@@ -82,17 +82,24 @@ export function upsertReport(
|
||||
}
|
||||
|
||||
/**
|
||||
* The list a finished request leaves: its reports, dropping any the host no longer has, except
|
||||
* that a copy on screen fetched after the request's copy stays.
|
||||
* Keep displayed reports in place: the finished list is in fetch-completion order, which can
|
||||
* change on every refresh. Drop missing reports, append new ones, and keep newer fetched copies.
|
||||
*/
|
||||
export function settleReports(
|
||||
shown: readonly UsageReportEntry[] | undefined,
|
||||
finished: readonly UsageReportEntry[],
|
||||
): UsageReportEntry[] {
|
||||
return finished.map((report) => {
|
||||
const copy = shown?.find((entry) => entry.id === report.id);
|
||||
return copy ? laterFetched(copy, report) : report;
|
||||
});
|
||||
const remaining = new Map(finished.map((report) => [report.id, report]));
|
||||
const settled: UsageReportEntry[] = [];
|
||||
for (const report of shown ?? []) {
|
||||
const arriving = remaining.get(report.id);
|
||||
if (!arriving) {
|
||||
continue;
|
||||
}
|
||||
settled.push(laterFetched(report, arriving));
|
||||
remaining.delete(report.id);
|
||||
}
|
||||
return [...settled, ...remaining.values()];
|
||||
}
|
||||
|
||||
export interface UsageQueryState {
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { clickNewChat, gotoWorkspace } from "../../app/e2e/support/helpers/launcher";
|
||||
import { clickSettingsBackToWorkspace } from "../../app/e2e/support/helpers/settings";
|
||||
import type { Page } from "@playwright/test";
|
||||
import { test, expect } from "../../app/e2e/support/fixtures";
|
||||
import { gotoAppShell, openSettings } from "../../app/e2e/support/helpers/app";
|
||||
@@ -213,3 +215,49 @@ for (const { platform, keys, label, firstCombo, secondCombo } of [
|
||||
await expectInterruptShortcut(page, label);
|
||||
});
|
||||
}
|
||||
|
||||
async function rebindTabNumbers(page: Page) {
|
||||
await captureShortcut(page, "Jump to tab", "workspace-tab-jump-index", "Control+1");
|
||||
await page.getByRole("button", { name: "Done", exact: true }).click();
|
||||
}
|
||||
|
||||
async function expectTabNumberRange(page: Page) {
|
||||
const row = page.getByText("Jump to tab", { exact: true }).locator("..");
|
||||
await expect(row.getByText("⌃1-9", { exact: true })).toBeVisible();
|
||||
}
|
||||
|
||||
async function openTwoDraftTabs(page: Page, workspaceId: string) {
|
||||
await installDesktopBridge(page);
|
||||
await gotoWorkspace(page, workspaceId);
|
||||
await clickNewChat(page);
|
||||
await clickNewChat(page);
|
||||
await expect(
|
||||
page.locator('[data-testid^="workspace-tab-draft_"]').filter({ visible: true }),
|
||||
).toHaveCount(2);
|
||||
await openSettings(page);
|
||||
await openSettingsSection(page, "shortcuts");
|
||||
}
|
||||
|
||||
async function expectTabNumberNavigation(page: Page) {
|
||||
const tabs = page.locator('[data-testid^="workspace-tab-draft_"]').filter({ visible: true });
|
||||
await page.keyboard.press("Control+1");
|
||||
await expect(tabs.nth(0)).toHaveAttribute("aria-selected", "true");
|
||||
await page.keyboard.press("Control+2");
|
||||
await expect(tabs.nth(1)).toHaveAttribute("aria-selected", "true");
|
||||
}
|
||||
|
||||
test("rebinding Jump to tab preserves the number group after reload", async ({
|
||||
page,
|
||||
withWorkspace,
|
||||
}) => {
|
||||
const workspace = await withWorkspace({ prefix: "tab-number-rebind-" });
|
||||
await openTwoDraftTabs(page, workspace.workspaceId);
|
||||
await rebindTabNumbers(page);
|
||||
await clickSettingsBackToWorkspace(page);
|
||||
await expectTabNumberNavigation(page);
|
||||
await page.reload();
|
||||
await expectTabNumberNavigation(page);
|
||||
await openSettings(page);
|
||||
await openSettingsSection(page, "shortcuts");
|
||||
await expectTabNumberRange(page);
|
||||
});
|
||||
|
||||
@@ -127,7 +127,7 @@ function inspectChatDragExclusions(scroll: Element) {
|
||||
const headerRect = header.getBoundingClientRect();
|
||||
const headerY = headerRect.top + headerRect.height / 2;
|
||||
const content = scroll.firstElementChild;
|
||||
const focusScope = scroll.closest("[tabindex]");
|
||||
const focusScope = scroll.closest("[data-window-content]")?.parentElement?.closest("[tabindex]");
|
||||
if (!content || !focusScope) throw new Error("Expected chat content and its focus scope");
|
||||
const contentRect = content.getBoundingClientRect();
|
||||
const chatX = (contentRect.left + contentRect.right) / 2;
|
||||
|
||||
@@ -547,8 +547,13 @@ class AcpRuntime {
|
||||
return sessionCapabilities;
|
||||
}
|
||||
|
||||
async discover(cwd = process.cwd()): Promise<ProviderCatalog> {
|
||||
const response = await this.call(this.connection.newSession({ cwd, mcpServers: [] }));
|
||||
async discover(cwd?: string): Promise<ProviderCatalog> {
|
||||
if (cwd === undefined && this.options.options.acpOptions?.workspaceOnlyCatalog) {
|
||||
return { models: [], modes: [] };
|
||||
}
|
||||
const response = await this.call(
|
||||
this.connection.newSession({ cwd: cwd ?? process.cwd(), mcpServers: [] }),
|
||||
);
|
||||
this.nativeSessionId = response.sessionId;
|
||||
this.modes = response.modes;
|
||||
this.configOptions = response.configOptions ?? [];
|
||||
|
||||
@@ -272,6 +272,39 @@ lines.on("line", (line) => {
|
||||
}
|
||||
});
|
||||
|
||||
it("still reports initialization failures for workspace-only global discovery", async () => {
|
||||
let unavailable = false;
|
||||
const { connector } = connectorHarness({
|
||||
handleRequest(instance, request) {
|
||||
if (unavailable && request.method === "initialize") {
|
||||
instance.reject(request, "Bridge unavailable");
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
});
|
||||
const registration = runAcpProvider({
|
||||
id: "workspace-acp",
|
||||
label: "Workspace ACP",
|
||||
connector,
|
||||
acpOptions: { workspaceOnlyCatalog: true },
|
||||
});
|
||||
const connection = await registration.connect({ versions: [1], capabilities: [] });
|
||||
const events: ProviderEvent[] = [];
|
||||
connection.onEvent((event) => events.push(event));
|
||||
try {
|
||||
unavailable = true;
|
||||
await connection.send({ type: "catalog", requestId: "global" });
|
||||
expect(await waitForEvent(events, (event) => event.type === "request.failed")).toMatchObject({
|
||||
requestId: "global",
|
||||
error: { message: expect.stringContaining("Bridge unavailable") },
|
||||
});
|
||||
expect(events.some((event) => event.type === "catalog")).toBe(false);
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects connection cleanly when the ACP executable does not exist", async () => {
|
||||
const registration = runAcpProvider({
|
||||
id: "missing-acp",
|
||||
|
||||
@@ -44,6 +44,8 @@ export type AcpConnector = () => AcpStream | Promise<AcpStream>;
|
||||
export interface AcpOptions {
|
||||
protocol?: "auto" | "v1";
|
||||
startupTimeoutMs?: number;
|
||||
/** Global discovery initializes ACP but returns an empty catalog without opening a session. */
|
||||
workspaceOnlyCatalog?: boolean;
|
||||
waitForInitialCommands?: boolean;
|
||||
initialCommandsTimeoutMs?: number;
|
||||
}
|
||||
|
||||
@@ -89,7 +89,7 @@
|
||||
"speech:transcribe:local": "tsx scripts/transcribe-local-wav.ts",
|
||||
"test": "npm run test:unit && npm run test:integration",
|
||||
"test:unit": "vitest run --fileParallelism --exclude \"**/*.e2e.test.ts\"",
|
||||
"test:integration": "vitest run --maxWorkers=1 src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts && vitest run --maxWorkers=1 src/server/daemon-e2e/git-operations.e2e.test.ts -t \"merges into\" && vitest run --maxWorkers=1 src/server/session.create-agent-worktree-autoarchive.e2e.test.ts -t \"creates a worktree and auto-archives both\" && vitest run --maxWorkers=1 src/server/agent/providers/opencode-bridge.local.e2e.test.ts -t \"versioned runtime\" && vitest run --maxWorkers=1 src/server/daemon-e2e/relay-transport.e2e.test.ts -t \"oversized attachments\"",
|
||||
"test:integration": "vitest run --maxWorkers=1 src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/workspace-create-worktree-source.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts && vitest run --maxWorkers=1 src/server/daemon-e2e/git-operations.e2e.test.ts -t \"merges into\" && vitest run --maxWorkers=1 src/server/session.create-agent-worktree-autoarchive.e2e.test.ts -t \"creates a worktree and auto-archives both\" && vitest run --maxWorkers=1 src/server/agent/providers/opencode-bridge.local.e2e.test.ts -t \"versioned runtime\" && vitest run --maxWorkers=1 src/server/daemon-e2e/relay-transport.e2e.test.ts -t \"oversized attachments\"",
|
||||
"test:hub-cli-contract": "vitest run --maxWorkers=1 src/server/hub/hub-cli-contract.test.ts",
|
||||
"test:integration:all": "npm run test:e2e",
|
||||
"test:integration:real": "vitest run real.e2e.test.ts",
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { afterEach, describe, expect, test } from "vitest";
|
||||
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const dir of tempDirs.splice(0)) {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
describe("transcribe-local-wav CLI", () => {
|
||||
test("initializes the complete speech provider configuration", () => {
|
||||
const modelsDir = mkdtempSync(path.join(tmpdir(), "paseo-transcribe-local-"));
|
||||
tempDirs.push(modelsDir);
|
||||
const missingWav = path.join(modelsDir, "missing.wav");
|
||||
const scriptPath = fileURLToPath(new URL("./transcribe-local-wav.ts", import.meta.url));
|
||||
|
||||
const result = spawnSync(
|
||||
process.execPath,
|
||||
["--import", "tsx", scriptPath, missingWav, "--models-dir", modelsDir],
|
||||
{
|
||||
encoding: "utf8",
|
||||
timeout: 15_000,
|
||||
},
|
||||
);
|
||||
|
||||
expect(result.error).toBeUndefined();
|
||||
expect(result.status).not.toBe(0);
|
||||
// The worker client is lazy, so reaching the missing WAV proves provider initialization completed first.
|
||||
expect(result.stderr).toContain("ENOENT");
|
||||
expect(result.stderr).toContain(missingWav);
|
||||
expect(result.stderr).not.toContain("Cannot read properties of undefined");
|
||||
});
|
||||
});
|
||||
@@ -120,6 +120,7 @@ async function main(): Promise<void> {
|
||||
|
||||
const providers: RequestedSpeechProviders = {
|
||||
dictationStt: { provider: "local", explicit: true },
|
||||
voiceTurnDetection: { provider: "local", explicit: false, enabled: false },
|
||||
voiceStt: { provider: "local", explicit: true },
|
||||
// Not used here, but required by the shared runtime config shape.
|
||||
voiceTts: { provider: "openai", explicit: false },
|
||||
|
||||
@@ -7073,3 +7073,74 @@ describe("Codex denied plan approvals", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test.each([
|
||||
{ statuses: ["completed"], expected: ["completed"] },
|
||||
{ statuses: ["completed", "inProgress"], expected: ["completed", "running"] },
|
||||
{ statuses: ["inProgress", "completed"], expected: ["running", "completed"] },
|
||||
])(
|
||||
"restores each native child status without settling a running sibling: $statuses",
|
||||
async ({ statuses, expected }) => {
|
||||
const ids = statuses.map((_, i) => `child-${i}`);
|
||||
const app = createFakeCodexAppServer({
|
||||
"thread/read": (params) => {
|
||||
const id = (params as { threadId: string }).threadId;
|
||||
if (id !== "parent")
|
||||
return { thread: { turns: [{ status: statuses[ids.indexOf(id)], items: [] }] } };
|
||||
return {
|
||||
thread: {
|
||||
turns: [
|
||||
{
|
||||
status: "completed",
|
||||
items: [
|
||||
{
|
||||
type: "collabAgentToolCall",
|
||||
id: "shared-spawn",
|
||||
tool: "spawnAgent",
|
||||
status: "completed",
|
||||
receiverThreadIds: ids,
|
||||
agentsStates: Object.fromEntries(
|
||||
ids.map((childId) => [childId, { status: "running" }]),
|
||||
),
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
const session = new CodexAppServerAgentSession(
|
||||
{ provider: "codex", cwd: process.cwd(), modeId: "full-access" },
|
||||
{ sessionId: "parent" },
|
||||
createTestLogger(),
|
||||
async () => app.child,
|
||||
{},
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
undefined,
|
||||
"history",
|
||||
);
|
||||
try {
|
||||
await session.connect();
|
||||
const statusesById = new Map<string, string | undefined>();
|
||||
let parentStatus: string | undefined;
|
||||
for await (const event of session.streamHistory()) {
|
||||
if (
|
||||
event.type === "timeline" &&
|
||||
event.item.type === "tool_call" &&
|
||||
event.item.callId === "shared-spawn"
|
||||
)
|
||||
parentStatus = event.item.status;
|
||||
if (event.type === "provider_subagent" && event.event.type === "upsert")
|
||||
statusesById.set(event.event.id, event.event.status);
|
||||
}
|
||||
expect(ids.map((id) => statusesById.get(id))).toEqual(expected);
|
||||
expect(parentStatus).toBe(expected.includes("running") ? "running" : "completed");
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
app.assertNoErrors();
|
||||
},
|
||||
);
|
||||
|
||||
@@ -20,6 +20,13 @@ readline.createInterface({ input: process.stdin }).on("line", (line) => {
|
||||
let result = {};
|
||||
if (request.method === "initialize")
|
||||
result = { protocolVersion: 1, agentCapabilities: {}, authMethods: [] };
|
||||
if (request.method === "session/new" && request.params.cwd !== process.env.HOPLITE_TEST_CWD) {
|
||||
send({
|
||||
id: request.id,
|
||||
error: { code: -32602, message: "No Hoplite project for this directory" },
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (request.method === "session/new")
|
||||
result = {
|
||||
sessionId: "hoplite-fixture",
|
||||
|
||||
@@ -199,10 +199,13 @@ test("bundled Hoplite requires a config entry and removal survives restart", asy
|
||||
hoplite: {
|
||||
enabled: true,
|
||||
command: [process.execPath, path.resolve(import.meta.dirname, "hoplite-fixture.cjs")],
|
||||
env: { HOPLITE_TEST_RECORD: record },
|
||||
env: { HOPLITE_TEST_RECORD: record, HOPLITE_TEST_CWD: root },
|
||||
},
|
||||
},
|
||||
});
|
||||
const globalModels = await client.listProviderModels("hoplite");
|
||||
expect(globalModels.error).toBeNull();
|
||||
expect(globalModels.models).toEqual([]);
|
||||
await expect
|
||||
.poll(
|
||||
async () =>
|
||||
@@ -211,9 +214,14 @@ test("bundled Hoplite requires a config entry and removal survives restart", asy
|
||||
)?.status,
|
||||
)
|
||||
.toBe("ready");
|
||||
expect((await client.listProviderModels("hoplite")).models.map((model) => model.id)).toEqual([
|
||||
"fixture-model",
|
||||
]);
|
||||
const workspaceModels = await client.listProviderModels("hoplite", { cwd: root });
|
||||
expect(workspaceModels.error).toBeNull();
|
||||
expect(workspaceModels.models.map((model) => model.id)).toEqual(["fixture-model"]);
|
||||
await client.refreshProvidersSnapshot({ providers: ["hoplite"] });
|
||||
expect((await client.listProviderModels("hoplite")).models).toEqual([]);
|
||||
expect(
|
||||
(await client.listProviderModels("hoplite", { cwd: root })).models.map((model) => model.id),
|
||||
).toEqual(["fixture-model"]);
|
||||
const agent = await client.createAgent({
|
||||
provider: "hoplite",
|
||||
cwd: root,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { existsSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { expect, onTestFinished, test } from "vitest";
|
||||
@@ -18,6 +19,7 @@ function createGitRepoWithBranch(): { repoDir: string; tempRoot: string } {
|
||||
const tempRoot = mkdtempSync(path.join(tmpdir(), "workspace-create-worktree-source-"));
|
||||
const repoDir = path.join(tempRoot, "repo");
|
||||
execFileSync("git", ["init", "-b", "main", repoDir], { stdio: "pipe" });
|
||||
execFileSync("git", ["config", "core.autocrlf", "false"], { cwd: repoDir, stdio: "pipe" });
|
||||
execFileSync("git", ["config", "user.email", "test@getpaseo.local"], {
|
||||
cwd: repoDir,
|
||||
stdio: "pipe",
|
||||
@@ -60,10 +62,134 @@ test("workspace.create worktree source forwards action=checkout + refName into t
|
||||
} finally {
|
||||
await client.close().catch(() => undefined);
|
||||
await daemon.close();
|
||||
rmSync(tempRoot, { recursive: true, force: true });
|
||||
await rm(tempRoot, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
||||
}
|
||||
}, 180000);
|
||||
|
||||
test.each([false, true])(
|
||||
"workspace.create opens worktree.terminals (setup service: %s)",
|
||||
async (withSetupService) => {
|
||||
const daemon = await createTestPaseoDaemon();
|
||||
const { repoDir, tempRoot } = createGitRepoWithBranch();
|
||||
writeFileSync(
|
||||
path.join(repoDir, "paseo.json"),
|
||||
JSON.stringify({
|
||||
worktree: {
|
||||
...(withSetupService
|
||||
? {
|
||||
// Launch the Windows service asynchronously so it outlives
|
||||
// the setup command instead of holding setup open.
|
||||
setup:
|
||||
process.platform === "win32"
|
||||
? "Start-Process -FilePath node -ArgumentList 'setup.cjs','serve' -WorkingDirectory (Get-Location).Path -WindowStyle Hidden; while (!(Test-Path setup-pid.txt)) { Start-Sleep -Milliseconds 25 }"
|
||||
: "node setup.cjs",
|
||||
}
|
||||
: {}),
|
||||
terminals: [
|
||||
{ name: "preview", command: "echo paseo-auto-terminal >> terminal-marker.txt" },
|
||||
],
|
||||
},
|
||||
}),
|
||||
);
|
||||
writeFileSync(
|
||||
path.join(repoDir, "setup.cjs"),
|
||||
`
|
||||
const fs = require("node:fs");
|
||||
if (process.argv[2] === "serve") {
|
||||
require("node:net").createServer().listen(Number(process.env.PASEO_WORKTREE_PORT), "127.0.0.1", () => {
|
||||
fs.writeFileSync("setup-pid.txt", String(process.pid));
|
||||
process.send?.("ready");
|
||||
});
|
||||
} else {
|
||||
const child = require("node:child_process").spawn(process.execPath, [__filename, "serve"], {
|
||||
detached: true,
|
||||
stdio: ["ignore", "ignore", "ignore", "ipc"],
|
||||
});
|
||||
child.once("message", () => { child.disconnect(); child.unref(); });
|
||||
}
|
||||
`,
|
||||
);
|
||||
execFileSync("git", ["add", "paseo.json", "setup.cjs"], { cwd: repoDir, stdio: "pipe" });
|
||||
execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", "add paseo.json"], {
|
||||
cwd: repoDir,
|
||||
stdio: "pipe",
|
||||
});
|
||||
const client = new DaemonClient({
|
||||
url: `ws://127.0.0.1:${daemon.port}/ws`,
|
||||
appVersion: "0.1.82",
|
||||
});
|
||||
|
||||
let workspaceCwd: string | undefined;
|
||||
try {
|
||||
await client.connect();
|
||||
|
||||
// This is the request the New Workspace screen sends: the workspace is
|
||||
// created on its own, with no agent in the same request.
|
||||
const result = await client.createWorkspace({
|
||||
source: {
|
||||
kind: "worktree",
|
||||
cwd: repoDir,
|
||||
action: "branch-off",
|
||||
branchName: "feature/auto-terminals",
|
||||
worktreeSlug: "feature-auto-terminals",
|
||||
baseBranch: "main",
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.error).toBeNull();
|
||||
const workspace = result.workspace;
|
||||
if (!workspace) {
|
||||
throw new Error("Expected a created workspace");
|
||||
}
|
||||
|
||||
workspaceCwd = workspace.workspaceDirectory;
|
||||
if (withSetupService) {
|
||||
await expect
|
||||
.poll(() => existsSync(path.join(workspaceCwd!, "setup-pid.txt")), { timeout: 30000 })
|
||||
.toBe(true);
|
||||
}
|
||||
await expect
|
||||
.poll(async () => (await client.fetchWorkspaceSetupStatus(workspace.id)).snapshot, {
|
||||
timeout: 30000,
|
||||
})
|
||||
.toMatchObject({ status: "completed", error: null });
|
||||
await expect
|
||||
.poll(
|
||||
async () =>
|
||||
(
|
||||
await client.listTerminals(workspace.workspaceDirectory, undefined, {
|
||||
workspaceId: workspace.id,
|
||||
})
|
||||
).terminals.map((terminal) => terminal.name),
|
||||
{ timeout: 30000 },
|
||||
)
|
||||
.toContain("preview");
|
||||
await expect
|
||||
.poll(
|
||||
() => {
|
||||
const marker = path.join(workspaceCwd!, "terminal-marker.txt");
|
||||
return existsSync(marker) ? readFileSync(marker, "utf8").trim() : null;
|
||||
},
|
||||
{ timeout: 10000 },
|
||||
)
|
||||
.toBe("paseo-auto-terminal");
|
||||
expect(
|
||||
(await client.listTerminals(workspaceCwd, undefined, { workspaceId: workspace.id }))
|
||||
.terminals,
|
||||
).toHaveLength(1);
|
||||
} finally {
|
||||
const pidFile = workspaceCwd && path.join(workspaceCwd, "setup-pid.txt");
|
||||
if (pidFile && existsSync(pidFile)) {
|
||||
process.kill(Number(readFileSync(pidFile, "utf8")));
|
||||
}
|
||||
await client.close().catch(() => undefined);
|
||||
await daemon.close();
|
||||
await rm(tempRoot, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
||||
}
|
||||
},
|
||||
180000,
|
||||
);
|
||||
|
||||
test("existing branch changes remain visible after archive and restore", async () => {
|
||||
const daemon = await createTestPaseoDaemon();
|
||||
const { repoDir, tempRoot } = createGitRepoWithBranch();
|
||||
@@ -74,7 +200,7 @@ test("existing branch changes remain visible after archive and restore", async (
|
||||
onTestFinished(async () => {
|
||||
await client.close().catch(() => undefined);
|
||||
await daemon.close();
|
||||
rmSync(tempRoot, { recursive: true, force: true });
|
||||
await rm(tempRoot, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
||||
});
|
||||
runGit(repoDir, "switch", "feature/existing-branch");
|
||||
commitFile(repoDir, "feature.txt", "feature change\n");
|
||||
@@ -134,7 +260,7 @@ test("workspace.create keeps a branch-off name separate from its worktree slug",
|
||||
} finally {
|
||||
await client.close().catch(() => undefined);
|
||||
await daemon.close();
|
||||
rmSync(tempRoot, { recursive: true, force: true });
|
||||
await rm(tempRoot, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
||||
}
|
||||
}, 180000);
|
||||
|
||||
@@ -168,7 +294,7 @@ test("workspace.create accepts a Git-valid branch-off name outside Paseo slug sy
|
||||
} finally {
|
||||
await client.close().catch(() => undefined);
|
||||
await daemon.close();
|
||||
rmSync(tempRoot, { recursive: true, force: true });
|
||||
await rm(tempRoot, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
||||
}
|
||||
}, 180000);
|
||||
|
||||
@@ -210,7 +336,7 @@ test("workspace.create always creates a new worktree when the slug is already oc
|
||||
} finally {
|
||||
await client.close().catch(() => undefined);
|
||||
await daemon.close();
|
||||
rmSync(tempRoot, { recursive: true, force: true });
|
||||
await rm(tempRoot, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
||||
}
|
||||
}, 180000);
|
||||
|
||||
@@ -255,7 +381,7 @@ test("workspace.create suffixes past an occupied detached worktree", async () =>
|
||||
} finally {
|
||||
await client.close().catch(() => undefined);
|
||||
await daemon.close();
|
||||
rmSync(tempRoot, { recursive: true, force: true });
|
||||
await rm(tempRoot, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
||||
}
|
||||
}, 180000);
|
||||
|
||||
@@ -297,7 +423,7 @@ test("workspace.create suffixes an occupied checkout branch", async () => {
|
||||
} finally {
|
||||
await client.close().catch(() => undefined);
|
||||
await daemon.close();
|
||||
rmSync(tempRoot, { recursive: true, force: true });
|
||||
await rm(tempRoot, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
||||
}
|
||||
}, 180000);
|
||||
|
||||
@@ -340,7 +466,7 @@ async function createRestorableWorkspace(baseRef: string) {
|
||||
onTestFinished(async () => {
|
||||
await client.close().catch(() => undefined);
|
||||
await daemon.close();
|
||||
rmSync(tempRoot, { recursive: true, force: true });
|
||||
await rm(tempRoot, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
||||
});
|
||||
createDivergentBases(repoDir);
|
||||
await client.connect();
|
||||
|
||||
@@ -593,13 +593,10 @@ export async function runWorktreeAutoTerminals(options: {
|
||||
workspaceId: string;
|
||||
worktree: WorktreeConfig;
|
||||
workspaceCwd: string;
|
||||
runtimeEnv: WorktreeRuntimeEnv;
|
||||
terminalManager: TerminalManager | null;
|
||||
logger?: Logger;
|
||||
}): Promise<void> {
|
||||
const runtimeEnv = await resolveWorktreeRuntimeEnv({
|
||||
worktreePath: options.worktree.worktreePath,
|
||||
branchName: options.worktree.branchName,
|
||||
});
|
||||
await runWorktreeTerminalBootstrap(
|
||||
{
|
||||
agentId: options.workspaceId,
|
||||
@@ -610,7 +607,7 @@ export async function runWorktreeAutoTerminals(options: {
|
||||
appendTimelineItem: async () => true,
|
||||
logger: options.logger,
|
||||
},
|
||||
runtimeEnv,
|
||||
options.runtimeEnv,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -817,7 +817,6 @@ export async function handleWorkspaceSetupRunRequest(
|
||||
slug: basename(worktree.worktreePath),
|
||||
worktreePath: worktree.worktreePath,
|
||||
workspaceCwd: workspace.cwd,
|
||||
runAutoTerminals: true,
|
||||
},
|
||||
signal,
|
||||
),
|
||||
@@ -857,7 +856,6 @@ export async function runWorktreeSetupInBackground(
|
||||
slug: string;
|
||||
worktreePath: string;
|
||||
workspaceCwd?: string;
|
||||
runAutoTerminals?: boolean;
|
||||
},
|
||||
signal?: AbortSignal,
|
||||
): Promise<void> {
|
||||
@@ -898,18 +896,18 @@ export async function runWorktreeSetupInBackground(
|
||||
} else {
|
||||
const workspaceCwd = options.workspaceCwd ?? worktree.worktreePath;
|
||||
const setupCommands = getWorktreeSetupCommands(workspaceCwd);
|
||||
const runtimeEnv = await resolveWorktreeRuntimeEnv({
|
||||
worktreePath: worktree.worktreePath,
|
||||
branchName: worktree.branchName,
|
||||
repoRootPath: options.repoRoot,
|
||||
});
|
||||
dependencies.terminalManager?.registerCwdEnv({
|
||||
cwd: workspaceCwd,
|
||||
env: runtimeEnv,
|
||||
});
|
||||
if (setupCommands.length === 0) {
|
||||
emitSetupProgress("completed", null);
|
||||
} else {
|
||||
const runtimeEnv = await resolveWorktreeRuntimeEnv({
|
||||
worktreePath: worktree.worktreePath,
|
||||
branchName: worktree.branchName,
|
||||
repoRootPath: options.repoRoot,
|
||||
});
|
||||
dependencies.terminalManager?.registerCwdEnv({
|
||||
cwd: workspaceCwd,
|
||||
env: runtimeEnv,
|
||||
});
|
||||
setupResults = await runWorktreeSetupCommands({
|
||||
worktreePath: workspaceCwd,
|
||||
branchName: worktree.branchName,
|
||||
@@ -924,15 +922,14 @@ export async function runWorktreeSetupInBackground(
|
||||
});
|
||||
emitSetupProgress("completed", null);
|
||||
}
|
||||
if (options.runAutoTerminals) {
|
||||
await runWorktreeAutoTerminals({
|
||||
workspaceId,
|
||||
worktree,
|
||||
workspaceCwd,
|
||||
terminalManager: dependencies.terminalManager,
|
||||
logger: dependencies.sessionLogger,
|
||||
});
|
||||
}
|
||||
await runWorktreeAutoTerminals({
|
||||
workspaceId,
|
||||
worktree,
|
||||
workspaceCwd,
|
||||
runtimeEnv,
|
||||
terminalManager: dependencies.terminalManager,
|
||||
logger: dependencies.sessionLogger,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof WorktreeSetupError) {
|
||||
|
||||
@@ -11,6 +11,7 @@ export function createHopliteProvider(): ProviderRegistration {
|
||||
description: "Hoplite's coding agent through the local `hoplite acp` bridge",
|
||||
icon: "icon.svg",
|
||||
command: ["hoplite", "acp"],
|
||||
acpOptions: { workspaceOnlyCatalog: true },
|
||||
transformers: [runPhaseTransformer],
|
||||
}),
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user