Compare commits

...
Author SHA1 Message Date
paseo-bot[bot] 2e13844f88 test(app): retain Android quiet-turn redraw reproduction 2026-10-16 05:23:05 +02:00
paseo-bot[bot]anddbunk903 5c2a1552df fix(app): preserve number groups when rebinding navigation shortcuts (#7065)
Recording a digit for tab or workspace navigation replaced the existing
1–9 wildcard with one literal key. Preserve the group when capturing a
replacement and display its range after saving and reloading.

Adapted the number-group fix from getpaseo/paseo#5237, with independent
failing-first renderer reproduction and tab/workspace matcher coverage.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: dbunk903 <74584941+dbunk903@users.noreply.github.com>
2026-10-16 04:14:28 +02:00
e0de0fdf6f Read cached chats while other agents stream (#7074)
* perf(app): overlay pending replica rows on read instead of forcing persists

readRows flushed every pending change to storage, read, and retried
whenever the host revision moved. Every stream reducer flush (48 ms) and
every agent delta advanced that revision, so opening another agent or
workspace on a host with a streaming agent re-serialized the whole
pending batch per iteration and could spin until the stream paused.

Reads now run on the write queue, so no drained batch is mid-apply while
a read runs, and rows still pending in memory are overlaid for the
requested keys. A read never forces a persist and never waits for the
host to go quiet.

Persist retries after a storage failure back off exponentially (1 s to
60 s) and log the failure instead of re-serializing every second.

Before: one readAgent during a 200-commit stream cost 201 store reads and
200 forced persists; a permanently failing store was written 30 times in
30 s. After: 1 read, 0 persists; 5 writes in 30 s.

Fixes #4813
Refs #4814

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(app): log replica persist retry failures

---------

Co-authored-by: Ivan Malison <IvanMalison@gmail.com>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: paseo-bot[bot] <paseo-bot[bot]@users.noreply.github.com>
2026-10-16 03:15:23 +02:00
8d424e039e Reduce rendering cost in long chats (#7052)
* perf(app): stop re-walking the timeline on every streamed delta

Every coalesced delta rebuilds the stream render model with the same
tail. The model re-sliced the tail at the history-window start on every
call, so the rendered tail was a fresh array per delta and every WeakMap
keyed on it (ordering, history split, turn timing, the layout history
cache, row revision) missed each time. Cache the slice by tail identity
and window start.

Turn timing then still walked the whole rendered tail per delta and
allocated a new assistant-timing Map, which the layout memo depends on.
Split the walk: the tail is walked once per tail identity and the head is
walked from the carried open turn per delta. The Map keeps its identity
while the head adds no completed turn.

Adds identity-contract tests and a vitest bench for the per-delta
pipeline. 200 deltas over a 2,000-item timeline, mean per run:
default mounted window 5.68ms -> 2.82ms, history fully revealed
16.95ms -> 1.81ms.

Fixes #4816

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* perf(app): keep the stream view's per-delta work bounded by the head

The chat outline concatenated tail and head, reduced over the result in
the render body, and rebuilt jumpToPrompt on every delta even when the
outline was disabled, which is every native viewport. Memoize the tail's
contribution, scan only the head per delta, do nothing while disabled,
make jumpToPrompt a stable event so the rail's memo holds, and republish
the active prompt only when the index or reading position changes.

The view built a Set of every mounted id plus the live head per delta for
the outline's pending-jump check; key it on mounted history only and
treat live head rows as always mounted. Split plugin projection so a head
change does not re-project the tail, memoize the history-window boundary
lookup, and read the turn presentation's submission flag with some()
instead of allocating a filtered array.

Refs #4816

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* test(app): confirm full history before measuring streaming

---------

Co-authored-by: Ivan Malison <IvanMalison@gmail.com>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-10-16 01:15:40 +02:00
paseo-bot[bot]andIvan Pantic d9b874f9d0 Scroll chat with Page Up and Page Down after clicking messages (#7033)
* fix(app): focus chat feed when clicking message content

* test(app): wait for new chat output before checking scroll position

Co-authored-by: Ivan Pantic <panta@talentkit.io>

* test(app): capture the keyboard paging regression

* test(app): verify paged chat text stays in place

---------

Co-authored-by: Ivan Pantic <panta@talentkit.io>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-10-16 00:14:23 +02:00
f56c013928 Open configured terminals after worktree setup (#6999)
* fix(server): open worktree.terminals when a workspace is created on its own

runWorktreeSetupInBackground only opened the paseo.json worktree.terminals
when its caller passed runAutoTerminals, and only the fork-PR "allow setup"
handler did. workspace.create, the request the New Workspace screen sends,
ran worktree.setup and then skipped the terminals.

Both callers want the terminals, so the flag goes away: terminals follow a
successful setup on a newly created worktree. Reused worktrees stay excluded
by shouldBootstrap, and the agent setup continuation never reaches this
function, so nothing opens twice.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* test(server): run automatic terminal regressions in CI

Include workspace creation in the existing integration command, and append to the terminal marker so repeated command execution fails the regression.

* test(server): make workspace fixtures portable on Windows

Run the setup fixture through a command accepted by PowerShell, await its readiness, and fix the fixture Git line-ending policy. Allow Windows directory locks to settle during cleanup.

* test(server): expose setup failures and await fixture cleanup

Check the public setup status before terminal startup so failures distinguish setup errors from terminal creation. Use asynchronous directory removal so Windows cleanup retries leave the event loop available.

* test(server): start the Windows setup service asynchronously

The Windows regression starts its service but setup stays running, so terminal bootstrap is never reached. Launch the fixture service explicitly with Start-Process and retain the readiness and setup-completion assertions.

---------

Co-authored-by: David Yang <9925+davidyang@users.noreply.github.com>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-10-15 23:11:13 +02:00
paseo-bot[bot]andSleroq 208e323035 Keep usage providers in place after refresh (#6947)
* fix(app): preserve usage provider order across refreshes

* test(usage): keep refresh and scrolling journeys stable

Usage reports can follow the long fixture card, so a fixed wheel distance
can scroll past its final window. Target the named windows with wheel
input while preserving the visibility checks. Assert refreshed provider
order through visible names and keep viewport setup in journey helpers.

Co-authored-by: Sleroq <hireme@sleroq.link>

---------

Co-authored-by: Sleroq <hireme@sleroq.link>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-10-15 21:16:52 +02:00
Mohamed Boudra ec7446add4 docs(readme): enlarge sponsor logos 2026-10-15 21:11:51 +02:00
Mohamed Boudra b30302b630 docs(changelog): 0.11.4 2026-10-15 20:26:28 +02:00
Mohamed Boudra 7aa3fac069 fix(providers): scope project-dependent model discovery to workspaces
Global discovery has no linked project. Initialize the bridge to check availability, but only open discovery sessions when a workspace is supplied.
2026-10-16 01:19:00 +07:00
46 changed files with 1533 additions and 231 deletions
+7 -1
View File
@@ -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))
+1 -1
View File
@@ -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>
+5
View File
@@ -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
View File
@@ -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,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(
@@ -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);
}
});
@@ -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();
@@ -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,
});
},
);
});
+22 -30
View File
@@ -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) {
+16 -11
View File
@@ -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}>
@@ -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[] {
@@ -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",
@@ -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 () => {
+64 -19
View File
@@ -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);
+2 -2
View File
@@ -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)),
);
}
+95 -2
View File
@@ -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,
});
});
});
+121 -47
View File
@@ -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,
};
}
+16
View File
@@ -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]);
});
+13 -6
View File
@@ -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 ?? [];
+33
View File
@@ -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",
+2
View File
@@ -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;
}
+1 -1
View File
@@ -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",
@@ -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,
);
}
+17 -20
View File
@@ -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],
}),
};
@@ -0,0 +1,53 @@
"""Failing rendering probe for https://github.com/getpaseo/paseo/issues/4634.
Prepare the packaged Android app through agent-device: foreground a conversation
with a quiet running turn, close the sidebar, and leave the device untouched.
Run this probe, then repeat on an idle conversation while that turn continues.
The default 10 FPS ceiling tests the report's expectation of few redraws. It is
an investigation hypothesis, not an agreed product performance budget. Status
rings and tool-label shimmer also animate; a failure does not identify which
animation draws, prove whole-conversation repainting, or measure device heating.
This device-dependent probe is deliberately outside the regular test suite.
"""
import argparse
import json
import re
import subprocess
import time
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--package", default="sh.paseo")
parser.add_argument("--seconds", type=float, default=10)
parser.add_argument("--max-fps", type=float, default=10)
args = parser.parse_args()
if args.seconds <= 0 or args.max_fps < 0:
parser.error("seconds must be positive and max-fps must be nonnegative")
command = ["adb", "shell", "dumpsys", "gfxinfo", args.package]
subprocess.run(command + ["reset"], check=True, capture_output=True, text=True)
started = time.monotonic()
time.sleep(args.seconds)
output = subprocess.check_output(command, text=True)
elapsed = time.monotonic() - started
counts = re.findall(r"^Total frames rendered:\s+(\d+)", output, re.MULTILINE)
if not counts:
raise RuntimeError("No frame counter found; verify the app is running")
frames = int(counts[0])
fps = frames / elapsed
print(
json.dumps({"frames": frames, "seconds": elapsed, "fps": fps,
"maximumFps": args.max_fps}),
flush=True,
)
assert fps <= args.max_fps, (
f"Quiet-turn redraw hypothesis failed: {fps:.1f} FPS exceeds "
f"{args.max_fps:.1f} FPS. This establishes frame frequency, not cause."
)
if __name__ == "__main__":
main()