mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-01 14:12:51 +00:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9e635d9b46 | ||
|
|
3e859625ed | ||
|
|
83b1a3cbe2 | ||
|
|
0132f9f3e3 |
@@ -61,18 +61,6 @@ Gradle auto-fetches the platform/build-tools it needs once licenses are accepted
|
||||
|
||||
## Local build + install
|
||||
|
||||
The `react-native-svg@15.15.4` patch prevents header fades retaining their old painted size after
|
||||
rotation. Rebuild native Android after changing it; Metro reloads cannot update this code. Keep the
|
||||
resize hunks until upstream invalidates descendant geometry on canvas resize. Its instrumentation
|
||||
regression renders real gradient pixels across growing and shrinking layouts, including a nested
|
||||
group. From `packages/app/android`, run it on your selected emulator:
|
||||
|
||||
```bash
|
||||
ANDROID_SERIAL=emulator-5562 ./gradlew :react-native-svg:connectedDebugAndroidTest \
|
||||
-Pandroid.testInstrumentationRunnerArguments.class=com.horcrux.svg.SvgResizeTest \
|
||||
--no-daemon --max-workers=2 -Dorg.gradle.parallel=false
|
||||
```
|
||||
|
||||
The locked `expo-modules-core@57.0.23` needs the patch installed by `npm install`.
|
||||
It backports
|
||||
[Expo's Activity-result launcher fix](https://github.com/expo/expo/pull/49634): changing
|
||||
|
||||
@@ -65,7 +65,6 @@ per-agent examples and provider-specific keys.
|
||||
## Table of Contents
|
||||
|
||||
- [Extending a built-in provider](#extending-a-built-in-provider)
|
||||
- [OpenCode with an existing v2 server](#opencode-with-an-existing-v2-server)
|
||||
- [Z.AI (Zhipu) coding plan](#zai-zhipu-coding-plan)
|
||||
- [Alibaba Cloud (Qwen) coding plan](#alibaba-cloud-qwen-coding-plan)
|
||||
- [Codex with a custom OpenAI-compatible endpoint](#codex-with-a-custom-openai-compatible-endpoint)
|
||||
@@ -108,35 +107,6 @@ See [Codex with a custom OpenAI-compatible endpoint](#codex-with-a-custom-openai
|
||||
|
||||
---
|
||||
|
||||
## OpenCode with an existing v2 server
|
||||
|
||||
Paseo first uses an explicitly configured server, then a healthy locally registered OpenCode v2 service, then starts its own helper. It never stops a reused service. To select a server explicitly, set its URL in the provider environment:
|
||||
|
||||
```json
|
||||
{
|
||||
"agents": {
|
||||
"providers": {
|
||||
"opencode": {
|
||||
"env": {
|
||||
"PASEO_OPENCODE_SERVER_URL": "http://127.0.0.1:4096",
|
||||
"PASEO_OPENCODE_SERVER_PASSWORD": "<server password>"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`PASEO_OPENCODE_SERVER_URL` must be an absolute `http` or `https` URL. Omit `PASEO_OPENCODE_SERVER_PASSWORD` when the server has no authentication; when set, Paseo authenticates with HTTP Basic auth as `opencode`.
|
||||
|
||||
A configured URL takes precedence even when unreachable; Paseo reports the connection error. The local service registration supplies its own authentication. For a discovered local service, Paseo installs its bridge package in OpenCode's watched global plugin directory without changing the existing configuration. Refresh reads the existing service's catalogs without starting another server.
|
||||
|
||||
An explicitly configured server needs the bridge installed separately. Connect once and start a session: the setup error gives the local package directory. Copy that directory to the server's OpenCode global `plugins` directory, then retry. For a server on another machine, set `PASEO_OPENCODE_BRIDGE_PORT` in the Paseo OpenCode provider environment before starting Paseo, and set `PASEO_OPENCODE_BRIDGE_URL` to the URL the OpenCode server can use to reach that port. For example, an SSH reverse tunnel can expose the Paseo loopback port on the OpenCode host. The bridge token is exchanged through the OpenCode connection and is not written into the plugin package.
|
||||
|
||||
OpenCode's custom MCP registrations are shared by all sessions in a location. Paseo rejects custom MCP servers and per-agent process environment overrides on a reused server rather than applying them to other sessions or ignoring them. Session identity is applied to each session's shell environment. A Paseo-owned helper supports custom process and MCP settings; it is selected when there is no explicit URL or healthy registered service.
|
||||
|
||||
---
|
||||
|
||||
## Z.AI (Zhipu) coding plan
|
||||
|
||||
[Z.AI](https://z.ai) is a Chinese AI company (Zhipu AI) that offers an Anthropic-compatible API endpoint. Their GLM Coding Plan provides flat-rate access to GLM models through Claude Code's Anthropic API protocol. These are **not** Anthropic Claude models — they are Zhipu's own GLM models exposed through an Anthropic-compatible API.
|
||||
|
||||
+1
-3
@@ -89,7 +89,7 @@ OMP supports native Paseo host tools. The adapter registers the full caller-scop
|
||||
|
||||
Pi RPC extension UI dialog requests (`select`, `input`, `editor`, `confirm`) are bridged into Paseo question permissions and answered with `extension_ui_response`. Pi extensions such as `ask_user` may chain dialogs: for example, a `select` can be followed by an optional-comment `input`. When an `ask_user` tool call declares `allowComment: true`, Paseo presents the selection and optional comment as one question permission, answers Pi's initial `select` immediately, then auto-answers the follow-up optional `input` with the comment the user already supplied (or an empty string). Preserve placeholders and optional/skip semantics for standalone optional inputs so the app can still distinguish "skip this optional input" from "cancel the whole dialog." Fire-and-forget extension UI requests such as notifications are intentionally ignored by the provider adapter unless Paseo grows first-class UI for them.
|
||||
|
||||
OpenCode adapters target v1.14.46 and v2.0.10. V2 rejects versions older than 2.0.10. Paseo selects an explicit server, then a healthy local registered service, then its own helper. It never stops a reused service. A local service loads the Paseo bridge from its watched plugin directory; sessions bind their own bridge credentials through OpenCode RPC. See [OpenCode with an existing v2 server](custom-providers.md#opencode-with-an-existing-v2-server) for setup and isolation limits. Load v2 code and materialize its plugin only after positive v2 selection; v1 sessions remain undecorated. Keep upstream SDK types inside the version-specific adapter. OpenCode owns storage migration; a missing native session must fail resume rather than create a replacement. V2 has no native archive/unarchive operation: archiving affects Paseo only. V1 retains native archiving.
|
||||
OpenCode adapters target v1.14.46 and v2.0.10. V2 rejects binaries older than the tested 2.0.10 SDK at runtime selection. Runtime selection uses the configured command and environment. A recognized version is cached until provider configuration reload; a failed, timed-out, or unrecognized probe retains the v1 path and retries detection on the next operation. Load v2 code and materialize its plugin only after positive v2 selection; v1 sessions remain undecorated. Keep upstream SDK types inside the version-specific adapter. OpenCode owns storage migration; a missing native session must fail resume rather than create a replacement. V2 has no native archive/unarchive operation: archiving affects Paseo only. V1 retains native archiving.
|
||||
|
||||
Use OpenCode v2 execution events to trigger turn completion, with active-state and durable-log reconciliation after admission, reconnect, and while a turn remains active. Do not use `session.wait`: a healthy turn exceeding Node's HTTP headers deadline produces a transport error while OpenCode keeps working. The live event feed has no replay, and shutdown interruption preserves the previous idle outcome, so the session snapshot alone cannot recover missed execution events. Quiet streams are healthy: v2 heartbeats are SSE comments, not application events.
|
||||
|
||||
@@ -507,8 +507,6 @@ interface AgentSession {
|
||||
}
|
||||
```
|
||||
|
||||
`describePersistence()` returns a handle only once a new provider process could resume it. Reload, idle runtime collection and daemon restart resume whatever handle the agent stored; a stored agent without one starts a new session instead. When there is no handle, `AgentManager` stores `getRuntimeInfo().sessionId` as one, so that ID follows the same rule. Codex, for example, starts a thread when the agent is created but writes its rollout only at its first turn, and `thread/resume` fails for it until then, so its adapter reports neither ID before Codex announces that turn.
|
||||
|
||||
`setMode` and `setThinkingOption` may return an `AgentProviderNotice` when the provider knows the change needs user-facing context. For example, providers that stage changes until the next turn should return an `info` notice while a turn is already running. The app renders the notice generically as a toast; provider-specific lifecycle behavior stays in the provider implementation.
|
||||
|
||||
### Steps
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { test, expect, type Page } from "../support/fixtures";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
@@ -68,54 +67,3 @@ test("opening an assistant file link dismisses its tooltip over the file tab", a
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
async function readLinkedGuide(page: Page, linkName: string, content: string): Promise<void> {
|
||||
await page.getByRole("link", { name: linkName, exact: true }).click();
|
||||
await expect(page.getByTestId("markdown-preview-frame").filter({ visible: true })).toContainText(
|
||||
content,
|
||||
);
|
||||
}
|
||||
|
||||
async function returnToNestedLinks(page: Page): Promise<void> {
|
||||
await page.getByRole("button", { name: "Nested file links", exact: true }).click();
|
||||
await expect(page.getByRole("link", { name: "nested guide", exact: true })).toBeVisible();
|
||||
}
|
||||
|
||||
test("assistant directory paths find nested files and preserve exact workspace paths", async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
testInfo.setTimeout(120_000);
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "nested-file-link-",
|
||||
title: "Nested file links",
|
||||
featureValues: {
|
||||
mockStreamingAssistantResponse:
|
||||
"Read [nested guide](schema/x.md), [exact guide](schema/exact.md), and [missing guide](schema/missing.md).",
|
||||
mockStreamingAssistantIntervalMs: 5,
|
||||
},
|
||||
});
|
||||
try {
|
||||
await mkdir(path.join(agent.cwd, "repo-a/schema"), { recursive: true });
|
||||
execFileSync("git", ["init", "-b", "main"], { cwd: path.join(agent.cwd, "repo-a") });
|
||||
await writeFile(
|
||||
path.join(agent.cwd, "repo-a/schema/x.md"),
|
||||
"# Nested file content\n\nDetails\n",
|
||||
);
|
||||
await mkdir(path.join(agent.cwd, "schema"), { recursive: true });
|
||||
await writeFile(path.join(agent.cwd, "schema/exact.md"), "# Exact file content\n");
|
||||
await writeFile(path.join(agent.cwd, "repo-a/schema/exact.md"), "# Wrong nested content\n");
|
||||
await openAgentRoute(page, agent);
|
||||
await agent.client.sendAgentMessage(agent.agentId, "Show the file links.");
|
||||
await agent.client.waitForFinish(agent.agentId, 30_000);
|
||||
|
||||
await expect(page.getByRole("textbox", { name: "Message agent..." }).first()).toBeEnabled();
|
||||
await readLinkedGuide(page, "nested guide", "Nested file content");
|
||||
await returnToNestedLinks(page);
|
||||
await readLinkedGuide(page, "exact guide", "Exact file content");
|
||||
await returnToNestedLinks(page);
|
||||
await page.getByRole("link", { name: "missing guide", exact: true }).click();
|
||||
await expect(page.getByText("File not found", { exact: true })).toBeVisible();
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
import { expect, test, type Page } from "../support/fixtures";
|
||||
import {
|
||||
attachFileFromMenu,
|
||||
composerLocator,
|
||||
expectComposerVisible,
|
||||
} from "../support/helpers/composer";
|
||||
import { composerLocator, expectComposerVisible } from "../support/helpers/composer";
|
||||
import {
|
||||
openAgentRoute,
|
||||
seedMockAgentWorkspace,
|
||||
@@ -369,56 +365,6 @@ function expectPopoverDoesNotDisappearAfterFirstVisible(frames: PopoverFrame[]):
|
||||
}
|
||||
|
||||
test.describe("Composer autocomplete", () => {
|
||||
test("inserts suggested commands from assistant messages without sending", async ({ page }) => {
|
||||
const requests = recordCommandRequestsByAgentId(page);
|
||||
const session = await seedMockAgentWorkspace({
|
||||
repoPrefix: "suggested-command-",
|
||||
title: "Suggested commands",
|
||||
initialPrompt: "Suggest `/mock` without running it",
|
||||
featureValues: { mockAssistantResponse: "Try `/mock` or [Run mock](/mock)." },
|
||||
});
|
||||
try {
|
||||
await openAgentRoute(page, session);
|
||||
const message = page.getByTestId("assistant-message").filter({ hasText: "Run mock" });
|
||||
await expect(message).toBeVisible();
|
||||
await expect(page.getByTestId("user-message").getByRole("link")).toHaveCount(0);
|
||||
await expect.poll(() => requests.length).toBe(1);
|
||||
await attachFileFromMenu(page, {
|
||||
name: "note.txt",
|
||||
mimeType: "text/plain",
|
||||
buffer: Buffer.from("attachment"),
|
||||
});
|
||||
await expect(page.getByTestId("composer-file-attachment-pill")).toContainText("note.txt");
|
||||
await message.getByRole("link", { name: "/mock", exact: true }).click();
|
||||
await expect(composerLocator(page)).toHaveValue("/mock ");
|
||||
await expect(
|
||||
page.getByTestId("composer-autocomplete-popover").filter({ visible: true }),
|
||||
).toHaveCount(0);
|
||||
await expect(composerLocator(page)).toBeFocused();
|
||||
await message.getByRole("link", { name: "Run mock" }).click();
|
||||
await expect(composerLocator(page)).toHaveValue("/mock /mock ");
|
||||
await expect(
|
||||
page.getByTestId("composer-autocomplete-popover").filter({ visible: true }),
|
||||
).toHaveCount(0);
|
||||
await expect(composerLocator(page)).toBeFocused();
|
||||
await expect(page.getByTestId("composer-file-attachment-pill")).toContainText("note.txt");
|
||||
await composerLocator(page).fill("draft");
|
||||
await composerLocator(page).evaluate((element: HTMLTextAreaElement) =>
|
||||
element.setSelectionRange(0, 0),
|
||||
);
|
||||
await message.getByRole("link", { name: "/mock", exact: true }).click();
|
||||
await composerLocator(page).pressSequentially("argument");
|
||||
await expect(composerLocator(page)).toHaveValue("draft /mock argument");
|
||||
await composerLocator(page).fill("/");
|
||||
await expect(
|
||||
page.getByTestId("composer-autocomplete-popover").filter({ visible: true }),
|
||||
).toContainText("/mock");
|
||||
expect(requests).toHaveLength(1);
|
||||
} finally {
|
||||
await session.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps New workspace off the running-agent command list before a project is chosen", async ({
|
||||
page,
|
||||
}) => {
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import { expect, test } from "../support/fixtures";
|
||||
import { composerLocator, expectComposerVisible } from "../support/helpers/composer";
|
||||
import {
|
||||
discardDictation,
|
||||
expectEmptyDictation,
|
||||
installSyntheticMicrophone,
|
||||
observeDictation,
|
||||
recordDictation,
|
||||
retryDictation,
|
||||
} from "../support/helpers/dictation";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
|
||||
// Silence is finalized by the real daemon without calling a transcription service.
|
||||
// A closed local endpoint makes an unexpected transcription request fail the test.
|
||||
test.use({
|
||||
e2eDaemonEnvironment: {
|
||||
PASEO_DICTATION_ENABLED: "1",
|
||||
PASEO_DICTATION_SILENCE_PEAK_THRESHOLD: "300",
|
||||
OPENAI_API_KEY: "unused-for-silent-recordings",
|
||||
OPENAI_BASE_URL: "http://127.0.0.1:9/v1",
|
||||
},
|
||||
});
|
||||
|
||||
test.describe("Dictation empty result", () => {
|
||||
test("the daemon accepts the same recording through repeated empty-result retries", async ({
|
||||
page,
|
||||
}) => {
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "dictation-empty-",
|
||||
title: "Empty dictation",
|
||||
});
|
||||
await installSyntheticMicrophone(page, { silent: true });
|
||||
const observed = observeDictation(page);
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
await recordDictation(page, observed);
|
||||
await expectEmptyDictation(page);
|
||||
await retryDictation(page);
|
||||
await expectEmptyDictation(page);
|
||||
await retryDictation(page);
|
||||
await expectEmptyDictation(page);
|
||||
|
||||
expect(observed.recordings).toHaveLength(3);
|
||||
expect(observed.recordings[0].audio.length).toBeGreaterThan(0);
|
||||
expect(observed.recordings[0].finalSeq).toBe(observed.recordings[0].audio.length - 1);
|
||||
expect(observed.recordings[0].text).toBe("");
|
||||
expect(observed.recordings[1]).toEqual(observed.recordings[0]);
|
||||
expect(observed.recordings[2]).toEqual(observed.recordings[0]);
|
||||
await discardDictation(page);
|
||||
await expect(composerLocator(page)).toBeEditable();
|
||||
await expect(composerLocator(page)).toHaveValue("");
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test.describe("narrow composer", () => {
|
||||
test.use({ viewport: { width: 390, height: 844 } });
|
||||
test("explains and discards an empty result", async ({ page }) => {
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "dictation-silent-",
|
||||
title: "Silent dictation",
|
||||
});
|
||||
await installSyntheticMicrophone(page, { silent: true });
|
||||
const observed = observeDictation(page);
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
await recordDictation(page, observed);
|
||||
await expectEmptyDictation(page);
|
||||
await discardDictation(page);
|
||||
await expect(composerLocator(page)).toBeEditable();
|
||||
await expect(composerLocator(page)).toHaveValue("");
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -81,8 +81,6 @@ for (const folder of [
|
||||
"docs/guides",
|
||||
"docs/guides/",
|
||||
"docs/指南",
|
||||
"examples/next.js/",
|
||||
"examples/next.js",
|
||||
]) {
|
||||
test(`chat folder link opens folder contents: ${folder}`, async ({ page }) => {
|
||||
const session = await seedMockAgentWorkspace({
|
||||
@@ -94,9 +92,6 @@ for (const folder of [
|
||||
try {
|
||||
await mkdir(path.join(session.cwd, folder), { recursive: true });
|
||||
await writeFile(path.join(session.cwd, folder, "guide.md"), "# Folder link destination\n");
|
||||
const competingFile = path.join(session.cwd, "repo-a", folder.replace(/\/$/, ""));
|
||||
await mkdir(path.dirname(competingFile), { recursive: true });
|
||||
await writeFile(competingFile, "This is a file, not the requested folder.\n");
|
||||
await session.client.waitForFinish(session.agentId, 30_000);
|
||||
await page.addInitScript(() => {
|
||||
localStorage.setItem(
|
||||
|
||||
@@ -38,9 +38,6 @@ import {
|
||||
fillDirectHostUri,
|
||||
expectDirectHostFormValues,
|
||||
expectDirectHostSslEnabled,
|
||||
expectDirectHostSslDisabled,
|
||||
fillDirectHostAddress,
|
||||
toggleDirectHostSsl,
|
||||
expectDirectHostUriValue,
|
||||
expectDirectHostUriHidden,
|
||||
expectDiagnosticsContent,
|
||||
@@ -287,16 +284,6 @@ test.describe("Settings sidebar navigation", () => {
|
||||
await expectAddHostMethodOptions(page);
|
||||
await selectHostConnectionType(page, "direct");
|
||||
|
||||
await fillDirectHostAddress(page, "example.paseo.test", "7443");
|
||||
await expectDirectHostSslDisabled(page);
|
||||
await toggleDirectHostSsl(page);
|
||||
await expectDirectHostSslEnabled(page);
|
||||
await toggleHostAdvanced(page);
|
||||
await expectDirectHostUriValue(page, "tcp://example.paseo.test:7443?ssl=true");
|
||||
await toggleHostAdvanced(page);
|
||||
await toggleDirectHostSsl(page);
|
||||
await expectDirectHostSslDisabled(page);
|
||||
|
||||
await toggleHostAdvanced(page);
|
||||
await fillDirectHostUri(page, "tcp://example.paseo.test:7443?ssl=true&password=shared-secret");
|
||||
await toggleHostAdvanced(page);
|
||||
|
||||
@@ -426,81 +426,3 @@ test("Manual restores pre-beta order and keeps drag order across sorting and rel
|
||||
await seed.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
function workspaceRows(page: Page, ids: string[]) {
|
||||
return page.locator(
|
||||
ids.map((id) => `[data-testid="sidebar-workspace-row-${getServerId()}:${id}"]`).join(", "),
|
||||
);
|
||||
}
|
||||
|
||||
async function openWorkspaceRow(page: Page, workspaceId: string) {
|
||||
await page.getByTestId(`sidebar-workspace-row-${getServerId()}:${workspaceId}`).click();
|
||||
await expect(page).toHaveURL(new RegExp(`/workspace/${workspaceId}`));
|
||||
}
|
||||
|
||||
test("collapsed groups lead with the open workspace instead of hiding it behind Show more", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(120_000);
|
||||
const { seed, ids } = await seedCompactProject();
|
||||
try {
|
||||
await gotoAppShell(page);
|
||||
await waitForSidebarHydration(page);
|
||||
await selectWorkspaceSort(page, "Created");
|
||||
const { rows, group } = compactProjectRows(page, seed);
|
||||
await expectWorkspaceOrder(rows, ids.slice(0, 7));
|
||||
await revealWorkspaces(group, "Show more");
|
||||
await openWorkspaceRow(page, ids[9]!);
|
||||
await expectWorkspaceOrder(rows, ids);
|
||||
await revealWorkspaces(group, "Show less");
|
||||
await expectWorkspaceOrder(rows, [ids[9]!, ...ids.slice(0, 7)]);
|
||||
await expect(
|
||||
page.getByTestId(`sidebar-workspace-row-${getServerId()}:${ids[9]!}`),
|
||||
).toHaveAttribute("aria-selected", "true");
|
||||
await reconnectSidebar(page);
|
||||
await expectWorkspaceOrder(rows, [ids[9]!, ...ids.slice(0, 7)]);
|
||||
await expect(
|
||||
page.getByTestId(`sidebar-workspace-row-${getServerId()}:${ids[9]!}`),
|
||||
).toHaveAttribute("aria-selected", "true");
|
||||
await openWorkspaceRow(page, ids[2]!);
|
||||
await expectWorkspaceOrder(rows, ids.slice(0, 7));
|
||||
await expect(
|
||||
page.getByTestId(`sidebar-workspace-row-${getServerId()}:${ids[2]!}`),
|
||||
).toHaveAttribute("aria-selected", "true");
|
||||
} finally {
|
||||
await seed.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("a Manual drag in a collapsed group keeps the open workspace's saved place", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(120_000);
|
||||
const { seed, ids } = await seedCompactProject();
|
||||
try {
|
||||
await gotoAppShell(page);
|
||||
await waitForSidebarHydration(page);
|
||||
const projectKey = projectEquivalenceViewKey(seed.projectKey);
|
||||
await restorePreBetaOrder(
|
||||
page,
|
||||
projectKey,
|
||||
ids.map((id) => `${getServerId()}:${id}`),
|
||||
);
|
||||
await selectWorkspaceSort(page, "Manual");
|
||||
const rows = workspaceRows(page, ids);
|
||||
const toggle = page.getByTestId(`sidebar-project-show-more-${projectKey}`);
|
||||
await expectWorkspaceOrder(rows, ids.slice(0, 7));
|
||||
await toggle.click();
|
||||
await openWorkspaceRow(page, ids[9]!);
|
||||
await toggle.click();
|
||||
await expectWorkspaceOrder(rows, [ids[9]!, ...ids.slice(0, 7)]);
|
||||
await quickDragFirstRowAfterSecond(workspaceRows(page, [ids[0]!, ids[1]!]), pressWorkspaceRow);
|
||||
await expectWorkspaceOrder(rows, [ids[9]!, ids[1]!, ids[0]!, ...ids.slice(2, 7)]);
|
||||
await reconnectSidebar(page);
|
||||
await expectWorkspaceOrder(rows, [ids[9]!, ids[1]!, ids[0]!, ...ids.slice(2, 7)]);
|
||||
await toggle.click();
|
||||
await expectWorkspaceOrder(rows, [ids[1]!, ids[0]!, ...ids.slice(2)]);
|
||||
} finally {
|
||||
await seed.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -70,31 +70,25 @@ test("previous and next traverse every visible workspace while digit shortcuts s
|
||||
workspaceId: order[8],
|
||||
});
|
||||
});
|
||||
await test.step("collapsed groups keep shortcut targets selected without expanding", async () => {
|
||||
await expectCollapsedWorkspaceShortcuts(page, order);
|
||||
await test.step("hidden Done rows remain shortcut targets without expanding the project", async () => {
|
||||
await expectHiddenWorkspaceShortcuts(page, order);
|
||||
});
|
||||
} finally {
|
||||
await project.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
async function expectCollapsedWorkspaceShortcuts(page: Page, order: string[]) {
|
||||
async function expectHiddenWorkspaceShortcuts(page: Page, order: string[]) {
|
||||
await page.getByLabel("Show less", { exact: true }).click();
|
||||
const rows = page.getByRole("button", { name: /^Workspace \d{2}$/ });
|
||||
await expect(rows).toHaveCount(8);
|
||||
await expectSidebarWorkspaceSelected({ page, serverId: getServerId(), workspaceId: order[8] });
|
||||
await switchWorkspaceViaSidebar({ page, serverId: getServerId(), workspaceId: order[0] });
|
||||
await expect(rows).toHaveCount(7);
|
||||
await switchWorkspaceViaSidebar({ page, serverId: getServerId(), workspaceId: order[0] });
|
||||
await page.keyboard.press("Alt+9");
|
||||
await expect(page).toHaveURL(new RegExp(`/workspace/${order[8]}$`));
|
||||
await expectSidebarWorkspaceSelected({ page, serverId: getServerId(), workspaceId: order[8] });
|
||||
await expect(rows).toHaveCount(8);
|
||||
await page.keyboard.press("Alt+]");
|
||||
await expect(page).toHaveURL(new RegExp(`/workspace/${order[9]}$`));
|
||||
await expectSidebarWorkspaceSelected({ page, serverId: getServerId(), workspaceId: order[9] });
|
||||
await expect(rows).toHaveCount(8);
|
||||
await expect(page.getByTestId(`sidebar-workspace-row-${getServerId()}:${order[8]}`)).toHaveCount(
|
||||
0,
|
||||
);
|
||||
await expect(page.getByLabel("Show more", { exact: true })).toBeVisible();
|
||||
await page.keyboard.press("Alt+]");
|
||||
await expect(page).toHaveURL(new RegExp(`/workspace/${order[9]}$`));
|
||||
await expect(rows).toHaveCount(7);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
import { expect, type Page } from "../fixtures";
|
||||
|
||||
/**
|
||||
* Replaces the browser microphone with an oscillator. `silent` keeps the stream
|
||||
* running at zero gain, which is what a muted or wrongly routed input delivers.
|
||||
*/
|
||||
export async function installSyntheticMicrophone(
|
||||
page: Page,
|
||||
options: { silent?: boolean } = {},
|
||||
): Promise<void> {
|
||||
await page.addInitScript((silent: boolean) => {
|
||||
const mediaDevices = navigator.mediaDevices;
|
||||
Object.defineProperty(mediaDevices, "getUserMedia", {
|
||||
configurable: true,
|
||||
value: async () => {
|
||||
const context = new AudioContext();
|
||||
const oscillator = context.createOscillator();
|
||||
const gain = context.createGain();
|
||||
gain.gain.value = silent ? 0 : 1;
|
||||
const destination = context.createMediaStreamDestination();
|
||||
oscillator.connect(gain);
|
||||
gain.connect(destination);
|
||||
oscillator.start();
|
||||
return destination.stream;
|
||||
},
|
||||
});
|
||||
}, options.silent ?? false);
|
||||
}
|
||||
|
||||
/** Observe real browser/daemon traffic without intercepting or answering it. */
|
||||
export function observeDictation(page: Page) {
|
||||
const streams = new Map<string, { audio: Map<number, string>; finalSeq: number }>();
|
||||
const recordings: Array<{ audio: string[]; finalSeq: number; text: string }> = [];
|
||||
let resolveAudio!: () => void;
|
||||
const audio = new Promise<void>((resolve) => {
|
||||
resolveAudio = resolve;
|
||||
});
|
||||
|
||||
page.on("websocket", (socket) => {
|
||||
socket.on("framesent", ({ payload }) => {
|
||||
const request = sessionMessage(payload);
|
||||
if (!request || typeof request.dictationId !== "string") return;
|
||||
const id = request.dictationId;
|
||||
if (request.type === "dictation_stream_start") {
|
||||
streams.set(id, { audio: new Map(), finalSeq: -1 });
|
||||
}
|
||||
if (request.type === "dictation_stream_chunk") {
|
||||
streams.get(id)!.audio.set(request.seq as number, request.audio as string);
|
||||
resolveAudio();
|
||||
}
|
||||
if (request.type === "dictation_stream_finish") {
|
||||
streams.get(id)!.finalSeq = request.finalSeq as number;
|
||||
}
|
||||
});
|
||||
socket.on("framereceived", ({ payload }) => {
|
||||
const response = sessionMessage(payload);
|
||||
if (response?.type !== "dictation_stream_final") return;
|
||||
const final = response.payload as { dictationId: string; text: string };
|
||||
const stream = streams.get(final.dictationId)!;
|
||||
recordings.push({
|
||||
audio: [...stream.audio.entries()].sort(([a], [b]) => a - b).map(([, chunk]) => chunk),
|
||||
finalSeq: stream.finalSeq,
|
||||
text: final.text,
|
||||
});
|
||||
});
|
||||
});
|
||||
return { waitForAudio: () => audio, recordings };
|
||||
}
|
||||
|
||||
function sessionMessage(payload: string | Buffer): Record<string, unknown> | null {
|
||||
try {
|
||||
const envelope = JSON.parse(typeof payload === "string" ? payload : payload.toString("utf8"));
|
||||
return envelope.type === "session" ? envelope.message : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function recordDictation(page: Page, observed: { waitForAudio(): Promise<void> }) {
|
||||
await page.getByRole("button", { name: "Start dictation", exact: true }).click();
|
||||
await observed.waitForAudio();
|
||||
await page.getByRole("button", { name: "Insert transcription", exact: true }).click();
|
||||
}
|
||||
|
||||
export async function expectEmptyDictation(page: Page) {
|
||||
const message = page.getByText("No transcription was returned. Tap retry to try again.", {
|
||||
exact: true,
|
||||
});
|
||||
await expect(message).toBeVisible();
|
||||
const bounds = await message.boundingBox();
|
||||
const cancel = await page
|
||||
.getByRole("button", { name: "Cancel dictation", exact: true })
|
||||
.boundingBox();
|
||||
expect(bounds).not.toBeNull();
|
||||
expect(cancel).not.toBeNull();
|
||||
expect(bounds!.y).toBeGreaterThanOrEqual(cancel!.y);
|
||||
expect(bounds!.y + bounds!.height).toBeLessThanOrEqual(cancel!.y + cancel!.height);
|
||||
}
|
||||
|
||||
export async function retryDictation(page: Page) {
|
||||
await page.getByRole("button", { name: "Retry dictation", exact: true }).click();
|
||||
}
|
||||
|
||||
export async function discardDictation(page: Page) {
|
||||
await page.getByRole("button", { name: "Cancel dictation", exact: true }).click();
|
||||
}
|
||||
@@ -182,8 +182,8 @@ export async function startIsolatedHostDaemon(
|
||||
const spawnDaemon = async (): Promise<ChildProcess> => {
|
||||
const spawnOptions: SpawnOptions = {
|
||||
cwd: serverDir,
|
||||
env: withDisabledE2ESpeechEnv({
|
||||
...process.env,
|
||||
env: {
|
||||
...withDisabledE2ESpeechEnv(process.env),
|
||||
...options.environment,
|
||||
PASEO_HOME: paseoHome,
|
||||
PASEO_SERVER_ID: serverId,
|
||||
@@ -192,7 +192,7 @@ export async function startIsolatedHostDaemon(
|
||||
PASEO_RELAY_ENABLED: options.mutableRelay ? undefined : "0",
|
||||
PASEO_NODE_ENV: "development",
|
||||
NODE_ENV: "development",
|
||||
}),
|
||||
},
|
||||
stdio: ["ignore", "ignore", "pipe"],
|
||||
detached: false,
|
||||
};
|
||||
|
||||
@@ -351,24 +351,9 @@ export async function expectDirectHostFormValues(
|
||||
}
|
||||
|
||||
export async function expectDirectHostSslEnabled(page: Page): Promise<void> {
|
||||
await expect(page.getByRole("checkbox", { name: "Use SSL", exact: true })).toBeChecked();
|
||||
await expect(page.getByTestId("direct-ssl-toggle-checked")).toBeVisible();
|
||||
}
|
||||
|
||||
export async function fillDirectHostAddress(page: Page, host: string, port: string): Promise<void> {
|
||||
await page.getByRole("textbox", { name: "Host", exact: true }).fill(host);
|
||||
await page.getByRole("textbox", { name: "Port", exact: true }).fill(port);
|
||||
}
|
||||
|
||||
export async function toggleDirectHostSsl(page: Page): Promise<void> {
|
||||
await page.getByRole("checkbox", { name: "Use SSL", exact: true }).click();
|
||||
}
|
||||
|
||||
export async function expectDirectHostSslDisabled(page: Page): Promise<void> {
|
||||
await expect(page.getByRole("checkbox", { name: "Use SSL", exact: true })).not.toBeChecked();
|
||||
await expect(page.getByTestId("direct-ssl-toggle-checked")).toHaveCount(0);
|
||||
}
|
||||
|
||||
export async function expectDirectHostUriValue(page: Page, uri: string): Promise<void> {
|
||||
await expect(page.getByTestId("direct-host-uri-input")).toHaveValue(uri);
|
||||
}
|
||||
|
||||
-35
@@ -10,7 +10,6 @@ import androidx.test.platform.app.InstrumentationRegistry
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
|
||||
@@ -56,40 +55,6 @@ class TerminalRowLayoutTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun selectionCompositesOverCellAndTerminalBackgroundsWithoutChangingForeground() {
|
||||
val red = 0xffff0000.toInt()
|
||||
val green = 0xff00aa00.toInt()
|
||||
val overlay = 0x472684ff
|
||||
val source = TerminalRowSource.decode("1,1;1,4294901760,4278233600,0;M")
|
||||
val layout = TerminalRowLayout(source, font, TerminalCustomGlyphs.EMPTY)
|
||||
paints.selectionBackground = overlay
|
||||
for (terminalBackground in listOf(0xffffffff.toInt(), 0xff000000.toInt())) {
|
||||
val actual = raster { canvas ->
|
||||
canvas.drawColor(terminalBackground)
|
||||
layout.drawSelected(canvas, 0, TerminalSelection(TerminalSelectionRecord()), paints)
|
||||
}
|
||||
val expected = raster { canvas ->
|
||||
canvas.drawColor(terminalBackground)
|
||||
canvas.drawColor(green)
|
||||
canvas.drawColor(overlay)
|
||||
}
|
||||
assertEquals(expected.getPixel(0, 0), actual.getPixel(0, 0))
|
||||
assertTrue("selected glyph retains its red foreground", (0 until font.cellHeightPx).any { y ->
|
||||
(0 until font.cellWidthPx).any { x -> actual.getPixel(x, y) == red }
|
||||
})
|
||||
}
|
||||
val defaultBackground = TerminalRowLayout(TerminalRowSource.decode("1,1;1,4294901760,0,0;M"), font, TerminalCustomGlyphs.EMPTY)
|
||||
for (terminalBackground in listOf(0xffffffff.toInt(), 0xff000000.toInt())) {
|
||||
val actual = raster { canvas ->
|
||||
canvas.drawColor(terminalBackground)
|
||||
defaultBackground.drawSelected(canvas, 0, TerminalSelection(TerminalSelectionRecord()), paints)
|
||||
}
|
||||
val expected = raster { canvas -> canvas.drawColor(terminalBackground); canvas.drawColor(overlay) }
|
||||
assertEquals(expected.getPixel(0, 0), actual.getPixel(0, 0))
|
||||
}
|
||||
}
|
||||
|
||||
private fun starts(row: JSONObject, key: String): List<Int> =
|
||||
row.getJSONArray(key).let { starts -> List(starts.length()) { starts.getInt(it) } }
|
||||
|
||||
|
||||
+1
@@ -63,6 +63,7 @@ class PaseoTerminalView(context: Context, appContext: AppContext) : ExpoView(con
|
||||
backgroundColor = argb(value.background)
|
||||
cursorColor = argb(value.cursor)
|
||||
paints.selectionBackground = argb(value.selectionBackground)
|
||||
paints.selectionForeground = argb(value.selectionForeground)
|
||||
invalidate()
|
||||
}
|
||||
|
||||
|
||||
+1
@@ -27,6 +27,7 @@ class TerminalThemeRecord : Record {
|
||||
@Field val background: Double = 0.0
|
||||
@Field val cursor: Double = 0.0
|
||||
@Field val selectionBackground: Double = 0.0
|
||||
@Field val selectionForeground: Double = 0.0
|
||||
}
|
||||
|
||||
class TerminalCustomGlyphRecord : Record {
|
||||
|
||||
+21
-17
@@ -23,7 +23,7 @@ private const val CLIP_UNBOUNDED_PX = 100_000f
|
||||
* either half alone would show an explicit virama. Each resulting group is drawn from the shaped
|
||||
* run (in context) at its first cell's column, centred in the columns it owns, and scaled down only when
|
||||
* its glyphs are wider than those columns. Colors never split groups or reshape the row: a group
|
||||
* whose cells differ in color is drawn once per color, clipped to those cells' columns.
|
||||
* whose cells differ in color or selection is drawn once per color, clipped to those cells' columns.
|
||||
*/
|
||||
internal class TerminalRowLayout(
|
||||
val source: TerminalRowSource,
|
||||
@@ -195,7 +195,7 @@ internal class TerminalRowLayout(
|
||||
canvas.drawRenderNode(recorded)
|
||||
}
|
||||
|
||||
/** Draws backgrounds, the selection overlay, then text with its original colors. */
|
||||
/** Draws the row with selected cells in selection colors. Selection never reshapes the row. */
|
||||
fun drawSelected(canvas: Canvas, row: Int, selection: TerminalSelection, paints: TerminalPaints) {
|
||||
drawContent(canvas, row, selection, paints)
|
||||
}
|
||||
@@ -213,17 +213,17 @@ internal class TerminalRowLayout(
|
||||
val cellHeight = font.cellHeightPx.toFloat()
|
||||
val fill = paints.fill
|
||||
for (cell in 0 until cellCount) {
|
||||
val left = cellCol[cell] * cellWidth
|
||||
val right = (cellCol[cell] + cellSpan[cell]) * cellWidth
|
||||
val background = cellBackground[cell]
|
||||
if (background ushr 24 != 0) {
|
||||
fill.color = background
|
||||
canvas.drawRect(left, 0f, right, cellHeight, fill)
|
||||
}
|
||||
if (selected(row, selection, cell)) {
|
||||
fill.color = paints.selectionBackground
|
||||
canvas.drawRect(left, 0f, right, cellHeight, fill)
|
||||
}
|
||||
val background =
|
||||
if (selected(row, selection, cell)) paints.selectionBackground else cellBackground[cell]
|
||||
if (background ushr 24 == 0) continue
|
||||
fill.color = background
|
||||
canvas.drawRect(
|
||||
cellCol[cell] * cellWidth,
|
||||
0f,
|
||||
(cellCol[cell] + cellSpan[cell]) * cellWidth,
|
||||
cellHeight,
|
||||
fill,
|
||||
)
|
||||
}
|
||||
|
||||
val baseline = font.baselinePx.toFloat()
|
||||
@@ -234,9 +234,9 @@ internal class TerminalRowLayout(
|
||||
val paint = font.paint(cellFlags[group.firstCell])
|
||||
var first = group.firstCell
|
||||
while (first <= group.lastCell) {
|
||||
val color = cellForeground[first]
|
||||
val color = foreground(row, selection, first, paints)
|
||||
var last = first
|
||||
while (last < group.lastCell && cellForeground[last + 1] == color) last += 1
|
||||
while (last < group.lastCell && foreground(row, selection, last + 1, paints) == color) last += 1
|
||||
// Only edges between differently colored cells clip; the group's outer edges may overhang.
|
||||
val clipped = first > group.firstCell || last < group.lastCell
|
||||
canvas.save()
|
||||
@@ -257,7 +257,7 @@ internal class TerminalRowLayout(
|
||||
for (cell in 0 until cellCount) {
|
||||
val glyph = cellGlyph[cell]
|
||||
val flags = cellFlags[cell]
|
||||
val foreground = cellForeground[cell]
|
||||
val foreground = foreground(row, selection, cell, paints)
|
||||
if (glyph != null) {
|
||||
fill.color = foreground
|
||||
glyph.draw(canvas, cellCol[cell] * cellWidth, cellSpan[cell] * cellWidth, cellHeight, font.density, fill)
|
||||
@@ -291,6 +291,9 @@ internal class TerminalRowLayout(
|
||||
canvas.drawTextRun(text, group.start, group.end, group.contextStart, group.contextEnd, x, baseline, false, paint)
|
||||
}
|
||||
|
||||
private fun foreground(row: Int, selection: TerminalSelection?, cell: Int, paints: TerminalPaints): Int =
|
||||
if (selected(row, selection, cell)) paints.selectionForeground else cellForeground[cell]
|
||||
|
||||
/** The row's text as accessibility reads it. */
|
||||
fun describe(): String = source.text.trimEnd()
|
||||
}
|
||||
@@ -298,5 +301,6 @@ internal class TerminalRowLayout(
|
||||
/** Paint state shared by every row of one view. */
|
||||
internal class TerminalPaints {
|
||||
val fill = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||
var selectionBackground: Int = 0x472684FF
|
||||
var selectionBackground: Int = 0xFFFFFF00.toInt()
|
||||
var selectionForeground: Int = 0xFF000000.toInt()
|
||||
}
|
||||
|
||||
@@ -43,6 +43,7 @@ export interface PaseoTerminalTheme {
|
||||
background: number;
|
||||
cursor: number;
|
||||
selectionBackground: number;
|
||||
selectionForeground: number;
|
||||
}
|
||||
|
||||
export interface PaseoTerminalCellMetrics {
|
||||
|
||||
@@ -24,7 +24,8 @@ final class PaseoTerminalView: ExpoView {
|
||||
private var background = TerminalColor(Double(0xff00_0000))
|
||||
private var cursorColor = TerminalColor(Double(0xffff_ffff))
|
||||
private var rowPaint = TerminalRowPaint(
|
||||
selectionBackground: TerminalColor(Double(0x4726_84ff)))
|
||||
selectionBackground: TerminalColor(Double(0xffff_ff00)),
|
||||
selectionForeground: TerminalColor(Double(0xff00_0000)))
|
||||
private var rowCache: [String: TerminalRowLayout] = [:]
|
||||
|
||||
required init(appContext: AppContext? = nil) {
|
||||
@@ -43,7 +44,8 @@ final class PaseoTerminalView: ExpoView {
|
||||
background = TerminalColor(record.background)
|
||||
cursorColor = TerminalColor(record.cursor)
|
||||
rowPaint = TerminalRowPaint(
|
||||
selectionBackground: TerminalColor(record.selectionBackground))
|
||||
selectionBackground: TerminalColor(record.selectionBackground),
|
||||
selectionForeground: TerminalColor(record.selectionForeground))
|
||||
backgroundColor = UIColor(cgColor: background.cgColor())
|
||||
setNeedsDisplay()
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ struct TerminalThemeRecord: Record {
|
||||
@Field var background: Double = 0
|
||||
@Field var cursor: Double = 0
|
||||
@Field var selectionBackground: Double = 0
|
||||
@Field var selectionForeground: Double = 0
|
||||
}
|
||||
|
||||
struct TerminalCustomGlyphRecord: Record {
|
||||
|
||||
@@ -27,6 +27,7 @@ private let leftToRightAttributes: [NSAttributedString.Key: Any] = {
|
||||
/// Colors a row is painted with besides its own styles.
|
||||
struct TerminalRowPaint {
|
||||
let selectionBackground: TerminalColor
|
||||
let selectionForeground: TerminalColor
|
||||
}
|
||||
|
||||
/// One row shaped once and placed on the terminal grid.
|
||||
@@ -266,33 +267,31 @@ final class TerminalRowLayout {
|
||||
selection?.contains(row: row, col: cellCol[cell], span: cellSpan[cell]) ?? false
|
||||
}
|
||||
|
||||
/// Draws cell backgrounds, the selection overlay, then text with its original colors.
|
||||
private func foreground(_ cell: Int, row: Int, selection: TerminalSelection?, paint: TerminalRowPaint) -> TerminalColor {
|
||||
isSelected(cell, row: row, selection: selection) ? paint.selectionForeground : cellForeground[cell]
|
||||
}
|
||||
|
||||
/// Draws the row with its top edge at `top`, selected cells in selection colors.
|
||||
func draw(in context: CGContext, row: Int, top: CGFloat, selection: TerminalSelection?, paint: TerminalRowPaint) {
|
||||
let cellWidth = font.cellWidth
|
||||
let cellHeight = font.cellHeight
|
||||
for cell in 0..<cellCount {
|
||||
let rect = CGRect(x: CGFloat(cellCol[cell]) * cellWidth, y: top, width: CGFloat(cellSpan[cell]) * cellWidth, height: cellHeight)
|
||||
let background = cellBackground[cell]
|
||||
if background.isPainted {
|
||||
context.setFillColor(background.cgColor())
|
||||
context.fill(rect)
|
||||
}
|
||||
if isSelected(cell, row: row, selection: selection) {
|
||||
context.setFillColor(paint.selectionBackground.cgColor())
|
||||
context.fill(rect)
|
||||
}
|
||||
let background = isSelected(cell, row: row, selection: selection) ? paint.selectionBackground : cellBackground[cell]
|
||||
guard background.isPainted else { continue }
|
||||
context.setFillColor(background.cgColor())
|
||||
context.fill(CGRect(x: CGFloat(cellCol[cell]) * cellWidth, y: top, width: CGFloat(cellSpan[cell]) * cellWidth, height: cellHeight))
|
||||
}
|
||||
|
||||
let centerY = top + cellHeight / 2
|
||||
let baselineInTextSpace = cellHeight / 2 - font.baseline
|
||||
// A group whose cells differ in color is drawn once per color, clipped to those
|
||||
// A group whose cells differ in color or selection is drawn once per color, clipped to those
|
||||
// cells' columns. Only edges between differently colored cells clip; outer edges may overhang.
|
||||
for group in groups {
|
||||
var first = group.firstCell
|
||||
while first <= group.lastCell {
|
||||
let color = cellForeground[first]
|
||||
let color = foreground(first, row: row, selection: selection, paint: paint)
|
||||
var last = first
|
||||
while last < group.lastCell && cellForeground[last + 1] == color {
|
||||
while last < group.lastCell && foreground(last + 1, row: row, selection: selection, paint: paint) == color {
|
||||
last += 1
|
||||
}
|
||||
context.saveGState()
|
||||
@@ -316,7 +315,7 @@ final class TerminalRowLayout {
|
||||
|
||||
let baseline = top + font.baseline
|
||||
for cell in 0..<cellCount {
|
||||
let color = cellForeground[cell]
|
||||
let color = foreground(cell, row: row, selection: selection, paint: paint)
|
||||
let left = CGFloat(cellCol[cell]) * cellWidth
|
||||
let width = CGFloat(cellSpan[cell]) * cellWidth
|
||||
if let glyph = cellGlyph[cell] {
|
||||
|
||||
@@ -1,99 +0,0 @@
|
||||
import { createContext, useCallback, useContext, useMemo, type ReactNode } from "react";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import type { ComposerEditingSession } from "@/composer/editing-session";
|
||||
import { agentCommandsQueryKey } from "./cache";
|
||||
import {
|
||||
useAgentCommandsQuery,
|
||||
type AgentSlashCommand,
|
||||
type DraftCommandConfig,
|
||||
} from "./use-query";
|
||||
|
||||
export type {
|
||||
AgentSlashCommand,
|
||||
DraftCommandConfig,
|
||||
DraftCommandTarget,
|
||||
AgentCommandsClient,
|
||||
} from "./use-query";
|
||||
export { fetchAgentCommands } from "./use-query";
|
||||
|
||||
type CommandQuery = ReturnType<typeof useAgentCommandsQuery>;
|
||||
const QueryContext = createContext<CommandQuery | null>(null);
|
||||
export interface CommandHints {
|
||||
names: ReadonlySet<string>;
|
||||
insert(command: string): void;
|
||||
}
|
||||
const HintsContext = createContext<CommandHints | null>(null);
|
||||
|
||||
function useLiveAgentCommands() {
|
||||
return useContext(QueryContext);
|
||||
}
|
||||
export function useAutocompleteCommands(input: {
|
||||
serverId: string;
|
||||
agentId: string;
|
||||
enabled: boolean;
|
||||
draftConfig?: DraftCommandConfig;
|
||||
}) {
|
||||
const live = useLiveAgentCommands();
|
||||
const fallback = useAgentCommandsQuery({
|
||||
serverId: input.serverId,
|
||||
agentId: input.agentId,
|
||||
enabled: !live && input.enabled,
|
||||
draftConfig: input.draftConfig,
|
||||
});
|
||||
return live ?? fallback;
|
||||
}
|
||||
export function useAgentCommandHints() {
|
||||
return useContext(HintsContext);
|
||||
}
|
||||
export function matchCommandLink(
|
||||
url: string,
|
||||
sourceType: "markdown" | "text" | "inline-code" | undefined,
|
||||
names: ReadonlySet<string>,
|
||||
): string | null {
|
||||
return (sourceType === "markdown" || sourceType === "inline-code") &&
|
||||
url.startsWith("/") &&
|
||||
names.has(url.slice(1))
|
||||
? url
|
||||
: null;
|
||||
}
|
||||
|
||||
export function AgentCommandsProvider({
|
||||
serverId,
|
||||
agentId,
|
||||
editingSession,
|
||||
enabled,
|
||||
children,
|
||||
}: {
|
||||
serverId: string;
|
||||
agentId: string;
|
||||
editingSession: ComposerEditingSession;
|
||||
enabled: boolean;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const query = useAgentCommandsQuery({ serverId, agentId, enabled });
|
||||
const queryClient = useQueryClient();
|
||||
const namesKey = JSON.stringify(
|
||||
[...new Set(query.commands.map((command) => command.name))].sort(),
|
||||
);
|
||||
const names = useMemo<ReadonlySet<string>>(
|
||||
() => new Set(JSON.parse(namesKey) as string[]),
|
||||
[namesKey],
|
||||
);
|
||||
const insert = useCallback(
|
||||
(token: string) => {
|
||||
const commands = queryClient.getQueryData<AgentSlashCommand[]>(
|
||||
agentCommandsQueryKey({ serverId, agentId }),
|
||||
);
|
||||
if (token.startsWith("/") && commands?.some((command) => `/${command.name}` === token)) {
|
||||
editingSession.insertCommand(token);
|
||||
}
|
||||
},
|
||||
[agentId, editingSession, queryClient, serverId],
|
||||
);
|
||||
const hints = useMemo(() => ({ names, insert }), [names, insert]);
|
||||
return (
|
||||
<QueryContext.Provider value={enabled ? query : null}>
|
||||
<HintsContext.Provider value={enabled ? hints : null}>{children}</HintsContext.Provider>
|
||||
</QueryContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -468,7 +468,6 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
() =>
|
||||
createInlinePathOpener({
|
||||
workspaceRoot,
|
||||
resolveRelativeFiles: true,
|
||||
client,
|
||||
openFile: openInlineFile,
|
||||
openDirectory: openInlineDirectory,
|
||||
|
||||
@@ -64,10 +64,7 @@ it("ignores an older probe after a newer file link opens", async () => {
|
||||
const opened: string[] = [];
|
||||
const opener = createInlinePathOpener({
|
||||
workspaceRoot: "/repo",
|
||||
client: {
|
||||
listDirectory: () => pendingProbe,
|
||||
getDirectorySuggestions: async () => ({ entries: [], error: null }),
|
||||
},
|
||||
client: { listDirectory: () => pendingProbe },
|
||||
openFile: (location) => {
|
||||
opened.push(location.path);
|
||||
},
|
||||
@@ -94,10 +91,7 @@ it("ignores a pending probe when its view is left", async () => {
|
||||
const opened: string[] = [];
|
||||
const opener = createInlinePathOpener({
|
||||
workspaceRoot: "/repo",
|
||||
client: {
|
||||
listDirectory: () => pendingProbe,
|
||||
getDirectorySuggestions: async () => ({ entries: [], error: null }),
|
||||
},
|
||||
client: { listDirectory: () => pendingProbe },
|
||||
openFile: (location) => {
|
||||
opened.push(location.path);
|
||||
},
|
||||
@@ -136,45 +130,3 @@ it("sends folders outside the workspace away from the workspace Files panel", as
|
||||
expect(outsideFolders).toEqual(["~/Downloads/contracts", "/tmp/reports"]);
|
||||
expect(workspaceFolders).toEqual(["docs"]);
|
||||
});
|
||||
|
||||
it("keeps a later selection when an earlier nested-file lookup finishes last", async () => {
|
||||
const { createInlinePathOpener } = await import("./path-open");
|
||||
const lookup = Promise.withResolvers<{
|
||||
entries: Array<{ path: string; kind: "file" }>;
|
||||
error: null;
|
||||
}>();
|
||||
const queries: string[] = [];
|
||||
const opened: string[] = [];
|
||||
const opener = createInlinePathOpener({
|
||||
workspaceRoot: "/repo",
|
||||
resolveRelativeFiles: true,
|
||||
client: {
|
||||
listDirectory: async () => {
|
||||
throw new Error("Not a directory");
|
||||
},
|
||||
getDirectorySuggestions: async ({ query }: { query: string }) => {
|
||||
queries.push(query);
|
||||
return lookup.promise;
|
||||
},
|
||||
},
|
||||
openFile: (location) => {
|
||||
opened.push(location.path);
|
||||
},
|
||||
openDirectory: (directory) => {
|
||||
opened.push(directory);
|
||||
},
|
||||
openOutsideDirectory: (directory) => {
|
||||
opened.push(directory);
|
||||
},
|
||||
});
|
||||
const earlier = opener.open(
|
||||
{ raw: "schema/x.md:2", path: "/repo/schema/x.md", lineStart: 2 },
|
||||
"side",
|
||||
);
|
||||
await Promise.resolve();
|
||||
expect(queries).toEqual(["schema/x.md"]);
|
||||
await opener.open({ raw: "./guide.md:2", path: "/repo/guide.md", lineStart: 2 }, "side");
|
||||
lookup.resolve({ entries: [{ path: "repo-a/schema/x.md", kind: "file" }], error: null });
|
||||
await earlier;
|
||||
expect(opened).toEqual(["guide.md"]);
|
||||
});
|
||||
|
||||
@@ -5,7 +5,6 @@ import {
|
||||
type OpenFileDisposition,
|
||||
} from "@/workspace/file-open";
|
||||
import { isAbsolutePath } from "@/utils/path";
|
||||
import { resolveMissingNestedRelativeFile, type GetDirectorySuggestions } from "./resolver";
|
||||
|
||||
interface PathOpenInput {
|
||||
file?: string;
|
||||
@@ -51,11 +50,7 @@ export async function resolveInlinePathOpen(input: PathOpenInput): Promise<PathO
|
||||
|
||||
export function createInlinePathOpener(input: {
|
||||
workspaceRoot: string;
|
||||
client: {
|
||||
listDirectory(root: string, path: string): Promise<unknown>;
|
||||
getDirectorySuggestions: GetDirectorySuggestions;
|
||||
} | null;
|
||||
resolveRelativeFiles?: boolean;
|
||||
client: PathOpenInput["client"];
|
||||
openFile: (location: WorkspaceFileLocation, disposition: OpenFileDisposition) => void;
|
||||
openDirectory: (path: string) => void;
|
||||
openOutsideDirectory: (path: string) => void;
|
||||
@@ -78,21 +73,10 @@ export function createInlinePathOpener(input: {
|
||||
} else if (destination.kind === "outsideDirectory") {
|
||||
input.openOutsideDirectory(destination.directoryPath);
|
||||
} else if (normalized.file) {
|
||||
const resolvedTarget =
|
||||
input.resolveRelativeFiles && input.client
|
||||
? await resolveMissingNestedRelativeFile({
|
||||
target,
|
||||
workspaceRoot: input.workspaceRoot,
|
||||
getDirectorySuggestions: input.client.getDirectorySuggestions.bind(input.client),
|
||||
})
|
||||
: target;
|
||||
if (ownGeneration !== generation) return;
|
||||
const resolved = normalizeInlinePathTarget(resolvedTarget.path, input.workspaceRoot);
|
||||
if (!resolved?.file) return;
|
||||
const location = normalizeWorkspaceFileLocation({
|
||||
path: resolved.file,
|
||||
lineStart: resolvedTarget.lineStart,
|
||||
lineEnd: resolvedTarget.lineEnd,
|
||||
path: normalized.file,
|
||||
lineStart: target.lineStart,
|
||||
lineEnd: target.lineEnd,
|
||||
});
|
||||
if (location) input.openFile(location, disposition);
|
||||
}
|
||||
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
classifyForResolution,
|
||||
fetchDaemonResolution,
|
||||
getAssistantFileLinkToken,
|
||||
resolveMissingNestedRelativeFile,
|
||||
UnresolvedFileLinkError,
|
||||
type AssistantFileLinkContext,
|
||||
type DirectorySuggestionEntry,
|
||||
@@ -425,174 +424,6 @@ describe("fetchDaemonResolution", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveMissingNestedRelativeFile", () => {
|
||||
const target = {
|
||||
raw: "schema/x.md:12-14",
|
||||
path: "/Users/test/project/schema/x.md",
|
||||
lineStart: 12,
|
||||
lineEnd: 14,
|
||||
};
|
||||
|
||||
it("opens a nested-repo suffix when the workspace-root path is missing", async () => {
|
||||
const { getDirectorySuggestions, searches } = suggestionsFromMap({
|
||||
"schema/x.md": [{ path: "repo-a/schema/x.md", kind: "file" }],
|
||||
});
|
||||
|
||||
const result = await resolveMissingNestedRelativeFile({
|
||||
target,
|
||||
workspaceRoot: "/Users/test/project",
|
||||
getDirectorySuggestions,
|
||||
});
|
||||
|
||||
expect(searches).toEqual([
|
||||
{
|
||||
query: "schema/x.md",
|
||||
cwd: "/Users/test/project",
|
||||
matchMode: "suffix",
|
||||
limit: 1,
|
||||
},
|
||||
]);
|
||||
expect(result).toEqual({
|
||||
...target,
|
||||
path: "/Users/test/project/repo-a/schema/x.md",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the exact workspace path when suggestions return that relative path", async () => {
|
||||
const { getDirectorySuggestions } = suggestionsFromMap({
|
||||
"schema/x.md": [{ path: "schema/x.md", kind: "file" }],
|
||||
});
|
||||
|
||||
const result = await resolveMissingNestedRelativeFile({
|
||||
target,
|
||||
workspaceRoot: "/Users/test/project",
|
||||
getDirectorySuggestions,
|
||||
});
|
||||
|
||||
expect(result).toEqual(target);
|
||||
});
|
||||
|
||||
it("keeps the original target when suggestions are empty", async () => {
|
||||
const { getDirectorySuggestions } = suggestionsFromMap({});
|
||||
|
||||
await expect(
|
||||
resolveMissingNestedRelativeFile({
|
||||
target,
|
||||
workspaceRoot: "/Users/test/project",
|
||||
getDirectorySuggestions,
|
||||
}),
|
||||
).resolves.toEqual(target);
|
||||
});
|
||||
|
||||
it("keeps the original target when the daemon throws", async () => {
|
||||
await expect(
|
||||
resolveMissingNestedRelativeFile({
|
||||
target,
|
||||
workspaceRoot: "/Users/test/project",
|
||||
getDirectorySuggestions: unavailableSuggestions,
|
||||
}),
|
||||
).resolves.toEqual(target);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["a bare filename", { ...target, path: "/Users/test/project/file.ts" }],
|
||||
["a path outside the workspace", { ...target, path: "/tmp/schema/x.md" }],
|
||||
["a home-relative path", { ...target, path: "~/schema/x.md" }],
|
||||
])("does not search %s", async (_label, candidate) => {
|
||||
const { getDirectorySuggestions, searches } = suggestionsFromMap({
|
||||
"schema/x.md": [{ path: "repo-a/schema/x.md", kind: "file" }],
|
||||
});
|
||||
|
||||
const result = await resolveMissingNestedRelativeFile({
|
||||
target: candidate,
|
||||
workspaceRoot: "/Users/test/project",
|
||||
getDirectorySuggestions,
|
||||
});
|
||||
|
||||
expect(searches).toEqual([]);
|
||||
expect(result).toEqual(candidate);
|
||||
});
|
||||
|
||||
it("does not search when the workspace root is blank", async () => {
|
||||
const { getDirectorySuggestions, searches } = suggestionsFromMap({});
|
||||
|
||||
const result = await resolveMissingNestedRelativeFile({
|
||||
target,
|
||||
workspaceRoot: " ",
|
||||
getDirectorySuggestions,
|
||||
});
|
||||
|
||||
expect(searches).toEqual([]);
|
||||
expect(result).toEqual(target);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["/Users/test/project/schema/x.md", "/Users/test/project"],
|
||||
["file:///Users/test/project/schema/x.md", "/Users/test/project"],
|
||||
["C:/repo/schema/x.md", "C:/repo"],
|
||||
["\\\\server\\share\\schema\\x.md", "//server/share"],
|
||||
])("keeps absolute destination %s", async (raw, workspaceRoot) => {
|
||||
const { getDirectorySuggestions, searches } = suggestionsFromMap({
|
||||
"schema/x.md": [{ path: "repo-a/schema/x.md", kind: "file" }],
|
||||
});
|
||||
const absoluteTarget = { raw, path: `${workspaceRoot}/schema/x.md` };
|
||||
await expect(
|
||||
resolveMissingNestedRelativeFile({
|
||||
target: absoluteTarget,
|
||||
workspaceRoot,
|
||||
getDirectorySuggestions,
|
||||
}),
|
||||
).resolves.toEqual(absoluteTarget);
|
||||
expect(searches).toEqual([]);
|
||||
});
|
||||
|
||||
it.each(["docs/guides", "./docs/guides", "docs/guides/"])(
|
||||
"keeps folder href %s direct",
|
||||
async (raw) => {
|
||||
const { getDirectorySuggestions, searches } = suggestionsFromMap({
|
||||
"docs/guides": [{ path: "repo-a/docs/guides", kind: "file" }],
|
||||
});
|
||||
const folderTarget = { raw, path: "/Users/test/project/docs/guides" };
|
||||
await expect(
|
||||
resolveMissingNestedRelativeFile({
|
||||
target: folderTarget,
|
||||
workspaceRoot: "/Users/test/project",
|
||||
getDirectorySuggestions,
|
||||
}),
|
||||
).resolves.toEqual(folderTarget);
|
||||
expect(searches).toEqual([]);
|
||||
},
|
||||
);
|
||||
|
||||
it("normalizes a Windows workspace root before the suffix lookup", async () => {
|
||||
const windowsTarget = {
|
||||
raw: "schema/x.md",
|
||||
path: "C:\\repo\\schema\\x.md",
|
||||
lineStart: undefined,
|
||||
lineEnd: undefined,
|
||||
};
|
||||
const { getDirectorySuggestions, searches } = suggestionsFromMap({
|
||||
"schema/x.md": [{ path: "repo-a/schema/x.md", kind: "file" }],
|
||||
});
|
||||
|
||||
const result = await resolveMissingNestedRelativeFile({
|
||||
target: windowsTarget,
|
||||
workspaceRoot: "C:\\repo\\",
|
||||
getDirectorySuggestions,
|
||||
});
|
||||
|
||||
expect(searches).toEqual([
|
||||
{
|
||||
query: "schema/x.md",
|
||||
cwd: "C:\\repo\\",
|
||||
matchMode: "suffix",
|
||||
limit: 1,
|
||||
},
|
||||
]);
|
||||
expect(result.path).toBe("C:/repo/repo-a/schema/x.md");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getAssistantFileLinkToken", () => {
|
||||
it("uses rendered text for markdown-it linkified tokens and href for explicit links", () => {
|
||||
expect(
|
||||
|
||||
@@ -5,7 +5,6 @@ import {
|
||||
type InlinePathTarget,
|
||||
} from "./parse";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import { isAbsolutePath } from "@/utils/path";
|
||||
|
||||
export interface AssistantFileLinkSource {
|
||||
href: string;
|
||||
@@ -106,62 +105,6 @@ export async function fetchDaemonResolution({
|
||||
};
|
||||
}
|
||||
|
||||
/** Only file-looking paths nested inside the workspace need suffix search. */
|
||||
function nestedRelativeLookupQuery(
|
||||
targetPath: string,
|
||||
workspaceRoot: string | undefined,
|
||||
): string | null {
|
||||
const root = workspaceRoot?.trim();
|
||||
if (!root) {
|
||||
return null;
|
||||
}
|
||||
const normalizedRoot = root.replace(/\\/g, "/").replace(/\/+$/, "");
|
||||
const normalizedPath = targetPath.replace(/\\/g, "/");
|
||||
const prefix = `${normalizedRoot}/`;
|
||||
if (!normalizedPath.startsWith(prefix)) {
|
||||
return null;
|
||||
}
|
||||
const relative = normalizedPath.slice(prefix.length);
|
||||
if (!relative.includes("/") || !isFileLookingAssistantToken(encodeURI(relative))) {
|
||||
return null;
|
||||
}
|
||||
return relative;
|
||||
}
|
||||
|
||||
/** When a markdown link points at workspaceRoot/schema/x.md and that file is
|
||||
* missing, ask the same suffix lookup bare names already use. An exact hit
|
||||
* stays on that path. A suffix hit such as repo-a/schema/x.md replaces it.
|
||||
* Lookup failure keeps the original target.
|
||||
*/
|
||||
export async function resolveMissingNestedRelativeFile(input: {
|
||||
target: InlinePathTarget;
|
||||
workspaceRoot?: string;
|
||||
getDirectorySuggestions: GetDirectorySuggestions;
|
||||
}): Promise<InlinePathTarget> {
|
||||
if (
|
||||
isAbsoluteInlineCodeToken(input.target.raw) ||
|
||||
input.target.raw.startsWith("~/") ||
|
||||
input.target.raw.endsWith("/")
|
||||
) {
|
||||
return input.target;
|
||||
}
|
||||
const query = nestedRelativeLookupQuery(input.target.path, input.workspaceRoot);
|
||||
if (!query) {
|
||||
return input.target;
|
||||
}
|
||||
try {
|
||||
return await fetchDaemonResolution({
|
||||
ambiguousQuery: query,
|
||||
token: input.target.raw,
|
||||
target: input.target,
|
||||
workspaceRoot: input.workspaceRoot,
|
||||
getDirectorySuggestions: input.getDirectorySuggestions,
|
||||
});
|
||||
} catch {
|
||||
return input.target;
|
||||
}
|
||||
}
|
||||
|
||||
export function classifyForResolution(
|
||||
source: AssistantFileLinkSource,
|
||||
context: AssistantFileLinkContext,
|
||||
@@ -272,7 +215,11 @@ export function shouldResolveDirectFileThroughSuggestions(input: {
|
||||
}
|
||||
|
||||
function isAbsoluteInlineCodeToken(token: string): boolean {
|
||||
return isAbsolutePath(token) || token.toLowerCase().startsWith("file://");
|
||||
return (
|
||||
token.startsWith("/") ||
|
||||
token.toLowerCase().startsWith("file://") ||
|
||||
/^[A-Za-z]:[\\/]/.test(token)
|
||||
);
|
||||
}
|
||||
|
||||
function isLinkifiedSource(source: AssistantFileLinkSource): boolean {
|
||||
|
||||
@@ -6,12 +6,15 @@ import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { Check, ChevronDown, ChevronRight, Eye, EyeOff, Link2 } from "lucide-react-native";
|
||||
import type { HostProfile } from "@/types/host-connection";
|
||||
import { useHosts, useHostMutations } from "@/runtime/host-runtime";
|
||||
import { parseConnectionUri, serializeConnectionUri } from "@/utils/daemon-endpoints";
|
||||
import {
|
||||
parseConnectionUri,
|
||||
serializeConnectionUri,
|
||||
serializeConnectionUriForStorage,
|
||||
} from "@/utils/daemon-endpoints";
|
||||
import { buildConnectionFailureCopy } from "./connection-failure-copy";
|
||||
import { AdaptiveModalSheet, AdaptiveTextInput, type SheetHeader } from "./adaptive-modal-sheet";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { PairingTargetTracker } from "./pair-link-credentials";
|
||||
import { buildDirectConnectionUri } from "./direct-connection-host";
|
||||
|
||||
const FLEX_ONE_STYLE = { flex: 1 } as const;
|
||||
|
||||
@@ -136,11 +139,37 @@ const styles = StyleSheet.create((theme) => ({
|
||||
},
|
||||
}));
|
||||
|
||||
function isIpv6Host(host: string): boolean {
|
||||
return host.includes(":") && !host.startsWith("[") && !host.endsWith("]");
|
||||
}
|
||||
|
||||
function buildConnectionUriFromDraft(
|
||||
draft: DirectConnectionDraft,
|
||||
labels: DirectConnectionLabels,
|
||||
): string {
|
||||
const host = draft.host.trim();
|
||||
const port = Number(draft.port.trim());
|
||||
if (!host) {
|
||||
throw new Error(labels.hostRequired);
|
||||
}
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
||||
throw new Error(labels.invalidPort);
|
||||
}
|
||||
|
||||
return serializeConnectionUriForStorage({
|
||||
host,
|
||||
port,
|
||||
isIpv6: isIpv6Host(host),
|
||||
useTls: draft.useTls,
|
||||
...(draft.password ? { password: draft.password } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
function prepareDirectConnection(
|
||||
draft: DirectConnectionDraft,
|
||||
labels: DirectConnectionLabels,
|
||||
): PreparedDirectConnection {
|
||||
const parsed = parseConnectionUri(buildDirectConnectionUri(draft, labels));
|
||||
const parsed = parseConnectionUri(buildConnectionUriFromDraft(draft, labels));
|
||||
const endpoint = parsed.isIpv6
|
||||
? `[${parsed.host}]:${parsed.port}`
|
||||
: `${parsed.host}:${parsed.port}`;
|
||||
@@ -391,7 +420,7 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
advancedTarget.current = new PairingTargetTracker("", true);
|
||||
try {
|
||||
setAdvancedUri(
|
||||
buildDirectConnectionUri({ host, port, useTls, password }, directConnectionLabels),
|
||||
buildConnectionUriFromDraft({ host, port, useTls, password }, directConnectionLabels),
|
||||
);
|
||||
} catch {
|
||||
setAdvancedUri("");
|
||||
@@ -476,7 +505,6 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
accessibilityRole="checkbox"
|
||||
accessibilityLabel={t("pairing.direct.fields.useSsl")}
|
||||
accessibilityState={useTlsAccessibilityState}
|
||||
aria-checked={useTls}
|
||||
testID="direct-ssl-toggle"
|
||||
>
|
||||
<View style={checkboxStyle}>
|
||||
|
||||
@@ -4,9 +4,11 @@ import { View, Text, Pressable } from "react-native";
|
||||
import { StyleSheet, useUnistyles } from "react-native-unistyles";
|
||||
import { X, ArrowUp, RefreshCcw, Check, Mic, Pencil } from "lucide-react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { TFunction } from "i18next";
|
||||
import { VolumeMeter } from "./volume-meter";
|
||||
import { FOOTER_HEIGHT } from "@/constants/layout";
|
||||
import type { DictationStatus } from "@/hooks/use-dictation";
|
||||
import type { DictationEmptyReason } from "@/dictation/result";
|
||||
|
||||
interface DictationControlsProps {
|
||||
volume: number;
|
||||
@@ -24,6 +26,30 @@ interface DictationControlsProps {
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
const EMPTY_REASON_MESSAGE_KEYS = {
|
||||
"no-audio": "message.dictation.empty.noAudio",
|
||||
"no-transcript": "message.dictation.empty.noTranscript",
|
||||
} as const satisfies Record<DictationEmptyReason, string>;
|
||||
|
||||
// The line under the meter once an attempt has finished without text.
|
||||
function resolveResultText(input: {
|
||||
t: TFunction;
|
||||
status: DictationStatus;
|
||||
errorText?: string;
|
||||
emptyReason?: DictationEmptyReason | null;
|
||||
}): string | null {
|
||||
const { t, status, errorText, emptyReason } = input;
|
||||
if (status === "empty") {
|
||||
return t(EMPTY_REASON_MESSAGE_KEYS[emptyReason ?? "no-transcript"]);
|
||||
}
|
||||
if (status !== "failed") {
|
||||
return null;
|
||||
}
|
||||
return errorText
|
||||
? t("message.dictation.failed", { error: errorText })
|
||||
: t("message.dictation.failedRetry");
|
||||
}
|
||||
|
||||
function formatDuration(seconds: number): string {
|
||||
const mins = Math.floor(seconds / 60);
|
||||
const secs = seconds % 60;
|
||||
@@ -147,18 +173,26 @@ export function DictationOverlay({
|
||||
isProcessing,
|
||||
status,
|
||||
errorText,
|
||||
emptyReason,
|
||||
onCancel,
|
||||
onAccept,
|
||||
onAcceptAndSend,
|
||||
onRetry,
|
||||
onDiscard,
|
||||
}: Omit<DictationControlsProps, "onStart" | "disabled" | "transcript"> & { errorText?: string }) {
|
||||
}: Omit<DictationControlsProps, "onStart" | "disabled" | "transcript"> & {
|
||||
errorText?: string;
|
||||
emptyReason?: DictationEmptyReason | null;
|
||||
}) {
|
||||
const { theme } = useUnistyles();
|
||||
const { t } = useTranslation();
|
||||
const isFailed = status === "failed";
|
||||
const isEmpty = status === "empty";
|
||||
// An empty result is a finished attempt the user has to acknowledge, like a failure.
|
||||
const isFailed = status === "failed" || isEmpty;
|
||||
const canRetry = !isEmpty || emptyReason !== "no-audio";
|
||||
const showActiveState = isRecording || isProcessing || isFailed;
|
||||
const actionsDisabled = isProcessing;
|
||||
const handleCancel = isFailed && onDiscard ? onDiscard : onCancel;
|
||||
const resultText = resolveResultText({ t, status, errorText, emptyReason });
|
||||
|
||||
const containerStyle = useMemo(
|
||||
() => [overlayStyles.container, { backgroundColor: theme.colors.accent }],
|
||||
@@ -202,26 +236,26 @@ export function DictationOverlay({
|
||||
</Pressable>
|
||||
|
||||
<View style={overlayStyles.centerContainer}>
|
||||
<View style={overlayStyles.meterRow}>
|
||||
<VolumeMeter
|
||||
volume={volume}
|
||||
isMuted={false}
|
||||
isSpeaking={false}
|
||||
orientation="horizontal"
|
||||
color={theme.colors.accentForeground}
|
||||
/>
|
||||
<Text style={overlayTimerTextStyle}>{formatDuration(duration)}</Text>
|
||||
</View>
|
||||
{!resultText ? (
|
||||
<View style={overlayStyles.meterRow}>
|
||||
<VolumeMeter
|
||||
volume={volume}
|
||||
isMuted={false}
|
||||
isSpeaking={false}
|
||||
orientation="horizontal"
|
||||
color={theme.colors.accentForeground}
|
||||
/>
|
||||
<Text style={overlayTimerTextStyle}>{formatDuration(duration)}</Text>
|
||||
</View>
|
||||
) : null}
|
||||
{status === "paused" ? (
|
||||
<Text numberOfLines={2} style={overlayTranscriptTextStyle}>
|
||||
{t("message.dictation.paused")}
|
||||
</Text>
|
||||
) : null}
|
||||
{isFailed ? (
|
||||
{resultText ? (
|
||||
<Text numberOfLines={2} style={overlayTranscriptTextStyle}>
|
||||
{errorText
|
||||
? t("message.dictation.failed", { error: errorText })
|
||||
: t("message.dictation.failedRetry")}
|
||||
{resultText}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
@@ -232,7 +266,7 @@ export function DictationOverlay({
|
||||
<LoadingSpinner size="small" color={theme.colors.accentForeground} />
|
||||
</View>
|
||||
) : null}
|
||||
{!actionsDisabled && isFailed ? (
|
||||
{!actionsDisabled && isFailed && canRetry ? (
|
||||
<Pressable
|
||||
onPress={onRetry}
|
||||
accessibilityRole="button"
|
||||
|
||||
@@ -1,68 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildDirectConnectionUri, normalizeDirectConnectionHost } from "./direct-connection-host";
|
||||
|
||||
const labels = {
|
||||
hostRequired: "host required",
|
||||
invalidPort: "invalid port",
|
||||
};
|
||||
|
||||
function buildUri(host: string, port = "6767"): string {
|
||||
return buildDirectConnectionUri({ host, port, useTls: false, password: "" }, labels);
|
||||
}
|
||||
|
||||
describe("normalizeDirectConnectionHost", () => {
|
||||
it.each([
|
||||
["100.66.69.36", { host: "100.66.69.36", port: null, isIpv6: false }],
|
||||
[" 100.66.69.36 ", { host: "100.66.69.36", port: null, isIpv6: false }],
|
||||
["100.66.69.36:6767", { host: "100.66.69.36", port: "6767", isIpv6: false }],
|
||||
["tcp://100.66.69.36:6767", { host: "100.66.69.36", port: "6767", isIpv6: false }],
|
||||
["http://100.66.69.36:6767/path?x=1#y", { host: "100.66.69.36", port: "6767", isIpv6: false }],
|
||||
["HTTPS://example.test", { host: "example.test", port: null, isIpv6: false }],
|
||||
["my-host.local:7000", { host: "my-host.local", port: "7000", isIpv6: false }],
|
||||
["[::1]", { host: "::1", port: null, isIpv6: true }],
|
||||
["[::1]:7000", { host: "::1", port: "7000", isIpv6: true }],
|
||||
["::1", { host: "::1", port: null, isIpv6: true }],
|
||||
["fe80::1", { host: "fe80::1", port: null, isIpv6: true }],
|
||||
["", { host: "", port: null, isIpv6: false }],
|
||||
])("normalizes %j", (input, expected) => {
|
||||
expect(normalizeDirectConnectionHost(input)).toEqual(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildDirectConnectionUri", () => {
|
||||
it.each([
|
||||
["100.66.69.36", "tcp://100.66.69.36:6767"],
|
||||
["100.66.69.36:6767", "tcp://100.66.69.36:6767"],
|
||||
["tcp://100.66.69.36:6767", "tcp://100.66.69.36:6767"],
|
||||
["http://100.66.69.36:6767/path?x", "tcp://100.66.69.36:6767"],
|
||||
["my-host.local:6767", "tcp://my-host.local:6767"],
|
||||
["[::1]", "tcp://[::1]:6767"],
|
||||
["[::1]:7000", "tcp://[::1]:7000"],
|
||||
["::1", "tcp://[::1]:6767"],
|
||||
["fe80::1", "tcp://[fe80::1]:6767"],
|
||||
])("builds a tcp URI from host %j", (host, expected) => {
|
||||
expect(buildUri(host)).toBe(expected);
|
||||
});
|
||||
|
||||
it("lets a port typed in the host field override the port field", () => {
|
||||
expect(buildUri("100.66.69.36:7000", "6767")).toBe("tcp://100.66.69.36:7000");
|
||||
});
|
||||
|
||||
it("keeps TLS and password settings", () => {
|
||||
expect(
|
||||
buildDirectConnectionUri(
|
||||
{ host: "tcp://example.test:443", port: "6767", useTls: true, password: "secret" },
|
||||
labels,
|
||||
),
|
||||
).toBe("tcp://example.test:443?ssl=true&password=secret");
|
||||
});
|
||||
|
||||
it.each(["", " ", "tcp://", "http:///path"])("requires a host for %j", (host) => {
|
||||
expect(() => buildUri(host)).toThrow("host required");
|
||||
});
|
||||
|
||||
it("rejects an invalid port", () => {
|
||||
expect(() => buildUri("100.66.69.36", "70000")).toThrow("invalid port");
|
||||
expect(() => buildUri("100.66.69.36:0")).toThrow("invalid port");
|
||||
});
|
||||
});
|
||||
@@ -1,70 +0,0 @@
|
||||
import { serializeConnectionUriForStorage } from "@/utils/daemon-endpoints";
|
||||
|
||||
export interface DirectConnectionHostInput {
|
||||
host: string;
|
||||
port: string;
|
||||
useTls: boolean;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface DirectConnectionHostLabels {
|
||||
hostRequired: string;
|
||||
invalidPort: string;
|
||||
}
|
||||
|
||||
export interface NormalizedDirectConnectionHost {
|
||||
host: string;
|
||||
/** Port typed into the host field, if any. Overrides the separate port field. */
|
||||
port: string | null;
|
||||
isIpv6: boolean;
|
||||
}
|
||||
|
||||
const SCHEME_PATTERN = /^[a-z][a-z0-9+.-]*:\/\//i;
|
||||
const BRACKETED_IPV6_PATTERN = /^\[([^\]]*)\](?::(\d*))?$/;
|
||||
const HOST_WITH_PORT_PATTERN = /^([^:]+):(\d+)$/;
|
||||
|
||||
/**
|
||||
* Users often paste `host:port` or a full URL into the host field.
|
||||
* Reduce it to a bare host (plus an optional port) before building the URI.
|
||||
*/
|
||||
export function normalizeDirectConnectionHost(input: string): NormalizedDirectConnectionHost {
|
||||
let host = input.trim().replace(SCHEME_PATTERN, "");
|
||||
const suffixIndex = host.search(/[/?#]/);
|
||||
if (suffixIndex !== -1) {
|
||||
host = host.slice(0, suffixIndex);
|
||||
}
|
||||
|
||||
const bracketed = BRACKETED_IPV6_PATTERN.exec(host);
|
||||
if (bracketed) {
|
||||
return { host: bracketed[1] ?? "", port: bracketed[2] || null, isIpv6: true };
|
||||
}
|
||||
|
||||
const hostWithPort = HOST_WITH_PORT_PATTERN.exec(host);
|
||||
if (hostWithPort) {
|
||||
return { host: hostWithPort[1] ?? "", port: hostWithPort[2] ?? null, isIpv6: false };
|
||||
}
|
||||
|
||||
return { host, port: null, isIpv6: host.split(":").length > 2 };
|
||||
}
|
||||
|
||||
export function buildDirectConnectionUri(
|
||||
draft: DirectConnectionHostInput,
|
||||
labels: DirectConnectionHostLabels,
|
||||
): string {
|
||||
const normalized = normalizeDirectConnectionHost(draft.host);
|
||||
const port = Number((normalized.port ?? draft.port).trim());
|
||||
if (!normalized.host) {
|
||||
throw new Error(labels.hostRequired);
|
||||
}
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
||||
throw new Error(labels.invalidPort);
|
||||
}
|
||||
|
||||
return serializeConnectionUriForStorage({
|
||||
host: normalized.host,
|
||||
port,
|
||||
isIpv6: normalized.isIpv6,
|
||||
useTls: draft.useTls,
|
||||
...(draft.password ? { password: draft.password } : {}),
|
||||
});
|
||||
}
|
||||
@@ -35,15 +35,11 @@ export interface MarkdownImageContext {
|
||||
filePath?: string;
|
||||
}
|
||||
|
||||
export function useMarkdownSource(
|
||||
text: string,
|
||||
context: MarkdownImageContext,
|
||||
commandNames?: ReadonlySet<string>,
|
||||
) {
|
||||
export function useMarkdownSource(text: string, context: MarkdownImageContext) {
|
||||
const occurrenceKey = useId();
|
||||
const prepared = useMemo(
|
||||
() => prepareMarkdownSource(text, context.workspaceRoot, { supportsSvg: isWeb, commandNames }),
|
||||
[text, context.workspaceRoot, commandNames],
|
||||
() => prepareMarkdownSource(text, context.workspaceRoot, { supportsSvg: isWeb }),
|
||||
[text, context.workspaceRoot],
|
||||
);
|
||||
const sources = [...new Set(prepared.images.map((image) => image.source))];
|
||||
const acquisitions = sources.map((source) => {
|
||||
|
||||
@@ -2,8 +2,6 @@ import { fromMarkdown } from "mdast-util-from-markdown";
|
||||
import { toNativeLinkRecognition } from "react-native-enriched-markdown/src/utils/regexParser";
|
||||
import { parseMarkdown } from "react-native-enriched-markdown/src/web/parseMarkdown";
|
||||
import { recognizeTextLinks } from "react-native-enriched-markdown/src/web/recognizeTextLinks";
|
||||
import { matchCommandLink } from "@/agent-commands";
|
||||
|
||||
import { classifyAssistantFileLink } from "@/assistant-file-links";
|
||||
import { markInlineImages } from "react-native-enriched-markdown/src/web/utils";
|
||||
import type { ASTNode } from "react-native-enriched-markdown/src/web/types";
|
||||
@@ -15,28 +13,6 @@ import { createMarkdownStyles } from "./styles";
|
||||
import { prepareMarkdownSource, PENDING_MARKDOWN_IMAGE } from "./source";
|
||||
import { normalizeMarkdownHtml } from "./html";
|
||||
|
||||
it("recognizes complete known commands in inline code", () => {
|
||||
const names = new Set(["code-review", "review:fast"]);
|
||||
const prepared = prepareMarkdownSource("`/code-review` `/unknown`", undefined, {
|
||||
commandNames: names,
|
||||
});
|
||||
expect(prepared.linkRecognition.inlineCode.test("/code-review")).toBe(true);
|
||||
expect(prepared.linkRecognition.inlineCode.test("/unknown")).toBe(
|
||||
prepareMarkdownSource("`/unknown`").linkRecognition.inlineCode.test("/unknown"),
|
||||
);
|
||||
const nonPath = prepareMarkdownSource("`/review:fast`", undefined, { commandNames: names });
|
||||
expect(nonPath.linkRecognition.inlineCode.test("/review:fast")).toBe(true);
|
||||
expect(matchCommandLink("/code-review", "inline-code", names)).toBe("/code-review");
|
||||
});
|
||||
|
||||
it("resolves authored root-relative links only when the target is a known command", () => {
|
||||
const names = new Set(["code-review"]);
|
||||
expect(matchCommandLink("/code-review", "markdown", names)).toBe("/code-review");
|
||||
expect(matchCommandLink("/code-review/file", "markdown", names)).toBeNull();
|
||||
expect(matchCommandLink("/code-review", "text", names)).toBeNull();
|
||||
expect(matchCommandLink("https://example.com/code-review", "markdown", names)).toBeNull();
|
||||
});
|
||||
|
||||
describe("shared Markdown source adaptation", () => {
|
||||
it("keeps paragraphs, fences and quotes together for the library", () => {
|
||||
const source = "First paragraph.\n\nSecond paragraph.\n\n```ts\nconst n = 1;\n```\n\n> Quote";
|
||||
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
useAssistantFileLinkEnvironment,
|
||||
} from "@/assistant-file-links";
|
||||
import { useStableEvent } from "@/hooks/use-stable-event";
|
||||
import { matchCommandLink, useAgentCommandHints, type CommandHints } from "@/agent-commands";
|
||||
import { AttachmentLightbox, type ImageLightboxSource } from "@/components/attachment-lightbox";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
@@ -49,7 +48,6 @@ export interface MarkdownRendererProps extends MarkdownImageContext {
|
||||
selectable?: boolean;
|
||||
streaming?: boolean;
|
||||
onLinkPress?: (url: string) => unknown;
|
||||
agentCommands?: boolean;
|
||||
}
|
||||
|
||||
/** All Markdown surfaces share the same engine and source adaptation. */
|
||||
@@ -61,21 +59,15 @@ export const MarkdownRenderer = memo(function MarkdownRenderer(props: MarkdownRe
|
||||
() => splitStreamingMarkdown(completeLines, true).head.length,
|
||||
[completeLines],
|
||||
);
|
||||
const Part = props.agentCommands ? CommandMarkdownPart : MarkdownPart;
|
||||
if (!streaming || boundary === 0) return <Part {...props} />;
|
||||
if (!streaming || boundary === 0) return <MarkdownPart {...props} />;
|
||||
return (
|
||||
<MarkdownBlockStack>
|
||||
<Part {...props} text={props.text.slice(0, boundary)} />
|
||||
<Part {...props} text={props.text.slice(boundary)} />
|
||||
<MarkdownPart {...props} text={props.text.slice(0, boundary)} />
|
||||
<MarkdownPart {...props} text={props.text.slice(boundary)} />
|
||||
</MarkdownBlockStack>
|
||||
);
|
||||
});
|
||||
|
||||
const CommandMarkdownPart = memo(function CommandMarkdownPart(props: MarkdownRendererProps) {
|
||||
const commandHints = useAgentCommandHints();
|
||||
return <MarkdownPart {...props} commandHints={commandHints} />;
|
||||
});
|
||||
|
||||
const MarkdownPart = memo(function MarkdownPart({
|
||||
text,
|
||||
compact = false,
|
||||
@@ -83,10 +75,8 @@ const MarkdownPart = memo(function MarkdownPart({
|
||||
selectable = true,
|
||||
streaming = false,
|
||||
onLinkPress,
|
||||
agentCommands: _agentCommands,
|
||||
commandHints = null,
|
||||
...imageContext
|
||||
}: MarkdownRendererProps & { commandHints?: CommandHints | null }) {
|
||||
}: MarkdownRendererProps) {
|
||||
const environment = useAssistantFileLinkEnvironment();
|
||||
const actions = useAssistantFileLinkActions();
|
||||
const client =
|
||||
@@ -94,23 +84,14 @@ const MarkdownPart = memo(function MarkdownPart({
|
||||
(environment.client?.readFile
|
||||
? { readFile: environment.client.readFile.bind(environment.client) }
|
||||
: undefined);
|
||||
const { markdown, imageSources, linkRecognition, linkSource } = useMarkdownSource(
|
||||
text,
|
||||
{
|
||||
workspaceRoot: environment.workspaceRoot,
|
||||
serverId: environment.serverId,
|
||||
...imageContext,
|
||||
client,
|
||||
},
|
||||
commandHints?.names,
|
||||
);
|
||||
const { markdown, imageSources, linkRecognition, linkSource } = useMarkdownSource(text, {
|
||||
workspaceRoot: environment.workspaceRoot,
|
||||
serverId: environment.serverId,
|
||||
...imageContext,
|
||||
client,
|
||||
});
|
||||
const [image, setImage] = useState<ImageLightboxSource | null>(null);
|
||||
const pressLink = useStableEvent(({ url, sourceType }: LinkPressEvent) => {
|
||||
const command = commandHints && matchCommandLink(url, sourceType, commandHints.names);
|
||||
if (command) {
|
||||
commandHints.insert(command);
|
||||
return;
|
||||
}
|
||||
const source = linkSource(url, sourceType);
|
||||
if (onLinkPress && !actions.canResolveFile(source)) onLinkPress(url);
|
||||
else actions.open(source, "preferred");
|
||||
|
||||
@@ -56,11 +56,7 @@ function linkMetadata(inlineCodePaths: ReadonlySet<string>) {
|
||||
};
|
||||
}
|
||||
|
||||
function collectInlineCodePaths(
|
||||
source: string,
|
||||
workspaceRoot?: string,
|
||||
commandNames?: ReadonlySet<string>,
|
||||
): ReadonlySet<string> {
|
||||
function collectInlineCodePaths(source: string, workspaceRoot?: string): ReadonlySet<string> {
|
||||
const paths = new Set<string>();
|
||||
const previousEnds = new Map<number, number>();
|
||||
// Collect candidates between consecutive runs of equal length. The engine owns
|
||||
@@ -78,11 +74,7 @@ function collectInlineCodePaths(
|
||||
value = value.slice(1, -1);
|
||||
}
|
||||
const classification = classifyAssistantFileLink(value, { workspaceRoot });
|
||||
if (
|
||||
(classification && classification.kind !== "external") ||
|
||||
(value.startsWith("/") && commandNames?.has(value.slice(1)))
|
||||
)
|
||||
paths.add(value);
|
||||
if (classification && classification.kind !== "external") paths.add(value);
|
||||
}
|
||||
return paths;
|
||||
}
|
||||
@@ -120,7 +112,7 @@ function workspaceHoverTitle(link: Link, markup: string, workspaceRoot?: string)
|
||||
export function prepareMarkdownSource(
|
||||
source: string,
|
||||
workspaceRoot?: string,
|
||||
options: { supportsSvg?: boolean; commandNames?: ReadonlySet<string> } = {},
|
||||
options: { supportsSvg?: boolean } = {},
|
||||
) {
|
||||
source = normalizeMarkdownHtml(source);
|
||||
const images: MarkdownImage[] = [];
|
||||
@@ -130,9 +122,7 @@ export function prepareMarkdownSource(
|
||||
extensions: [gfmTable()],
|
||||
mdastExtensions: [gfmTableFromMarkdown()],
|
||||
}));
|
||||
const metadata = linkMetadata(
|
||||
collectInlineCodePaths(source, workspaceRoot, options.commandNames),
|
||||
);
|
||||
const metadata = linkMetadata(collectInlineCodePaths(source, workspaceRoot));
|
||||
const edits: { start: number; end: number; text: string }[] = [];
|
||||
if (
|
||||
!source.includes("![") &&
|
||||
|
||||
@@ -1199,7 +1199,6 @@ export const AssistantMessage = memo(function AssistantMessage({
|
||||
>
|
||||
<MarkdownRenderer
|
||||
text={revealedMessage}
|
||||
agentCommands
|
||||
streaming={phase !== "complete" || revealedMessage.length < renderedMessage.text.length}
|
||||
client={client}
|
||||
workspaceRoot={workspaceRoot}
|
||||
|
||||
@@ -462,7 +462,7 @@ describe("sidebar group visibility", () => {
|
||||
|
||||
it.each([0, 7, 8])("limits %i Done rows to seven", (count) => {
|
||||
const items = entries(Array(count).fill("done"));
|
||||
const { result } = renderHook(() => useLimitedSidebarGroup({ items, selection: null, policy }));
|
||||
const { result } = renderHook(() => useLimitedSidebarGroup(items, policy));
|
||||
expect(result.current.visibleItems).toEqual(items.slice(0, 7));
|
||||
expect(result.current.canToggle).toBe(count > 7);
|
||||
});
|
||||
@@ -471,9 +471,7 @@ describe("sidebar group visibility", () => {
|
||||
"keeps row twelve visible for %s without filling gaps",
|
||||
(status) => {
|
||||
const items = entries([...Array(11).fill("done"), status]);
|
||||
const { result } = renderHook(() =>
|
||||
useLimitedSidebarGroup({ items, selection: null, policy }),
|
||||
);
|
||||
const { result } = renderHook(() => useLimitedSidebarGroup(items, policy));
|
||||
expect(names(result.current.visibleItems)).toEqual([
|
||||
"row-1",
|
||||
"row-2",
|
||||
@@ -494,11 +492,7 @@ describe("sidebar group visibility", () => {
|
||||
const hydrated = new Map(items.slice(0, 9).map((item) => [item.workspaceKey, item]));
|
||||
for (const entriesByKey of [new Map(), hydrated]) {
|
||||
const { result } = renderHook(() =>
|
||||
useLimitedSidebarGroup({
|
||||
items,
|
||||
selection: null,
|
||||
policy: createWorkspaceVisibilityPolicy(entriesByKey),
|
||||
}),
|
||||
useLimitedSidebarGroup(items, createWorkspaceVisibilityPolicy(entriesByKey)),
|
||||
);
|
||||
expect(result.current.canToggle).toBe(true);
|
||||
expect(names(result.current.visibleItems)).toEqual(
|
||||
@@ -518,7 +512,7 @@ describe("sidebar group visibility", () => {
|
||||
"needs_input",
|
||||
"failed",
|
||||
]);
|
||||
const { result } = renderHook(() => useLimitedSidebarGroup({ items, selection: null, policy }));
|
||||
const { result } = renderHook(() => useLimitedSidebarGroup(items, policy));
|
||||
expect(result.current.visibleItems).toEqual(items);
|
||||
expect(result.current.canToggle).toBe(false);
|
||||
});
|
||||
@@ -533,7 +527,7 @@ describe("sidebar group visibility", () => {
|
||||
"attention",
|
||||
]);
|
||||
const { result, rerender, unmount } = renderHook(
|
||||
({ rows }) => useLimitedSidebarGroup({ items: rows, selection: null, policy }),
|
||||
({ rows }) => useLimitedSidebarGroup(rows, policy),
|
||||
{ initialProps: { rows: items } },
|
||||
);
|
||||
expect(names(result.current.visibleItems)).toEqual([
|
||||
@@ -574,7 +568,7 @@ describe("sidebar group visibility", () => {
|
||||
expect(result.current.expanded).toBe(false);
|
||||
act(() => result.current.toggleExpanded());
|
||||
unmount();
|
||||
const remounted = renderHook(() => useLimitedSidebarGroup({ items, selection: null, policy }));
|
||||
const remounted = renderHook(() => useLimitedSidebarGroup(items, policy));
|
||||
expect(remounted.result.current.expanded).toBe(false);
|
||||
expect(remounted.result.current.visibleItems).toHaveLength(10);
|
||||
});
|
||||
@@ -598,12 +592,7 @@ describe("sidebar group visibility", () => {
|
||||
lifecycle: "active" as const,
|
||||
};
|
||||
const { result, rerender } = renderHook(
|
||||
({ last }) =>
|
||||
useLimitedSidebarGroup({
|
||||
items: [...items.slice(0, 11), last],
|
||||
selection: null,
|
||||
policy,
|
||||
}),
|
||||
({ last }) => useLimitedSidebarGroup([...items.slice(0, 11), last], policy),
|
||||
{ initialProps: { last: items[11] } },
|
||||
);
|
||||
expect(result.current.visibleItems).toHaveLength(7);
|
||||
@@ -641,7 +630,7 @@ describe("sidebar group visibility", () => {
|
||||
|
||||
it("preserves the twenty-row pinned policy regardless of status", () => {
|
||||
const items = entries(Array(21).fill("running"));
|
||||
const { result } = renderHook(() => useLimitedSidebarGroup({ items, selection: null }));
|
||||
const { result } = renderHook(() => useLimitedSidebarGroup(items));
|
||||
expect(result.current.visibleItems).toEqual(items.slice(0, 20));
|
||||
expect(result.current.canToggle).toBe(true);
|
||||
act(() => result.current.toggleExpanded());
|
||||
|
||||
@@ -1598,16 +1598,11 @@ function ProjectBlock({
|
||||
[workspaceEntriesByKey],
|
||||
);
|
||||
const {
|
||||
leadingItem: leadingWorkspace,
|
||||
visibleItems: visibleWorkspaces,
|
||||
expanded: workspacesExpanded,
|
||||
canToggle: canToggleWorkspaces,
|
||||
toggleExpanded: toggleWorkspacesExpanded,
|
||||
} = useLimitedSidebarGroup({
|
||||
items: project.workspaces,
|
||||
selection: selectionEnabled ? activeWorkspaceSelection : null,
|
||||
policy: visibilityPolicy,
|
||||
});
|
||||
} = useLimitedSidebarGroup(project.workspaces, visibilityPolicy);
|
||||
const activeServerId = activeWorkspaceSelection?.serverId ?? null;
|
||||
const activeHostStatus = useHostRuntimeConnectionStatus(activeServerId ?? "");
|
||||
const preferredServerId = activeHostStatus === "online" ? activeServerId : null;
|
||||
@@ -1766,33 +1761,28 @@ function ProjectBlock({
|
||||
let projectChildren = null;
|
||||
if (!collapsed) {
|
||||
if (project.workspaces.length > 0) {
|
||||
const leadingWorkspaceRow = leadingWorkspace ? renderWorkspaceRow(leadingWorkspace) : null;
|
||||
projectChildren = (
|
||||
<>
|
||||
{manualSort ? (
|
||||
<>
|
||||
{leadingWorkspaceRow}
|
||||
<DraggableList
|
||||
testID={`sidebar-workspace-list-${project.viewKey}`}
|
||||
data={visibleWorkspaces}
|
||||
keyExtractor={workspaceKeyExtractor}
|
||||
renderItem={renderWorkspace}
|
||||
onDragEnd={handleWorkspaceDragEnd}
|
||||
extraData={activeWorkspaceSelectionKey(activeWorkspaceSelection)}
|
||||
scrollEnabled={false}
|
||||
useDragHandle
|
||||
nestable={useNestable}
|
||||
simultaneousGestureRef={parentGestureRef}
|
||||
gestureHostPresented={dragGestureHostActive}
|
||||
containerStyle={styles.workspaceListContainer}
|
||||
/>
|
||||
</>
|
||||
<DraggableList
|
||||
testID={`sidebar-workspace-list-${project.viewKey}`}
|
||||
data={visibleWorkspaces}
|
||||
keyExtractor={workspaceKeyExtractor}
|
||||
renderItem={renderWorkspace}
|
||||
onDragEnd={handleWorkspaceDragEnd}
|
||||
extraData={activeWorkspaceSelectionKey(activeWorkspaceSelection)}
|
||||
scrollEnabled={false}
|
||||
useDragHandle
|
||||
nestable={useNestable}
|
||||
simultaneousGestureRef={parentGestureRef}
|
||||
gestureHostPresented={dragGestureHostActive}
|
||||
containerStyle={styles.workspaceListContainer}
|
||||
/>
|
||||
) : (
|
||||
<View
|
||||
testID={`sidebar-workspace-list-${project.viewKey}`}
|
||||
style={styles.workspaceListContainer}
|
||||
>
|
||||
{leadingWorkspaceRow}
|
||||
{visibleWorkspaces.map((item) => renderWorkspaceRow(item))}
|
||||
</View>
|
||||
)}
|
||||
@@ -2198,15 +2188,11 @@ function ProjectModeList({
|
||||
const activeWorkspaceSelection = useActiveWorkspaceSelection();
|
||||
const { pinnedChats, unpinnedProjects } = pinnedGroups;
|
||||
const {
|
||||
leadingItem: leadingPinnedChat,
|
||||
visibleItems: visiblePinnedChats,
|
||||
expanded: pinnedChatsExpanded,
|
||||
canToggle: canTogglePinnedChats,
|
||||
toggleExpanded: togglePinnedChatsExpanded,
|
||||
} = useLimitedSidebarGroup({
|
||||
items: pinnedChats,
|
||||
selection: selectionEnabled ? activeWorkspaceSelection : null,
|
||||
});
|
||||
} = useLimitedSidebarGroup(pinnedChats);
|
||||
const nativeScrollGestureProps = useMemo(
|
||||
() =>
|
||||
parentGestureRef
|
||||
@@ -2409,38 +2395,37 @@ function ProjectModeList({
|
||||
[renderProjectBlock],
|
||||
);
|
||||
|
||||
const renderPinnedChatRow = useCallback(
|
||||
(
|
||||
workspace: SidebarWorkspacePlacement,
|
||||
input?: {
|
||||
drag?: () => void;
|
||||
isDragging?: boolean;
|
||||
dragHandleProps?: DraggableListDragHandleProps;
|
||||
},
|
||||
) => (
|
||||
<MemoWorkspaceRowItem
|
||||
key={workspace.workspaceKey}
|
||||
workspace={workspace}
|
||||
workspaceEntry={workspaceEntriesByKey.get(workspace.workspaceKey) ?? null}
|
||||
hostBadge={hostBadgeByServerId.get(workspace.serverId) ?? null}
|
||||
leadingProjectName={workspace.projectName}
|
||||
leadingProjectIconDataUri={
|
||||
projectIconByProjectViewKey.get(workspace.projectViewKey) ?? null
|
||||
}
|
||||
shortcutNumber={shortcutIndexByWorkspaceKey.get(workspace.workspaceKey) ?? null}
|
||||
showShortcutBadge={showShortcutBadges}
|
||||
canCopyBranchName={workspace.projectKind === "git"}
|
||||
canPin={supportsPinningByServerId.get(workspace.serverId) === true}
|
||||
onToggleWorkspacePin={onToggleWorkspacePin}
|
||||
isCreating={creatingWorkspaceIds.has(workspace.workspaceId)}
|
||||
selectionEnabled={selectionEnabled}
|
||||
activeWorkspaceSelection={activeWorkspaceSelection}
|
||||
onWorkspacePress={onWorkspacePress}
|
||||
drag={input?.drag}
|
||||
isDragging={input?.isDragging}
|
||||
dragHandleProps={input?.dragHandleProps}
|
||||
/>
|
||||
),
|
||||
const renderPinnedChat = useCallback(
|
||||
({
|
||||
item: workspace,
|
||||
drag,
|
||||
isActive,
|
||||
dragHandleProps,
|
||||
}: DraggableRenderItemInfo<SidebarWorkspacePlacement>) => {
|
||||
return (
|
||||
<MemoWorkspaceRowItem
|
||||
workspace={workspace}
|
||||
workspaceEntry={workspaceEntriesByKey.get(workspace.workspaceKey) ?? null}
|
||||
hostBadge={hostBadgeByServerId.get(workspace.serverId) ?? null}
|
||||
leadingProjectName={workspace.projectName}
|
||||
leadingProjectIconDataUri={
|
||||
projectIconByProjectViewKey.get(workspace.projectViewKey) ?? null
|
||||
}
|
||||
shortcutNumber={shortcutIndexByWorkspaceKey.get(workspace.workspaceKey) ?? null}
|
||||
showShortcutBadge={showShortcutBadges}
|
||||
canCopyBranchName={workspace.projectKind === "git"}
|
||||
canPin={supportsPinningByServerId.get(workspace.serverId) === true}
|
||||
onToggleWorkspacePin={onToggleWorkspacePin}
|
||||
isCreating={creatingWorkspaceIds.has(workspace.workspaceId)}
|
||||
selectionEnabled={selectionEnabled}
|
||||
activeWorkspaceSelection={activeWorkspaceSelection}
|
||||
onWorkspacePress={onWorkspacePress}
|
||||
drag={drag}
|
||||
isDragging={isActive}
|
||||
dragHandleProps={dragHandleProps}
|
||||
/>
|
||||
);
|
||||
},
|
||||
[
|
||||
activeWorkspaceSelection,
|
||||
creatingWorkspaceIds,
|
||||
@@ -2456,22 +2441,6 @@ function ProjectModeList({
|
||||
],
|
||||
);
|
||||
|
||||
const renderPinnedChat = useCallback(
|
||||
({
|
||||
item: workspace,
|
||||
drag,
|
||||
isActive,
|
||||
dragHandleProps,
|
||||
}: DraggableRenderItemInfo<SidebarWorkspacePlacement>) => {
|
||||
return renderPinnedChatRow(workspace, {
|
||||
drag,
|
||||
isDragging: isActive,
|
||||
dragHandleProps,
|
||||
});
|
||||
},
|
||||
[renderPinnedChatRow],
|
||||
);
|
||||
|
||||
const projectBody =
|
||||
projects.length === 0 ? (
|
||||
<SidebarProjectEmptyState onAddProject={onAddProject} onImportSession={onImportSession} />
|
||||
@@ -2504,7 +2473,6 @@ function ProjectModeList({
|
||||
/>
|
||||
{pinnedCollapsed ? null : (
|
||||
<>
|
||||
{leadingPinnedChat ? renderPinnedChatRow(leadingPinnedChat) : null}
|
||||
<DraggableList
|
||||
testID="sidebar-pinned-list"
|
||||
data={visiblePinnedChats}
|
||||
|
||||
@@ -1,137 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { SidebarStateBucket } from "@/hooks/sidebar-workspaces-view-model";
|
||||
import type { ActiveWorkspaceSelection } from "@/stores/last-workspace-selection";
|
||||
import {
|
||||
selectSidebarGroupVisibility,
|
||||
type SidebarGroupItem,
|
||||
type SidebarGroupVisibilityPolicy,
|
||||
} from "./sidebar-group-visibility";
|
||||
|
||||
interface Item extends SidebarGroupItem {
|
||||
id: number;
|
||||
statusBucket: SidebarStateBucket;
|
||||
}
|
||||
|
||||
const serverId = "host-a";
|
||||
|
||||
function rows(statuses: readonly SidebarStateBucket[], rowServerId = serverId): Item[] {
|
||||
return statuses.map((statusBucket, index) => ({
|
||||
id: index + 1,
|
||||
serverId: rowServerId,
|
||||
workspaceId: `workspace-${index + 1}`,
|
||||
statusBucket,
|
||||
}));
|
||||
}
|
||||
|
||||
const workspacePolicy: SidebarGroupVisibilityPolicy<Item> = {
|
||||
kind: "workspaces",
|
||||
getStatusBucket: (item) => item.statusBucket,
|
||||
};
|
||||
|
||||
function selectionFor(item: SidebarGroupItem): ActiveWorkspaceSelection {
|
||||
return { serverId: item.serverId, workspaceId: item.workspaceId };
|
||||
}
|
||||
|
||||
describe("selectSidebarGroupVisibility", () => {
|
||||
it("leads with a hidden open row while keeping the baseline order", () => {
|
||||
const items = rows(Array(9).fill("done"));
|
||||
const result = selectSidebarGroupVisibility({
|
||||
items,
|
||||
expanded: false,
|
||||
policy: workspacePolicy,
|
||||
selection: selectionFor(items[8]!),
|
||||
});
|
||||
|
||||
expect(result.leadingItem).toBe(items[8]);
|
||||
expect(result.visibleItems).toEqual(items.slice(0, 7));
|
||||
expect(result.canToggle).toBe(true);
|
||||
});
|
||||
|
||||
it("leaves selected rows in place when they are already in the baseline", () => {
|
||||
const items = rows([...Array(8).fill("done"), "running", "done"]);
|
||||
const expected = [...items.slice(0, 7), items[8]];
|
||||
|
||||
for (const selectedIndex of [2, 8]) {
|
||||
const result = selectSidebarGroupVisibility({
|
||||
items,
|
||||
expanded: false,
|
||||
policy: workspacePolicy,
|
||||
selection: selectionFor(items[selectedIndex]!),
|
||||
});
|
||||
|
||||
expect(result.leadingItem).toBeNull();
|
||||
expect(result.visibleItems).toEqual(expected);
|
||||
expect(result.canToggle).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("shows the whole group without a toggle when the open row is the only hidden row", () => {
|
||||
const items = rows(Array(8).fill("done"));
|
||||
const result = selectSidebarGroupVisibility({
|
||||
items,
|
||||
expanded: false,
|
||||
policy: workspacePolicy,
|
||||
selection: selectionFor(items[7]!),
|
||||
});
|
||||
|
||||
expect(result.leadingItem).toBeNull();
|
||||
expect(result.visibleItems).toEqual(items);
|
||||
expect(result.canToggle).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps expanded groups in their original order", () => {
|
||||
const items = rows(Array(9).fill("done"));
|
||||
const result = selectSidebarGroupVisibility({
|
||||
items,
|
||||
expanded: true,
|
||||
policy: workspacePolicy,
|
||||
selection: selectionFor(items[8]!),
|
||||
});
|
||||
|
||||
expect(result.leadingItem).toBeNull();
|
||||
expect(result.visibleItems).toEqual(items);
|
||||
expect(result.canToggle).toBe(true);
|
||||
});
|
||||
|
||||
it("applies the twenty-row limit to pinned groups", () => {
|
||||
const items = rows(Array(22).fill("done"));
|
||||
const result = selectSidebarGroupVisibility({
|
||||
items,
|
||||
expanded: false,
|
||||
policy: { kind: "pinned" },
|
||||
selection: selectionFor(items[21]!),
|
||||
});
|
||||
|
||||
expect(result.leadingItem).toBe(items[21]);
|
||||
expect(result.visibleItems).toEqual(items.slice(0, 20));
|
||||
expect(result.canToggle).toBe(true);
|
||||
});
|
||||
|
||||
it("preserves the current limit when selection is null", () => {
|
||||
const items = rows(Array(8).fill("done"));
|
||||
const result = selectSidebarGroupVisibility({
|
||||
items,
|
||||
expanded: false,
|
||||
policy: workspacePolicy,
|
||||
selection: null,
|
||||
});
|
||||
|
||||
expect(result.leadingItem).toBeNull();
|
||||
expect(result.visibleItems).toEqual(items.slice(0, 7));
|
||||
expect(result.canToggle).toBe(true);
|
||||
});
|
||||
|
||||
it("matches the open row by server and workspace identity", () => {
|
||||
const items = rows(Array(9).fill("done"), "host-b");
|
||||
const result = selectSidebarGroupVisibility({
|
||||
items,
|
||||
expanded: false,
|
||||
policy: workspacePolicy,
|
||||
selection: { serverId: serverId, workspaceId: items[8]!.workspaceId },
|
||||
});
|
||||
|
||||
expect(result.leadingItem).toBeNull();
|
||||
expect(result.visibleItems).toEqual(items.slice(0, 7));
|
||||
expect(result.canToggle).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,28 +1,4 @@
|
||||
import type { SidebarStateBucket } from "@/hooks/sidebar-workspaces-view-model";
|
||||
import type { ActiveWorkspaceSelection } from "@/stores/last-workspace-selection";
|
||||
|
||||
export interface SidebarGroupItem {
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
}
|
||||
|
||||
export interface SidebarGroupVisibilityInput<T> {
|
||||
items: readonly T[];
|
||||
expanded: boolean;
|
||||
policy: SidebarGroupVisibilityPolicy<T>;
|
||||
/** The workspace the group's rows highlight as selected. Null when no row can be selected. */
|
||||
selection: ActiveWorkspaceSelection | null;
|
||||
}
|
||||
|
||||
export interface SidebarGroupVisibility<T> {
|
||||
/**
|
||||
* The open workspace when the collapsed limit would hide it. Rendered before `visibleItems`,
|
||||
* out of group order, outside any drag list. Never also present in `visibleItems`.
|
||||
*/
|
||||
leadingItem: T | null;
|
||||
visibleItems: T[];
|
||||
canToggle: boolean;
|
||||
}
|
||||
|
||||
export type SidebarGroupVisibilityPolicy<T> =
|
||||
| { kind: "pinned" }
|
||||
@@ -40,45 +16,18 @@ export function createWorkspaceVisibilityPolicy<T extends { workspaceKey: string
|
||||
};
|
||||
}
|
||||
|
||||
function isOpenWorkspace(
|
||||
item: SidebarGroupItem,
|
||||
selection: ActiveWorkspaceSelection | null,
|
||||
): boolean {
|
||||
return (
|
||||
selection !== null &&
|
||||
item.serverId === selection.serverId &&
|
||||
item.workspaceId === selection.workspaceId
|
||||
);
|
||||
}
|
||||
|
||||
export function selectSidebarGroupVisibility<T extends SidebarGroupItem>(
|
||||
input: SidebarGroupVisibilityInput<T>,
|
||||
): SidebarGroupVisibility<T> {
|
||||
const { items, expanded, policy, selection } = input;
|
||||
export function selectSidebarGroupVisibility<T>(
|
||||
items: readonly T[],
|
||||
expanded: boolean,
|
||||
policy: SidebarGroupVisibilityPolicy<T>,
|
||||
) {
|
||||
const limit = policy.kind === "pinned" ? 20 : 7;
|
||||
const baseline: T[] = [];
|
||||
let leadingItem: T | null = null;
|
||||
let canToggle = false;
|
||||
|
||||
items.forEach((item, index) => {
|
||||
const inBaseline =
|
||||
index < limit || (policy.kind === "workspaces" && policy.getStatusBucket(item) !== "done");
|
||||
if (inBaseline) {
|
||||
baseline.push(item);
|
||||
} else if (leadingItem === null && isOpenWorkspace(item, selection)) {
|
||||
leadingItem = item;
|
||||
} else {
|
||||
canToggle = true;
|
||||
}
|
||||
});
|
||||
|
||||
if (expanded || !canToggle) {
|
||||
return { leadingItem: null, visibleItems: items.slice(), canToggle };
|
||||
}
|
||||
|
||||
const baseline = items.filter(
|
||||
(item, index) =>
|
||||
index < limit || (policy.kind === "workspaces" && policy.getStatusBucket(item) !== "done"),
|
||||
);
|
||||
return {
|
||||
leadingItem,
|
||||
visibleItems: baseline,
|
||||
canToggle,
|
||||
visibleItems: expanded ? items.slice() : baseline,
|
||||
canToggle: baseline.length < items.length,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -147,7 +147,6 @@ export function SidebarStatusWorkspaceList({
|
||||
dragGestureHostActive,
|
||||
}: StatusWorkspaceListProps) {
|
||||
const { t } = useTranslation();
|
||||
const activeWorkspaceSelection = useActiveWorkspaceSelection();
|
||||
const collapsedWorkspaceGroupKeys = useSidebarCollapsedSectionsStore(
|
||||
(state) => state.collapsedWorkspaceGroupKeys,
|
||||
);
|
||||
@@ -156,27 +155,23 @@ export function SidebarStatusWorkspaceList({
|
||||
(state) => state.togglePinnedCollapsed,
|
||||
);
|
||||
const {
|
||||
leadingItem: leadingPinnedWorkspace,
|
||||
visibleItems: visiblePinnedWorkspaces,
|
||||
expanded: pinnedWorkspacesExpanded,
|
||||
canToggle: canTogglePinnedWorkspaces,
|
||||
toggleExpanded: togglePinnedWorkspacesExpanded,
|
||||
} = useLimitedSidebarGroup({ items: pinnedWorkspaces, selection: activeWorkspaceSelection });
|
||||
} = useLimitedSidebarGroup(pinnedWorkspaces);
|
||||
|
||||
const statusShortcutIndex = showShortcutBadges
|
||||
? shortcutIndexByWorkspaceKey
|
||||
: EMPTY_SHORTCUT_INDEX;
|
||||
const renderPinnedWorkspaceRow = useCallback(
|
||||
(
|
||||
workspace: SidebarWorkspaceEntry,
|
||||
input?: {
|
||||
drag?: () => void;
|
||||
isDragging?: boolean;
|
||||
dragHandleProps?: DraggableListDragHandleProps;
|
||||
},
|
||||
) => (
|
||||
const renderPinnedWorkspace = useCallback(
|
||||
({
|
||||
item: workspace,
|
||||
drag,
|
||||
isActive,
|
||||
dragHandleProps,
|
||||
}: DraggableRenderItemInfo<SidebarWorkspaceEntry>) => (
|
||||
<StatusWorkspaceRow
|
||||
key={workspace.workspaceKey}
|
||||
workspace={workspace}
|
||||
{...buildStatusRowProjectPresentation({
|
||||
workspace,
|
||||
@@ -189,9 +184,9 @@ export function SidebarStatusWorkspaceList({
|
||||
canPin={supportsPinningByServerId.get(workspace.serverId) === true}
|
||||
onToggleWorkspacePin={onToggleWorkspacePin}
|
||||
onWorkspacePress={onWorkspacePress}
|
||||
drag={input?.drag}
|
||||
isDragging={input?.isDragging}
|
||||
dragHandleProps={input?.dragHandleProps}
|
||||
drag={drag}
|
||||
isDragging={isActive}
|
||||
dragHandleProps={dragHandleProps}
|
||||
/>
|
||||
),
|
||||
[
|
||||
@@ -204,20 +199,6 @@ export function SidebarStatusWorkspaceList({
|
||||
supportsPinningByServerId,
|
||||
],
|
||||
);
|
||||
const renderPinnedWorkspace = useCallback(
|
||||
({
|
||||
item: workspace,
|
||||
drag,
|
||||
isActive,
|
||||
dragHandleProps,
|
||||
}: DraggableRenderItemInfo<SidebarWorkspaceEntry>) =>
|
||||
renderPinnedWorkspaceRow(workspace, {
|
||||
drag,
|
||||
isDragging: isActive,
|
||||
dragHandleProps,
|
||||
}),
|
||||
[renderPinnedWorkspaceRow],
|
||||
);
|
||||
const content = (
|
||||
<>
|
||||
{pinnedWorkspaces.length > 0 ? (
|
||||
@@ -230,7 +211,6 @@ export function SidebarStatusWorkspaceList({
|
||||
/>
|
||||
{pinnedCollapsed ? null : (
|
||||
<>
|
||||
{leadingPinnedWorkspace ? renderPinnedWorkspaceRow(leadingPinnedWorkspace) : null}
|
||||
<DraggableList
|
||||
testID="sidebar-pinned-list"
|
||||
data={visiblePinnedWorkspaces}
|
||||
@@ -365,37 +345,12 @@ function StatusGroupRows({
|
||||
supportsPinningByServerId: ReadonlyMap<string, boolean>;
|
||||
onToggleWorkspacePin: ToggleSidebarWorkspacePin;
|
||||
}) {
|
||||
const activeWorkspaceSelection = useActiveWorkspaceSelection();
|
||||
const {
|
||||
leadingItem: leadingWorkspace,
|
||||
visibleItems: visibleWorkspaces,
|
||||
expanded: workspacesExpanded,
|
||||
canToggle: canToggleWorkspaces,
|
||||
toggleExpanded: toggleWorkspacesExpanded,
|
||||
} = useLimitedSidebarGroup({
|
||||
items: group.rows,
|
||||
selection: activeWorkspaceSelection,
|
||||
policy: STATUS_GROUP_VISIBILITY,
|
||||
});
|
||||
|
||||
function renderWorkspaceRow(workspace: SidebarWorkspaceEntry) {
|
||||
return (
|
||||
<StatusWorkspaceRow
|
||||
key={workspace.workspaceKey}
|
||||
workspace={workspace}
|
||||
{...buildStatusRowProjectPresentation({
|
||||
workspace,
|
||||
projectIconByProjectViewKey,
|
||||
hostBadgeByServerId,
|
||||
})}
|
||||
shortcutNumber={shortcutIndex.get(workspace.workspaceKey) ?? null}
|
||||
showShortcutBadge={showShortcutBadges}
|
||||
canPin={supportsPinningByServerId.get(workspace.serverId) === true}
|
||||
onToggleWorkspacePin={onToggleWorkspacePin}
|
||||
onWorkspacePress={onWorkspacePress}
|
||||
/>
|
||||
);
|
||||
}
|
||||
} = useLimitedSidebarGroup(group.rows, STATUS_GROUP_VISIBILITY);
|
||||
|
||||
return (
|
||||
<View style={collapsed ? undefined : styles.statusGroupBlockExpanded}>
|
||||
@@ -405,8 +360,22 @@ function StatusGroupRows({
|
||||
style={styles.statusWorkspaceListContainer}
|
||||
testID={`sidebar-status-group-rows-${group.key}`}
|
||||
>
|
||||
{leadingWorkspace ? renderWorkspaceRow(leadingWorkspace) : null}
|
||||
{visibleWorkspaces.map(renderWorkspaceRow)}
|
||||
{visibleWorkspaces.map((workspace) => (
|
||||
<StatusWorkspaceRow
|
||||
key={workspace.workspaceKey}
|
||||
workspace={workspace}
|
||||
{...buildStatusRowProjectPresentation({
|
||||
workspace,
|
||||
projectIconByProjectViewKey,
|
||||
hostBadgeByServerId,
|
||||
})}
|
||||
shortcutNumber={shortcutIndex.get(workspace.workspaceKey) ?? null}
|
||||
showShortcutBadge={showShortcutBadges}
|
||||
canPin={supportsPinningByServerId.get(workspace.serverId) === true}
|
||||
onToggleWorkspacePin={onToggleWorkspacePin}
|
||||
onWorkspacePress={onWorkspacePress}
|
||||
/>
|
||||
))}
|
||||
{canToggleWorkspaces ? (
|
||||
<SidebarGroupToggleRow
|
||||
expanded={workspacesExpanded}
|
||||
|
||||
@@ -1,32 +1,19 @@
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import {
|
||||
selectSidebarGroupVisibility,
|
||||
type SidebarGroupItem,
|
||||
type SidebarGroupVisibility,
|
||||
type SidebarGroupVisibilityPolicy,
|
||||
} from "./sidebar-group-visibility";
|
||||
import type { ActiveWorkspaceSelection } from "@/stores/last-workspace-selection";
|
||||
|
||||
const PINNED_POLICY = { kind: "pinned" } as const;
|
||||
|
||||
interface LimitedSidebarGroupInput<T> {
|
||||
items: readonly T[];
|
||||
selection: ActiveWorkspaceSelection | null;
|
||||
policy?: SidebarGroupVisibilityPolicy<T>;
|
||||
}
|
||||
|
||||
export function useLimitedSidebarGroup<T extends SidebarGroupItem>({
|
||||
items,
|
||||
selection,
|
||||
policy = PINNED_POLICY,
|
||||
}: LimitedSidebarGroupInput<T>): SidebarGroupVisibility<T> & {
|
||||
expanded: boolean;
|
||||
toggleExpanded: () => void;
|
||||
} {
|
||||
export function useLimitedSidebarGroup<T>(
|
||||
items: readonly T[],
|
||||
policy: SidebarGroupVisibilityPolicy<T> = PINNED_POLICY,
|
||||
) {
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const visibility = useMemo(
|
||||
() => selectSidebarGroupVisibility({ items, expanded, policy, selection }),
|
||||
[expanded, items, policy, selection],
|
||||
() => selectSidebarGroupVisibility(items, expanded, policy),
|
||||
[expanded, items, policy],
|
||||
);
|
||||
const toggleExpanded = useCallback(() => setExpanded((current) => !current), []);
|
||||
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import Svg, { Path } from "react-native-svg";
|
||||
import { useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
Keyboard,
|
||||
type LayoutChangeEvent,
|
||||
PanResponder,
|
||||
type PanResponderGestureState,
|
||||
Pressable,
|
||||
StyleSheet,
|
||||
Text,
|
||||
View,
|
||||
type GestureResponderEvent,
|
||||
type StyleProp,
|
||||
type ViewStyle,
|
||||
} from "react-native";
|
||||
@@ -46,10 +47,13 @@ import {
|
||||
type TerminalSelectionViewport,
|
||||
} from "../terminal/native-renderer/terminal-selection";
|
||||
import {
|
||||
createTerminalSelectionController,
|
||||
terminalSelectionHandles,
|
||||
TERMINAL_SELECTION_GRIP_SIZE,
|
||||
} from "../terminal/native-renderer/terminal-selection-controller";
|
||||
TERMINAL_GESTURE_LONG_PRESS_MS,
|
||||
TERMINAL_GESTURE_TAP_TOLERANCE_PX,
|
||||
advanceTerminalScrollGesture,
|
||||
classifyTerminalGestureIntent,
|
||||
resolveTerminalGestureReleaseAction,
|
||||
type TerminalGestureIntent,
|
||||
} from "../terminal/native-renderer/terminal-selection-gesture";
|
||||
import { resolveNativeTerminalMountAction } from "../terminal/native-renderer/terminal-mount-policy";
|
||||
import {
|
||||
forwardNativeTerminalKey,
|
||||
@@ -83,6 +87,38 @@ const DEFAULT_XTERM_THEME: ITheme = {
|
||||
foreground: "#e6e6e6",
|
||||
cursor: "#e6e6e6",
|
||||
};
|
||||
interface NativeTerminalPanState {
|
||||
lastDy: number;
|
||||
rowRemainder: number;
|
||||
didScroll: boolean;
|
||||
didNavigate: boolean;
|
||||
movedBeyondTapTolerance: boolean;
|
||||
intent: TerminalGestureIntent | null;
|
||||
}
|
||||
|
||||
interface NativeTerminalSelectionPress {
|
||||
startX: number;
|
||||
startY: number;
|
||||
startedAt: number;
|
||||
startedWithSelection: boolean;
|
||||
status: "pressing" | "selecting";
|
||||
}
|
||||
|
||||
function resolvePanResponderPoint(
|
||||
press: NativeTerminalSelectionPress,
|
||||
event: GestureResponderEvent,
|
||||
gesture: PanResponderGestureState,
|
||||
): { x: number; y: number } {
|
||||
const eventDx = event.nativeEvent.locationX - press.startX;
|
||||
const eventDy = event.nativeEvent.locationY - press.startY;
|
||||
const dx = Math.abs(eventDx) > Math.abs(gesture.dx) ? eventDx : gesture.dx;
|
||||
const dy = Math.abs(eventDy) > Math.abs(gesture.dy) ? eventDy : gesture.dy;
|
||||
return {
|
||||
x: press.startX + dx,
|
||||
y: press.startY + dy,
|
||||
};
|
||||
}
|
||||
|
||||
function initialNativeTerminalSize(): TerminalMeasuredSize {
|
||||
return { rows: MIN_NATIVE_TERMINAL_ROWS, cols: MIN_NATIVE_TERMINAL_COLS };
|
||||
}
|
||||
@@ -127,14 +163,19 @@ function NativeTerminalEmulator({
|
||||
const outputDrainRef = useRef<NativeTerminalOutputDrain | null>(null);
|
||||
const screenModelRef = useRef<TerminalScreenModel | null>(null);
|
||||
const selectionModelRef = useRef<TerminalSelectionModel>(createTerminalSelectionModel());
|
||||
const selectionControllerRef = useRef<ReturnType<
|
||||
typeof createTerminalSelectionController
|
||||
> | null>(null);
|
||||
const gestureStartRef = useRef({ x: 0, y: 0 });
|
||||
const [cellMetrics, setCellMetrics] = useState<TerminalGridCellMetrics | null>(null);
|
||||
const selectionLongPressTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const selectionPressRef = useRef<NativeTerminalSelectionPress | null>(null);
|
||||
const latestResolvedScreenRef = useRef<TerminalScreenState | null>(null);
|
||||
const paintFrameRef = useRef<number | null>(null);
|
||||
const outputDecoderRef = useRef(new TextDecoder());
|
||||
const panStateRef = useRef<NativeTerminalPanState>({
|
||||
lastDy: 0,
|
||||
rowRemainder: 0,
|
||||
didScroll: false,
|
||||
didNavigate: false,
|
||||
movedBeyondTapTolerance: false,
|
||||
intent: null,
|
||||
});
|
||||
const inputModeTrackerRef = useRef(new TerminalInputModeTracker());
|
||||
const lastInputModeStateRef = useRef<TerminalInputModeState>({
|
||||
...inputModeTrackerRef.current.getState(),
|
||||
@@ -204,7 +245,6 @@ function NativeTerminalEmulator({
|
||||
}, []);
|
||||
|
||||
const clearSelection = useCallback(() => {
|
||||
selectionControllerRef.current?.cancel();
|
||||
const snapshot = selectionModelRef.current.clear();
|
||||
commitSelectionRange(snapshot.range);
|
||||
}, [commitSelectionRange]);
|
||||
@@ -215,14 +255,20 @@ function NativeTerminalEmulator({
|
||||
|
||||
const syncSelectionWithTerminal = useCallback(
|
||||
(terminal: NativeHeadlessTerminal) => {
|
||||
const previous = selectionModelRef.current.getSnapshot().range;
|
||||
const snapshot = selectionModelRef.current.sync({ bounds: terminal.getBufferBounds() });
|
||||
if (previous && !snapshot.range) selectionControllerRef.current?.cancel();
|
||||
commitSelectionRange(snapshot.range);
|
||||
},
|
||||
[commitSelectionRange],
|
||||
);
|
||||
|
||||
const clearSelectionLongPressTimeout = useCallback(() => {
|
||||
if (selectionLongPressTimeoutRef.current === null) {
|
||||
return;
|
||||
}
|
||||
clearTimeout(selectionLongPressTimeoutRef.current);
|
||||
selectionLongPressTimeoutRef.current = null;
|
||||
}, []);
|
||||
|
||||
const resolveVisibleRows = useCallback((terminal: NativeHeadlessTerminal): number => {
|
||||
return (
|
||||
resolveMeasuredNativeTerminalSize({
|
||||
@@ -477,7 +523,8 @@ function NativeTerminalEmulator({
|
||||
emitMeasuredSize({ source: "measure" });
|
||||
return () => {
|
||||
callbacksRef.current.onRendererReadyChange?.({ streamKey, isReady: false });
|
||||
selectionControllerRef.current?.cancel();
|
||||
clearSelectionLongPressTimeout();
|
||||
selectionPressRef.current = null;
|
||||
if (paintFrameRef.current !== null) {
|
||||
cancelAnimationFrame(paintFrameRef.current);
|
||||
paintFrameRef.current = null;
|
||||
@@ -487,7 +534,7 @@ function NativeTerminalEmulator({
|
||||
terminalRef.current?.dispose();
|
||||
terminalRef.current = null;
|
||||
};
|
||||
}, [emitMeasuredSize, resetTerminal, streamKey]);
|
||||
}, [clearSelectionLongPressTimeout, emitMeasuredSize, resetTerminal, streamKey]);
|
||||
|
||||
useEffect(() => {
|
||||
if (focusRequestToken <= 0) return;
|
||||
@@ -544,7 +591,6 @@ function NativeTerminalEmulator({
|
||||
const handleCellMetricsChange = useCallback(
|
||||
(metrics: TerminalGridCellMetrics) => {
|
||||
metricsRef.current = metrics;
|
||||
setCellMetrics(metrics);
|
||||
emitMeasuredSize({ source: "measure" });
|
||||
},
|
||||
[emitMeasuredSize],
|
||||
@@ -617,6 +663,14 @@ function NativeTerminalEmulator({
|
||||
if (!coordinate) {
|
||||
return;
|
||||
}
|
||||
const existingPress = selectionPressRef.current;
|
||||
selectionPressRef.current = {
|
||||
startX: point.x,
|
||||
startY: point.y,
|
||||
startedAt: existingPress?.startedAt ?? Date.now(),
|
||||
startedWithSelection: existingPress?.startedWithSelection ?? false,
|
||||
status: "selecting",
|
||||
};
|
||||
const bounds = terminal.getBufferBounds();
|
||||
const wordSelection = resolveTerminalWordSelection({ terminal, coordinate });
|
||||
let snapshot = selectionModelRef.current.begin({
|
||||
@@ -631,61 +685,222 @@ function NativeTerminalEmulator({
|
||||
[commitSelectionRange, resolveSelectionCoordinate],
|
||||
);
|
||||
|
||||
const selectionController = useMemo(
|
||||
() =>
|
||||
createTerminalSelectionController({
|
||||
getGeometry: () => {
|
||||
const viewport = resolveSelectionViewport();
|
||||
const metrics = metricsRef.current;
|
||||
return viewport && metrics
|
||||
? { range: selectionRangeRef.current, viewport, metrics }
|
||||
: null;
|
||||
},
|
||||
onBeginHandle: (endpoint, cols) =>
|
||||
selectionModelRef.current.beginEndpointDrag(endpoint, cols),
|
||||
onMoveHandle: (coordinate) => {
|
||||
const terminal = terminalRef.current;
|
||||
if (!terminal) return;
|
||||
commitSelectionRange(
|
||||
selectionModelRef.current.update({ coordinate, bounds: terminal.getBufferBounds() })
|
||||
.range,
|
||||
);
|
||||
},
|
||||
onLongPress: beginSelectionAtPoint,
|
||||
onTap: focusTerminalFromTap,
|
||||
onScroll: applyScroll,
|
||||
schedule: (callback, delay) => setTimeout(callback, delay) as unknown as number,
|
||||
cancel: (timer) => clearTimeout(timer),
|
||||
}),
|
||||
[
|
||||
applyScroll,
|
||||
beginSelectionAtPoint,
|
||||
commitSelectionRange,
|
||||
focusTerminalFromTap,
|
||||
resolveSelectionViewport,
|
||||
],
|
||||
const updateSelectionAtPoint = useCallback(
|
||||
(point: { x: number; y: number }) => {
|
||||
const terminal = terminalRef.current;
|
||||
if (!terminal || selectionPressRef.current?.status !== "selecting") {
|
||||
return;
|
||||
}
|
||||
const coordinate = resolveSelectionCoordinate(point);
|
||||
if (!coordinate) {
|
||||
return;
|
||||
}
|
||||
const snapshot = selectionModelRef.current.update({
|
||||
coordinate,
|
||||
bounds: terminal.getBufferBounds(),
|
||||
});
|
||||
commitSelectionRange(snapshot.range);
|
||||
},
|
||||
[commitSelectionRange, resolveSelectionCoordinate],
|
||||
);
|
||||
|
||||
const handlePanResponderScroll = useCallback(
|
||||
(currentDy: number) => {
|
||||
const cellHeight = metricsRef.current?.cellHeight;
|
||||
if (!cellHeight || cellHeight <= 0) {
|
||||
return;
|
||||
}
|
||||
const panState = panStateRef.current;
|
||||
const update = advanceTerminalScrollGesture({
|
||||
state: panState,
|
||||
currentDy,
|
||||
cellHeight,
|
||||
});
|
||||
panState.lastDy = update.state.lastDy;
|
||||
panState.rowRemainder = update.state.rowRemainder;
|
||||
panState.didScroll = update.state.didScroll;
|
||||
const { rowDelta } = update;
|
||||
if (rowDelta === 0) {
|
||||
return;
|
||||
}
|
||||
if (rowDelta > 0) {
|
||||
applyScroll("up", rowDelta);
|
||||
return;
|
||||
}
|
||||
applyScroll("down", Math.abs(rowDelta));
|
||||
},
|
||||
[applyScroll],
|
||||
);
|
||||
selectionControllerRef.current = selectionController;
|
||||
|
||||
const panResponder = useMemo(
|
||||
() =>
|
||||
PanResponder.create({
|
||||
onStartShouldSetPanResponder: () => true,
|
||||
onStartShouldSetPanResponderCapture: () => true,
|
||||
onMoveShouldSetPanResponder: (_event, gesture) => {
|
||||
const intent = classifyTerminalGestureIntent({
|
||||
status: selectionRangeRef.current ? "selecting" : "pressing",
|
||||
dx: gesture.dx,
|
||||
dy: gesture.dy,
|
||||
vx: gesture.vx,
|
||||
vy: gesture.vy,
|
||||
});
|
||||
return intent === "scroll" || intent === "select";
|
||||
},
|
||||
onMoveShouldSetPanResponderCapture: (_event, gesture) => {
|
||||
const intent = classifyTerminalGestureIntent({
|
||||
status: selectionRangeRef.current ? "selecting" : "pressing",
|
||||
dx: gesture.dx,
|
||||
dy: gesture.dy,
|
||||
vx: gesture.vx,
|
||||
vy: gesture.vy,
|
||||
});
|
||||
return intent === "scroll" || intent === "select";
|
||||
},
|
||||
onPanResponderGrant: (event) => {
|
||||
const point = { x: event.nativeEvent.locationX, y: event.nativeEvent.locationY };
|
||||
gestureStartRef.current = point;
|
||||
selectionController.press(point);
|
||||
panStateRef.current = {
|
||||
lastDy: 0,
|
||||
rowRemainder: 0,
|
||||
didScroll: false,
|
||||
didNavigate: false,
|
||||
movedBeyondTapTolerance: false,
|
||||
intent: null,
|
||||
};
|
||||
const point = {
|
||||
x: event.nativeEvent.locationX,
|
||||
y: event.nativeEvent.locationY,
|
||||
};
|
||||
const pressStatus = selectionRangeRef.current ? "selecting" : "pressing";
|
||||
selectionPressRef.current = {
|
||||
startX: point.x,
|
||||
startY: point.y,
|
||||
startedAt: Date.now(),
|
||||
startedWithSelection: pressStatus === "selecting",
|
||||
status: pressStatus,
|
||||
};
|
||||
clearSelectionLongPressTimeout();
|
||||
if (pressStatus === "selecting") {
|
||||
return;
|
||||
}
|
||||
selectionLongPressTimeoutRef.current = setTimeout(() => {
|
||||
selectionLongPressTimeoutRef.current = null;
|
||||
const press = selectionPressRef.current;
|
||||
if (press?.status !== "pressing") {
|
||||
return;
|
||||
}
|
||||
beginSelectionAtPoint({ x: press.startX, y: press.startY });
|
||||
}, TERMINAL_GESTURE_LONG_PRESS_MS);
|
||||
},
|
||||
onPanResponderMove: (event, gesture) => {
|
||||
const selectionPress = selectionPressRef.current;
|
||||
const panState = panStateRef.current;
|
||||
if (Math.hypot(gesture.dx, gesture.dy) > TERMINAL_GESTURE_TAP_TOLERANCE_PX) {
|
||||
panState.movedBeyondTapTolerance = true;
|
||||
}
|
||||
if (selectionPress?.status === "selecting") {
|
||||
if (panState.movedBeyondTapTolerance) {
|
||||
updateSelectionAtPoint(resolvePanResponderPoint(selectionPress, event, gesture));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (panState.intent === "scroll") {
|
||||
handlePanResponderScroll(gesture.dy);
|
||||
return;
|
||||
}
|
||||
if (panState.didNavigate) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (selectionPress?.status === "pressing") {
|
||||
const point = resolvePanResponderPoint(selectionPress, event, gesture);
|
||||
const dx = point.x - selectionPress.startX;
|
||||
const dy = point.y - selectionPress.startY;
|
||||
const intent = classifyTerminalGestureIntent({
|
||||
status: "pressing",
|
||||
dx,
|
||||
dy,
|
||||
vx: gesture.vx,
|
||||
vy: gesture.vy,
|
||||
elapsedMs: Date.now() - selectionPress.startedAt,
|
||||
});
|
||||
if (intent === "tap" || intent === "pending") {
|
||||
return;
|
||||
}
|
||||
|
||||
clearSelectionLongPressTimeout();
|
||||
panState.intent = intent;
|
||||
|
||||
if (intent === "scroll") {
|
||||
selectionPressRef.current = null;
|
||||
handlePanResponderScroll(gesture.dy);
|
||||
return;
|
||||
}
|
||||
|
||||
if (intent === "select") {
|
||||
beginSelectionAtPoint({ x: selectionPress.startX, y: selectionPress.startY });
|
||||
updateSelectionAtPoint(point);
|
||||
return;
|
||||
}
|
||||
}
|
||||
},
|
||||
onPanResponderRelease: (event, gesture) => {
|
||||
clearSelectionLongPressTimeout();
|
||||
const selectionPress = selectionPressRef.current;
|
||||
if (
|
||||
selectionPress?.status === "selecting" &&
|
||||
panStateRef.current.movedBeyondTapTolerance
|
||||
) {
|
||||
updateSelectionAtPoint(resolvePanResponderPoint(selectionPress, event, gesture));
|
||||
}
|
||||
selectionPressRef.current = null;
|
||||
const { didScroll, didNavigate, movedBeyondTapTolerance } = panStateRef.current;
|
||||
panStateRef.current = {
|
||||
lastDy: 0,
|
||||
rowRemainder: 0,
|
||||
didScroll: false,
|
||||
didNavigate: false,
|
||||
movedBeyondTapTolerance: false,
|
||||
intent: null,
|
||||
};
|
||||
const releaseAction = resolveTerminalGestureReleaseAction({
|
||||
status: selectionPress?.status ?? "idle",
|
||||
startedWithSelection: selectionPress?.startedWithSelection,
|
||||
didScroll,
|
||||
didNavigate,
|
||||
movedBeyondTapTolerance,
|
||||
pressDurationMs: selectionPress ? Date.now() - selectionPress.startedAt : 0,
|
||||
longPressMs: TERMINAL_GESTURE_LONG_PRESS_MS,
|
||||
scrollMode: terminalScreenRef.current?.scroll.mode ?? "following",
|
||||
});
|
||||
if (releaseAction === "select" && selectionPress) {
|
||||
beginSelectionAtPoint({ x: selectionPress.startX, y: selectionPress.startY });
|
||||
return;
|
||||
}
|
||||
if (releaseAction === "focus" || releaseAction === "clear") {
|
||||
focusTerminalFromTap();
|
||||
}
|
||||
},
|
||||
onPanResponderTerminate: () => {
|
||||
clearSelectionLongPressTimeout();
|
||||
selectionPressRef.current = null;
|
||||
panStateRef.current = {
|
||||
lastDy: 0,
|
||||
rowRemainder: 0,
|
||||
didScroll: false,
|
||||
didNavigate: false,
|
||||
movedBeyondTapTolerance: false,
|
||||
intent: null,
|
||||
};
|
||||
},
|
||||
onPanResponderMove: (_event, gesture) =>
|
||||
selectionController.move({
|
||||
x: gestureStartRef.current.x + gesture.dx,
|
||||
y: gestureStartRef.current.y + gesture.dy,
|
||||
}),
|
||||
onPanResponderRelease: () => selectionController.release(),
|
||||
onPanResponderTerminate: () => selectionController.cancel(),
|
||||
}),
|
||||
[selectionController],
|
||||
[
|
||||
beginSelectionAtPoint,
|
||||
clearSelectionLongPressTimeout,
|
||||
focusTerminalFromTap,
|
||||
handlePanResponderScroll,
|
||||
updateSelectionAtPoint,
|
||||
],
|
||||
);
|
||||
|
||||
const backgroundColor = xtermTheme.background ?? "#0b0b0b";
|
||||
@@ -696,11 +911,6 @@ function NativeTerminalEmulator({
|
||||
|
||||
const terminalState = terminalScreen?.viewport ?? null;
|
||||
const isScrolled = terminalScreen?.scroll.mode === "scrolled";
|
||||
const viewport = resolveSelectionViewport();
|
||||
const handles =
|
||||
viewport && cellMetrics
|
||||
? terminalSelectionHandles({ range: selectionRange, viewport, metrics: cellMetrics })
|
||||
: [];
|
||||
const terminalGrid = terminalState ? (
|
||||
<TerminalGridView
|
||||
state={terminalState}
|
||||
@@ -717,41 +927,6 @@ function NativeTerminalEmulator({
|
||||
<View onLayout={handleLayout} style={rootStyle} testID={testId}>
|
||||
<View {...panResponder.panHandlers} accessible={false} style={styles.nativeSurface}>
|
||||
{terminalGrid}
|
||||
<View pointerEvents="none" style={StyleSheet.absoluteFill}>
|
||||
{handles.map((handle) => (
|
||||
<View key={handle.endpoint}>
|
||||
<View
|
||||
style={[
|
||||
styles.selectionStem,
|
||||
{
|
||||
left: Math.max(
|
||||
0,
|
||||
Math.min(handle.x - 1, viewport!.cols * cellMetrics!.cellWidth - 2),
|
||||
),
|
||||
top: handle.stemTop,
|
||||
height: handle.stemHeight,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
<Svg
|
||||
width={TERMINAL_SELECTION_GRIP_SIZE}
|
||||
height={TERMINAL_SELECTION_GRIP_SIZE}
|
||||
viewBox="0 0 18 18"
|
||||
style={[styles.selectionGrip, { left: handle.gripX - 9, top: handle.gripY - 9 }]}
|
||||
>
|
||||
<Path
|
||||
fill="#2684ff"
|
||||
d={
|
||||
handle.gripDirection === "left"
|
||||
? "M18 0H9C4 0 0 4 0 9S4 18 9 18 18 14 18 9Z"
|
||||
: "M0 0H9C14 0 18 4 18 9S14 18 9 18 0 14 0 9Z"
|
||||
}
|
||||
transform={handle.gripAbove ? "translate(0 18) scale(1 -1)" : undefined}
|
||||
/>
|
||||
</Svg>
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
<TerminalInput
|
||||
ref={inputRef}
|
||||
isKeyboardVisible={isKeyboardVisible}
|
||||
@@ -794,8 +969,6 @@ const styles = StyleSheet.create({
|
||||
nativeGrid: {
|
||||
flex: 1,
|
||||
},
|
||||
selectionGrip: { position: "absolute" },
|
||||
selectionStem: { position: "absolute", width: 2, backgroundColor: "#2684ff" },
|
||||
followButton: {
|
||||
position: "absolute",
|
||||
right: 12,
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import React, { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { useDraftStore } from "@/stores/draft-store";
|
||||
import type { AttachmentMetadata, ComposerAttachment } from "@/attachments/types";
|
||||
import { createWorkspaceFileAttachment } from "@/attachments/workspace-file";
|
||||
@@ -126,13 +126,17 @@ afterEach(async () => {
|
||||
});
|
||||
});
|
||||
|
||||
let useAgentInputDraft: typeof import("./input-draft").useAgentInputDraft;
|
||||
type DraftRecordForTest = ReturnType<typeof useDraftStore.getState>["drafts"][string];
|
||||
|
||||
Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", {
|
||||
value: true,
|
||||
configurable: true,
|
||||
beforeAll(async () => {
|
||||
Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", {
|
||||
value: true,
|
||||
configurable: true,
|
||||
});
|
||||
|
||||
({ useAgentInputDraft } = await import("./input-draft"));
|
||||
});
|
||||
const { useAgentInputDraft } = await import("./input-draft");
|
||||
|
||||
describe("useAgentInputDraft live contract", () => {
|
||||
beforeEach(() => {
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import type { UserComposerAttachment } from "@/attachments/types";
|
||||
import type { TextReplacement } from "@/composer/types";
|
||||
import type { DraftAgentControlsProps } from "@/composer/agent-controls";
|
||||
import type { DraftCommandTarget } from "@/agent-commands";
|
||||
import type { DraftCommandTarget } from "@/hooks/use-agent-commands-query";
|
||||
import {
|
||||
useAgentFormState,
|
||||
type CreateAgentInitialValues,
|
||||
|
||||
@@ -2,31 +2,6 @@ import { describe, expect, it } from "vitest";
|
||||
import { ComposerEditingSession, ComposerEditingSessions } from "./index";
|
||||
|
||||
describe("composer editing session", () => {
|
||||
it("appends commands to the current editor buffer and focuses it", () => {
|
||||
const session = new ComposerEditingSession();
|
||||
let text = "draft typed since publication";
|
||||
let focuses = 0;
|
||||
let selection = { start: 0, end: 0 };
|
||||
const detach = session.attachEditor({
|
||||
getText: () => text,
|
||||
replaceText: (next, nextSelection) => {
|
||||
text = next;
|
||||
selection = nextSelection;
|
||||
},
|
||||
focus: () => {
|
||||
focuses += 1;
|
||||
},
|
||||
});
|
||||
session.insertCommand("/review");
|
||||
expect(selection).toEqual({ start: text.length, end: text.length });
|
||||
session.insertCommand("/test");
|
||||
expect(text).toBe("draft typed since publication /review /test ");
|
||||
expect(focuses).toBe(2);
|
||||
expect(selection).toEqual({ start: text.length, end: text.length });
|
||||
detach();
|
||||
session.insertCommand("/ignored");
|
||||
expect(text).toBe("draft typed since publication /review /test ");
|
||||
});
|
||||
it("publishes fullscreen changes once per transition", () => {
|
||||
const session = new ComposerEditingSession();
|
||||
const changes: boolean[] = [];
|
||||
|
||||
@@ -30,29 +30,10 @@ export interface ComposerRetainedEditor {
|
||||
*/
|
||||
export class ComposerEditingSession {
|
||||
private fullscreen = false;
|
||||
private editor: {
|
||||
getText(): string;
|
||||
replaceText(text: string, selection: ComposerSelection): void;
|
||||
focus(): void;
|
||||
} | null = null;
|
||||
private retained: ComposerRetainedEditor | null = null;
|
||||
private listeners = new Set<() => void>();
|
||||
constructor(private readonly onChange?: () => void) {}
|
||||
getFullscreen = () => this.fullscreen;
|
||||
attachEditor(editor: NonNullable<ComposerEditingSession["editor"]>) {
|
||||
this.editor = editor;
|
||||
return () => {
|
||||
if (this.editor === editor) this.editor = null;
|
||||
};
|
||||
}
|
||||
insertCommand(command: string) {
|
||||
const editor = this.editor;
|
||||
if (!editor) return;
|
||||
const text = editor.getText();
|
||||
const nextText = `${text}${text && !/\s$/.test(text) ? " " : ""}${command} `;
|
||||
editor.replaceText(nextText, { start: nextText.length, end: nextText.length });
|
||||
editor.focus();
|
||||
}
|
||||
/** Called by the unmounting editor; the next mount of this session takes it. */
|
||||
retainEditor(retained: ComposerRetainedEditor) {
|
||||
this.retained = retained;
|
||||
|
||||
@@ -71,7 +71,7 @@ import {
|
||||
} from "./input/input";
|
||||
import type { ImageAttachment, MessagePayload, TextReplacement } from "./types";
|
||||
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||
import type { DraftCommandTarget } from "@/agent-commands";
|
||||
import type { DraftCommandTarget } from "@/hooks/use-agent-commands-query";
|
||||
import { encodeImages } from "@/utils/encode-images";
|
||||
import { focusWithRetries } from "@/utils/web-focus";
|
||||
import {
|
||||
|
||||
@@ -562,6 +562,7 @@ function MessageInputOverlay({
|
||||
isDictationProcessing,
|
||||
dictationStatus,
|
||||
dictationError,
|
||||
dictationEmptyReason,
|
||||
onCancelRecording,
|
||||
onAcceptRecording,
|
||||
onAcceptAndSendRecording,
|
||||
@@ -585,6 +586,7 @@ function MessageInputOverlay({
|
||||
isDictationProcessing: boolean;
|
||||
dictationStatus: React.ComponentProps<typeof DictationOverlay>["status"];
|
||||
dictationError: string | null;
|
||||
dictationEmptyReason: React.ComponentProps<typeof DictationOverlay>["emptyReason"];
|
||||
onCancelRecording: () => Promise<void>;
|
||||
onAcceptRecording: () => Promise<void>;
|
||||
onAcceptAndSendRecording: () => Promise<void>;
|
||||
@@ -593,6 +595,7 @@ function MessageInputOverlay({
|
||||
onRealtimeVoiceStop: () => void;
|
||||
}) {
|
||||
if (showDictationOverlay) {
|
||||
const awaitsAcknowledgement = dictationStatus === "failed" || dictationStatus === "empty";
|
||||
return (
|
||||
<DictationOverlay
|
||||
volume={dictationVolume}
|
||||
@@ -601,11 +604,12 @@ function MessageInputOverlay({
|
||||
isProcessing={isDictationProcessing}
|
||||
status={dictationStatus}
|
||||
errorText={dictationStatus === "failed" ? (dictationError ?? undefined) : undefined}
|
||||
emptyReason={dictationEmptyReason}
|
||||
onCancel={onCancelRecording}
|
||||
onAccept={onAcceptRecording}
|
||||
onAcceptAndSend={onAcceptAndSendRecording}
|
||||
onRetry={dictationStatus === "failed" ? onRetryFailedRecording : undefined}
|
||||
onDiscard={dictationStatus === "failed" ? onDiscardFailedRecording : undefined}
|
||||
onRetry={awaitsAcknowledgement ? onRetryFailedRecording : undefined}
|
||||
onDiscard={awaitsAcknowledgement ? onDiscardFailedRecording : undefined}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1032,7 +1036,12 @@ function computeShouldShowDictationOverlay(
|
||||
isDictationProcessing: boolean,
|
||||
dictationStatus: string,
|
||||
): boolean {
|
||||
return isDictating || isDictationProcessing || dictationStatus === "failed";
|
||||
return (
|
||||
isDictating ||
|
||||
isDictationProcessing ||
|
||||
dictationStatus === "failed" ||
|
||||
dictationStatus === "empty"
|
||||
);
|
||||
}
|
||||
|
||||
function computeIsDictationStartEnabled(
|
||||
@@ -1407,16 +1416,6 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
|
||||
[onChangeText, updateComposerHeightForText, updateLiveTextPresence],
|
||||
);
|
||||
|
||||
useLayoutEffect(
|
||||
() =>
|
||||
editingSession.attachEditor({
|
||||
getText: () => textInputRef.current?.getText() ?? valueRef.current,
|
||||
replaceText,
|
||||
focus: () => textInputRef.current?.focus(),
|
||||
}),
|
||||
[editingSession, replaceText],
|
||||
);
|
||||
|
||||
useImperativeHandle(ref, () => ({
|
||||
focus: () => {
|
||||
textInputRef.current?.focus();
|
||||
@@ -1543,6 +1542,7 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
|
||||
duration: dictationDuration,
|
||||
error: dictationError,
|
||||
status: dictationStatus,
|
||||
emptyReason: dictationEmptyReason,
|
||||
startDictation,
|
||||
cancelDictation,
|
||||
confirmDictation,
|
||||
@@ -2190,6 +2190,7 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
|
||||
isDictationProcessing={isDictationProcessing}
|
||||
dictationStatus={dictationStatus}
|
||||
dictationError={dictationError}
|
||||
dictationEmptyReason={dictationEmptyReason}
|
||||
onCancelRecording={handleCancelRecording}
|
||||
onAcceptRecording={handleAcceptRecording}
|
||||
onAcceptAndSendRecording={handleAcceptAndSendRecording}
|
||||
@@ -2211,6 +2212,7 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
|
||||
isDictationProcessing,
|
||||
dictationStatus,
|
||||
dictationError,
|
||||
dictationEmptyReason,
|
||||
handleCancelRecording,
|
||||
handleAcceptRecording,
|
||||
handleAcceptAndSendRecording,
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
} from "./provider-snapshot-cache";
|
||||
import { queryClient as singletonQueryClient } from "./query-client";
|
||||
import { replaceProviderSnapshotIcons } from "@/data/provider-icons";
|
||||
import { agentCommandsQueryRoot } from "@/agent-commands/cache";
|
||||
import { agentCommandsQueryRoot } from "@/hooks/agent-commands-query";
|
||||
import type { AgentProvider } from "@getpaseo/protocol/agent-types";
|
||||
import { normalizeWorkspacePath } from "@/utils/workspace-identity";
|
||||
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
import type { OwnedSubscription } from "@getpaseo/client";
|
||||
import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types";
|
||||
import type { Query, QueryCacheNotifyEvent, QueryClient, QueryKey } from "@tanstack/react-query";
|
||||
import type {
|
||||
ListTerminalsResponse,
|
||||
MutableDaemonConfig,
|
||||
SessionOutboundMessage,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
import { invalidateCommandsForProviderChange } from "@/agent-commands/cache";
|
||||
import { agentCommandsQueryRoot } from "@/hooks/agent-commands-query";
|
||||
import { shareCheckoutDiff } from "@/git/diff-sharing";
|
||||
import { orderCheckoutDiffFiles } from "@/git/diff-order";
|
||||
import { daemonConfigQueryKey } from "@/data/daemon-config";
|
||||
@@ -187,10 +186,10 @@ export async function applyProvidersSnapshotUpdate(input: {
|
||||
const snapshot = { ...input.message.payload, requestId: "providers_snapshot_update" };
|
||||
const cwd = normalizeProvidersSnapshotCwd(snapshot.cwd);
|
||||
const queryKey = providersSnapshotQueryKey(input.serverId, cwd);
|
||||
const previous = input.queryClient.getQueryData<{ entries: ProviderSnapshotEntry[] }>(queryKey);
|
||||
const previous = input.queryClient.getQueryData<{ snapshotHash?: string }>(queryKey);
|
||||
let announcement: typeof snapshot | undefined = snapshot;
|
||||
void input.queryClient.cancelQueries({ queryKey, exact: true });
|
||||
const current = await input.queryClient.fetchQuery({
|
||||
await input.queryClient.fetchQuery({
|
||||
queryKey,
|
||||
staleTime: 0,
|
||||
structuralSharing: false,
|
||||
@@ -206,13 +205,12 @@ export async function applyProvidersSnapshotUpdate(input: {
|
||||
});
|
||||
},
|
||||
});
|
||||
void invalidateCommandsForProviderChange({
|
||||
queryClient: input.queryClient,
|
||||
serverId: input.serverId,
|
||||
cwd,
|
||||
previous: previous?.entries,
|
||||
current: current.entries,
|
||||
});
|
||||
if (!snapshot.snapshotHash || previous?.snapshotHash !== snapshot.snapshotHash) {
|
||||
void input.queryClient.invalidateQueries({
|
||||
queryKey: agentCommandsQueryRoot(input.serverId),
|
||||
exact: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export function mountServerDataPushRouter(input: PushRouterInput): () => void {
|
||||
|
||||
@@ -27,7 +27,7 @@ type ReplicaQueryInput<TQueryFnData, TError, TData, TQueryKey extends QueryKey>
|
||||
|
||||
type FetchQueryInput<TQueryFnData, TError, TData, TQueryKey extends QueryKey> = Omit<
|
||||
UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
|
||||
"initialData" | "placeholderData" | "queryFn" | "staleTime"
|
||||
"initialData" | "placeholderData" | "queryFn" | "refetchOnMount" | "staleTime"
|
||||
> & {
|
||||
dataShape: "list" | "value";
|
||||
queryFn: QueryFnOption<TQueryFnData, TError, TData, TQueryKey>;
|
||||
@@ -113,7 +113,7 @@ export function fetchQueryOptions<
|
||||
dataShape,
|
||||
},
|
||||
},
|
||||
refetchOnMount: options.refetchOnMount ?? (immutableWhen ? true : "always"),
|
||||
refetchOnMount: immutableWhen ? true : "always",
|
||||
staleTime: immutableWhen
|
||||
? (query) =>
|
||||
query.state.data !== undefined && immutableWhen(query.state.data) ? Infinity : 0
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { completeDictation, type DictationRecording } from "./result";
|
||||
|
||||
class RecordedAudio implements DictationRecording {
|
||||
constructor(private segments: string[]) {}
|
||||
getSegmentCount() {
|
||||
return this.segments.length;
|
||||
}
|
||||
clearAll() {
|
||||
this.segments = [];
|
||||
}
|
||||
}
|
||||
|
||||
describe("completing dictation", () => {
|
||||
it("keeps a recording through repeated empty results until a retry returns text", () => {
|
||||
const recording = new RecordedAudio(["first PCM chunk", "second PCM chunk"]);
|
||||
const empty = { finalText: " ", partialText: "", recording };
|
||||
const result = completeDictation(empty);
|
||||
expect(recording.getSegmentCount()).toBe(2);
|
||||
expect(result).toEqual({ status: "empty", reason: "no-transcript" });
|
||||
expect(completeDictation(empty)).toEqual({ status: "empty", reason: "no-transcript" });
|
||||
expect(recording.getSegmentCount()).toBe(2);
|
||||
expect(completeDictation({ ...empty, finalText: " recovered " })).toEqual({
|
||||
status: "transcribed",
|
||||
text: "recovered",
|
||||
});
|
||||
expect(recording.getSegmentCount()).toBe(0);
|
||||
});
|
||||
|
||||
it("keeps usable partial text when the final response is empty", () => {
|
||||
const recording = new RecordedAudio(["PCM chunk"]);
|
||||
expect(
|
||||
completeDictation({ finalText: "", partialText: " recognized words ", recording }),
|
||||
).toEqual({
|
||||
status: "transcribed",
|
||||
text: "recognized words",
|
||||
});
|
||||
expect(recording.getSegmentCount()).toBe(0);
|
||||
});
|
||||
|
||||
it("reports a missing recording without inventing a reason for the empty result", () => {
|
||||
expect(
|
||||
completeDictation({ finalText: "", partialText: "", recording: new RecordedAudio([]) }),
|
||||
).toEqual({
|
||||
status: "empty",
|
||||
reason: "no-audio",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
export type DictationEmptyReason = "no-audio" | "no-transcript";
|
||||
|
||||
export interface DictationRecording {
|
||||
getSegmentCount(): number;
|
||||
clearAll(): void;
|
||||
}
|
||||
|
||||
export type DictationResult =
|
||||
| { status: "empty"; reason: DictationEmptyReason }
|
||||
| { status: "transcribed"; text: string };
|
||||
|
||||
export function completeDictation(input: {
|
||||
finalText: string;
|
||||
partialText: string;
|
||||
recording: DictationRecording;
|
||||
}): DictationResult {
|
||||
const text = input.finalText.trim() || input.partialText.trim();
|
||||
if (!text) {
|
||||
return {
|
||||
status: "empty",
|
||||
reason: input.recording.getSegmentCount() === 0 ? "no-audio" : "no-transcript",
|
||||
};
|
||||
}
|
||||
input.recording.clearAll();
|
||||
return { status: "transcribed", text };
|
||||
}
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
resolveWorkingDiffComparison,
|
||||
selectWorkingDiffComparison,
|
||||
} from "@/git/working-diff-comparison";
|
||||
import { draftAgentCommandsQueryKey } from "@/agent-commands/cache";
|
||||
import { draftAgentCommandsQueryKey } from "@/hooks/agent-commands-query";
|
||||
import {
|
||||
applyCheckoutStatusUpdateFromEvent,
|
||||
ensureCheckoutStatus,
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
invalidatePrPaneTimelineForCheckout,
|
||||
} from "@/git/query-keys";
|
||||
import { type CheckoutPrStatusPayload, normalizeCheckoutPrStatusPayload } from "@/git/pr-status";
|
||||
import { resetDraftAgentCommandsForCheckout } from "@/agent-commands/cache";
|
||||
import { resetDraftAgentCommandsForCheckout } from "@/hooks/agent-commands-query";
|
||||
|
||||
export type CheckoutStatusPayload = CheckoutStatusResponse["payload"];
|
||||
export type { CheckoutPrStatusPayload } from "@/git/pr-status";
|
||||
|
||||
+1
-51
@@ -1,61 +1,11 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { QueryClient, QueryObserver } from "@tanstack/react-query";
|
||||
import { fetchQueryOptions } from "@/data/query";
|
||||
import {
|
||||
agentCommandsQueryKey,
|
||||
agentCommandsQueryRoot,
|
||||
draftAgentCommandsQueryKey,
|
||||
normalizeAgentCommandsCwd,
|
||||
sessionAgentCommandsQueryKey,
|
||||
sessionCommandQueryPolicy,
|
||||
} from "./cache";
|
||||
|
||||
it("reuses fresh commands and keeps stale commands during a shared refresh and failure", async () => {
|
||||
const client = new QueryClient({ defaultOptions: { queries: { gcTime: 300_000 } } });
|
||||
const key = sessionAgentCommandsQueryKey({ serverId: "s", agentId: "a" });
|
||||
let calls = 0;
|
||||
let fail = false;
|
||||
let resolveRefresh: (value: string[]) => void = () => {};
|
||||
const refresh = new Promise<string[]>((resolve) => {
|
||||
resolveRefresh = resolve;
|
||||
});
|
||||
const options = fetchQueryOptions({
|
||||
...sessionCommandQueryPolicy,
|
||||
staleTimeMs: sessionCommandQueryPolicy.staleTime,
|
||||
dataShape: "value",
|
||||
queryKey: key,
|
||||
retry: false,
|
||||
queryFn: async () => {
|
||||
calls++;
|
||||
if (fail) throw new Error("offline");
|
||||
return refresh;
|
||||
},
|
||||
});
|
||||
client.setQueryData(key, ["old"]);
|
||||
const fresh = new QueryObserver(client, options);
|
||||
const unsubscribeFresh = fresh.subscribe(() => {});
|
||||
expect(calls).toBe(0);
|
||||
unsubscribeFresh();
|
||||
client.setQueryData(key, ["old"], { updatedAt: 1 });
|
||||
const first = new QueryObserver(client, options);
|
||||
const second = new QueryObserver(client, options);
|
||||
const unsubscribeFirst = first.subscribe(() => {});
|
||||
const unsubscribeSecond = second.subscribe(() => {});
|
||||
expect(calls).toBe(1);
|
||||
expect(first.getCurrentResult().data).toEqual(["old"]);
|
||||
expect(client.getQueryCache().find({ queryKey: key })?.gcTime).toBe(1_800_000);
|
||||
resolveRefresh(["new"]);
|
||||
await refresh;
|
||||
await first.refetch({ cancelRefetch: false });
|
||||
expect(second.getCurrentResult().data).toEqual(["new"]);
|
||||
fail = true;
|
||||
await client.invalidateQueries({ queryKey: key });
|
||||
expect(first.getCurrentResult().data).toEqual(["new"]);
|
||||
expect(first.getCurrentResult().isError).toBe(true);
|
||||
unsubscribeFirst();
|
||||
unsubscribeSecond();
|
||||
client.clear();
|
||||
});
|
||||
} from "./agent-commands-query";
|
||||
|
||||
describe("agent command query keys", () => {
|
||||
it("shares draft commands across draft tabs with the same provider setup", () => {
|
||||
-48
@@ -1,16 +1,8 @@
|
||||
import type { QueryClient } from "@tanstack/react-query";
|
||||
import type { AgentProvider } from "@getpaseo/protocol/agent-types";
|
||||
import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types";
|
||||
import equal from "fast-deep-equal";
|
||||
import { normalizeWorkspacePath } from "@/utils/workspace-identity";
|
||||
|
||||
export const AGENT_COMMANDS_QUERY_ROOT = "agentCommands";
|
||||
export const sessionCommandQueryPolicy = {
|
||||
staleTime: 600_000,
|
||||
gcTime: 1_800_000,
|
||||
refetchOnMount: true,
|
||||
refetchOnWindowFocus: false,
|
||||
} as const;
|
||||
|
||||
export interface AgentCommandsDraftConfig {
|
||||
provider: AgentProvider;
|
||||
@@ -29,46 +21,6 @@ export function agentCommandsQueryRoot(serverId: string) {
|
||||
return [AGENT_COMMANDS_QUERY_ROOT, serverId] as const;
|
||||
}
|
||||
|
||||
/** Snapshot announcements contain provider metadata, not command catalogs. Ignore initial
|
||||
* discovery and unrelated providers; explicit refresh still invalidates every catalog. */
|
||||
export function invalidateCommandsForProviderChange(input: {
|
||||
queryClient: QueryClient;
|
||||
serverId: string;
|
||||
cwd: string | null;
|
||||
previous: readonly ProviderSnapshotEntry[] | undefined;
|
||||
current: readonly ProviderSnapshotEntry[];
|
||||
}): Promise<void> {
|
||||
const previous = new Map((input.previous ?? []).map((entry) => [entry.provider, entry]));
|
||||
const current = new Map(input.current.map((entry) => [entry.provider, entry]));
|
||||
const relevant = (entry: ProviderSnapshotEntry | undefined) =>
|
||||
entry && {
|
||||
status: entry.status,
|
||||
enabled: entry.enabled,
|
||||
source: entry.source,
|
||||
models: entry.models,
|
||||
modes: entry.modes,
|
||||
defaultModeId: entry.defaultModeId,
|
||||
};
|
||||
return input.queryClient.invalidateQueries({
|
||||
queryKey: agentCommandsQueryRoot(input.serverId),
|
||||
predicate: (query) => {
|
||||
const isDraft = query.queryKey[2] === "draft";
|
||||
const provider =
|
||||
query.meta?.agentCommandProvider ?? (isDraft ? query.queryKey[6] : undefined);
|
||||
const cwd = query.meta?.agentCommandCwd ?? (isDraft ? query.queryKey[4] : undefined);
|
||||
if (input.cwd && typeof cwd === "string" && normalizeAgentCommandsCwd(cwd) !== input.cwd)
|
||||
return false;
|
||||
if (typeof provider !== "string") return false;
|
||||
const before = previous.get(provider);
|
||||
const after = current.get(provider);
|
||||
if (!before) return after?.status === "ready" && query.state.status === "error";
|
||||
if (before.status !== "ready")
|
||||
return after?.status === "ready" && query.state.status === "error";
|
||||
return !equal(relevant(before), relevant(after));
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function sessionAgentCommandsQueryKey(input: { serverId: string; agentId: string }) {
|
||||
return [...agentCommandsQueryRoot(input.serverId), "session", input.agentId] as const;
|
||||
}
|
||||
@@ -4,11 +4,11 @@ import type { TFunction } from "i18next";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { AutocompleteOption } from "@/components/ui/autocomplete";
|
||||
import {
|
||||
useAutocompleteCommands,
|
||||
useAgentCommandsQuery,
|
||||
type AgentSlashCommand,
|
||||
type DraftCommandConfig,
|
||||
type DraftCommandTarget,
|
||||
} from "@/agent-commands";
|
||||
} from "./use-agent-commands-query";
|
||||
import { orderAutocompleteOptions } from "@/components/ui/autocomplete-utils";
|
||||
import { useAutocomplete } from "./use-autocomplete";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
@@ -432,7 +432,7 @@ export function useAgentAutocomplete(input: UseAgentAutocompleteInput): AgentAut
|
||||
autocompleteCwd,
|
||||
});
|
||||
|
||||
const commandsQuery = useAutocompleteCommands({
|
||||
const commandsQuery = useAgentCommandsQuery({
|
||||
serverId,
|
||||
agentId,
|
||||
enabled: mode === "command" && canLoadCommands && canListCommands,
|
||||
|
||||
+5
-7
@@ -1,5 +1,9 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { type AgentCommandsClient, type DraftCommandConfig, fetchAgentCommands } from "./use-query";
|
||||
import {
|
||||
type AgentCommandsClient,
|
||||
type DraftCommandConfig,
|
||||
fetchAgentCommands,
|
||||
} from "./use-agent-commands-query";
|
||||
|
||||
type ListCommands = AgentCommandsClient["listCommands"];
|
||||
type ListCommandsResult = Awaited<ReturnType<ListCommands>>;
|
||||
@@ -34,12 +38,6 @@ function commandsPayload(commands: ListCommandsResult["commands"]): ListCommands
|
||||
}
|
||||
|
||||
describe("fetchAgentCommands", () => {
|
||||
it("rejects a discovery error so a previous catalog is retained", async () => {
|
||||
const client = createClient({ ...commandsPayload([]), error: "provider unavailable" });
|
||||
await expect(fetchAgentCommands({ client, agentId: "agent-1" })).rejects.toThrow(
|
||||
"provider unavailable",
|
||||
);
|
||||
});
|
||||
it("loads commands for a draft composer without an agent id", async () => {
|
||||
const client = createClient(
|
||||
commandsPayload([{ name: "compact", description: "Compact context", argumentHint: "" }]),
|
||||
+8
-28
@@ -1,15 +1,12 @@
|
||||
import { useFetchQuery } from "@/data/query";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import { useRetainedPanelActive } from "@/components/retained-panel";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { useShallow } from "zustand/shallow";
|
||||
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
|
||||
import {
|
||||
agentCommandsQueryKey,
|
||||
sessionCommandQueryPolicy,
|
||||
type AgentCommandsDraftConfig,
|
||||
} from "./cache";
|
||||
import { agentCommandsQueryKey, type AgentCommandsDraftConfig } from "@/hooks/agent-commands-query";
|
||||
|
||||
const DRAFT_COMMANDS_STALE_TIME = Number.POSITIVE_INFINITY;
|
||||
const SESSION_COMMANDS_STALE_TIME = 60_000;
|
||||
|
||||
export interface AgentSlashCommand {
|
||||
name: string;
|
||||
@@ -44,7 +41,6 @@ export async function fetchAgentCommands(input: {
|
||||
agentId: input.agentId,
|
||||
draftConfig: input.draftConfig,
|
||||
});
|
||||
if (response.error) throw new Error(response.error);
|
||||
return response.commands as AgentSlashCommand[];
|
||||
}
|
||||
|
||||
@@ -66,16 +62,8 @@ export function useAgentCommandsQuery({
|
||||
const queryEnabled = enabled && retainedPanelActive;
|
||||
const client = useHostRuntimeClient(serverId);
|
||||
const isConnected = useHostRuntimeIsConnected(serverId);
|
||||
const { provider, cwd } = useSessionStore(
|
||||
useShallow((state) => {
|
||||
const agent =
|
||||
state.sessions[serverId]?.agents?.get(agentId) ??
|
||||
state.sessions[serverId]?.agentDetails?.get(agentId);
|
||||
return { provider: agent?.provider, cwd: agent?.cwd };
|
||||
}),
|
||||
);
|
||||
|
||||
const query = useFetchQuery({
|
||||
const query = useQuery({
|
||||
queryKey: agentCommandsQueryKey({ serverId, agentId, draftConfig }),
|
||||
queryFn: async () => {
|
||||
if (!client) {
|
||||
@@ -84,15 +72,7 @@ export function useAgentCommandsQuery({
|
||||
return fetchAgentCommands({ client, agentId, draftConfig });
|
||||
},
|
||||
enabled: queryEnabled && !!client && isConnected && (!!agentId || !!draftConfig),
|
||||
dataShape: "value",
|
||||
meta: {
|
||||
agentCommandProvider: draftConfig?.provider ?? provider,
|
||||
agentCommandCwd: draftConfig?.cwd ?? cwd,
|
||||
},
|
||||
...(draftConfig
|
||||
? { immutableWhen: () => true as const }
|
||||
: { ...sessionCommandQueryPolicy, staleTimeMs: sessionCommandQueryPolicy.staleTime }),
|
||||
subscribed: queryEnabled,
|
||||
staleTime: draftConfig ? DRAFT_COMMANDS_STALE_TIME : SESSION_COMMANDS_STALE_TIME,
|
||||
retry: 3,
|
||||
retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 5000),
|
||||
});
|
||||
@@ -104,7 +84,7 @@ export function useAgentCommandsQuery({
|
||||
return {
|
||||
commands: query.data ?? [],
|
||||
isLoading,
|
||||
isError: query.isError && query.data === undefined,
|
||||
isError: query.isError,
|
||||
error: query.error,
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { beforeAll, describe, expect, it } from "vitest";
|
||||
import type {
|
||||
DaemonClient,
|
||||
FetchAgentHistoryEntry,
|
||||
@@ -13,8 +13,18 @@ import { allAgentHistoryQueryKey } from "./agent-history-query-key";
|
||||
}
|
||||
).__DEV__ = false;
|
||||
|
||||
const { fetchAgentHistoryBatch, fetchAgentHistoryPage, collectAgentHistoryHostErrors } =
|
||||
await import("./use-agent-history");
|
||||
type UseAgentHistoryModule = typeof import("./use-agent-history");
|
||||
|
||||
let fetchAgentHistoryBatch: UseAgentHistoryModule["fetchAgentHistoryBatch"];
|
||||
let fetchAgentHistoryPage: UseAgentHistoryModule["fetchAgentHistoryPage"];
|
||||
let collectAgentHistoryHostErrors: UseAgentHistoryModule["collectAgentHistoryHostErrors"];
|
||||
|
||||
beforeAll(async () => {
|
||||
const module = await import("./use-agent-history");
|
||||
fetchAgentHistoryBatch = module.fetchAgentHistoryBatch;
|
||||
fetchAgentHistoryPage = module.fetchAgentHistoryPage;
|
||||
collectAgentHistoryHostErrors = module.collectAgentHistoryHostErrors;
|
||||
});
|
||||
|
||||
type FetchAgentHistory = DaemonClient["fetchAgentHistory"];
|
||||
type FetchAgentHistoryResult = Awaited<ReturnType<FetchAgentHistory>>;
|
||||
|
||||
@@ -1,6 +1,14 @@
|
||||
import type { DictationEmptyReason } from "@/dictation/result";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
|
||||
export type DictationStatus = "idle" | "recording" | "paused" | "uploading" | "failed";
|
||||
export type DictationStatus =
|
||||
| "idle"
|
||||
| "recording"
|
||||
| "paused"
|
||||
| "uploading"
|
||||
| "failed"
|
||||
// Finished without text; captured audio remains available for retry.
|
||||
| "empty";
|
||||
|
||||
export interface UseDictationOptions {
|
||||
client: import("@getpaseo/client/internal/daemon-client").DaemonClient | null;
|
||||
@@ -22,6 +30,7 @@ export interface UseDictationResult {
|
||||
duration: number;
|
||||
error: string | null;
|
||||
status: DictationStatus;
|
||||
emptyReason: DictationEmptyReason | null;
|
||||
startDictation: () => Promise<void>;
|
||||
cancelDictation: () => Promise<void>;
|
||||
confirmDictation: () => Promise<void>;
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { DictationStreamSender } from "@/dictation/dictation-stream-sender";
|
||||
import { completeDictation, type DictationEmptyReason } from "@/dictation/result";
|
||||
import { useDictationAudioSource } from "@/hooks/use-dictation-audio-source";
|
||||
import { generateMessageId } from "@/types/stream";
|
||||
import { AttemptGuard } from "@/utils/attempt-guard";
|
||||
@@ -33,6 +34,7 @@ export function useDictation(options: UseDictationOptions): UseDictationResult {
|
||||
const [duration, setDuration] = useState(0);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [status, setStatus] = useState<DictationStatus>("idle");
|
||||
const [emptyReason, setEmptyReason] = useState<DictationEmptyReason | null>(null);
|
||||
const latestPartialTranscriptRef = useRef("");
|
||||
|
||||
const onTranscriptRef = useRef(onTranscript);
|
||||
@@ -131,12 +133,17 @@ export function useDictation(options: UseDictationOptions): UseDictationResult {
|
||||
[setError],
|
||||
);
|
||||
|
||||
const clearStreamingState = useCallback(() => {
|
||||
senderRef.current?.clearAll();
|
||||
const clearTranscriptState = useCallback(() => {
|
||||
latestPartialTranscriptRef.current = "";
|
||||
setPartialTranscript("");
|
||||
setEmptyReason(null);
|
||||
}, []);
|
||||
|
||||
const clearStreamingState = useCallback(() => {
|
||||
senderRef.current?.clearAll();
|
||||
clearTranscriptState();
|
||||
}, [clearTranscriptState]);
|
||||
|
||||
const startNewStream = useCallback(async (reason: string) => {
|
||||
await senderRef.current?.restartStream(reason);
|
||||
}, []);
|
||||
@@ -192,16 +199,20 @@ export function useDictation(options: UseDictationOptions): UseDictationResult {
|
||||
setDuration(0);
|
||||
setStatus("idle");
|
||||
|
||||
const transcriptText =
|
||||
text.trim().length > 0 ? text.trim() : latestPartialTranscriptRef.current.trim();
|
||||
clearStreamingState();
|
||||
|
||||
if (!transcriptText) {
|
||||
const result = completeDictation({
|
||||
finalText: text,
|
||||
partialText: latestPartialTranscriptRef.current,
|
||||
recording: senderRef.current!,
|
||||
});
|
||||
if (result.status === "empty") {
|
||||
setStatus("empty");
|
||||
setEmptyReason(result.reason);
|
||||
return;
|
||||
}
|
||||
onTranscriptRef.current?.(transcriptText, { requestId });
|
||||
clearTranscriptState();
|
||||
onTranscriptRef.current?.(result.text, { requestId });
|
||||
},
|
||||
[clearStreamingState],
|
||||
[clearTranscriptState],
|
||||
);
|
||||
|
||||
const handleDictationFailure = useCallback(
|
||||
@@ -395,6 +406,7 @@ export function useDictation(options: UseDictationOptions): UseDictationResult {
|
||||
return;
|
||||
}
|
||||
setError(null);
|
||||
setEmptyReason(null);
|
||||
setStatus("uploading");
|
||||
setIsProcessing(true);
|
||||
isProcessingRef.current = true;
|
||||
@@ -462,6 +474,7 @@ export function useDictation(options: UseDictationOptions): UseDictationResult {
|
||||
duration,
|
||||
error,
|
||||
status: status === "recording" && audio.isPaused ? "paused" : status,
|
||||
emptyReason,
|
||||
startDictation,
|
||||
cancelDictation,
|
||||
confirmDictation,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { QueryClient, QueryObserver } from "@tanstack/react-query";
|
||||
import { QueryClient } from "@tanstack/react-query";
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
expandProviderSnapshot,
|
||||
} from "@getpaseo/protocol/provider-snapshot-codec";
|
||||
import type { CachedProviderSnapshot, ProviderSnapshotCache } from "@/data/provider-snapshot-cache";
|
||||
import { draftAgentCommandsQueryKey, sessionAgentCommandsQueryKey } from "@/agent-commands/cache";
|
||||
import { draftAgentCommandsQueryKey } from "@/hooks/agent-commands-query";
|
||||
import { providerSnapshotIcons } from "@/data/provider-icons";
|
||||
import { applyProvidersSnapshotUpdate, type ProvidersSnapshotUpdate } from "@/data/push-router";
|
||||
import {
|
||||
@@ -363,153 +363,6 @@ describe("applyProvidersSnapshotUpdate", () => {
|
||||
};
|
||||
}
|
||||
|
||||
it("refreshes active commands only when their provider changes after discovery", async () => {
|
||||
const key = sessionAgentCommandsQueryKey({ serverId, agentId: "agent-1" });
|
||||
let requests = 0;
|
||||
const observer = new QueryObserver(queryClient, {
|
||||
queryKey: key,
|
||||
queryFn: async () => {
|
||||
requests++;
|
||||
return [{ name: "review" }];
|
||||
},
|
||||
staleTime: Infinity,
|
||||
meta: { agentCommandProvider: "codex", agentCommandCwd: "/repo-a" },
|
||||
});
|
||||
const unsubscribe = observer.subscribe(() => {});
|
||||
await observer.refetch({ cancelRefetch: false });
|
||||
expect(requests).toBe(1);
|
||||
const codex = codexEntry("ready", [readyCodexModel]);
|
||||
const other = { provider: "claude", status: "loading", enabled: true } as ProviderSnapshotEntry;
|
||||
await applyProvidersSnapshotUpdate({
|
||||
client: createClient(),
|
||||
serverId,
|
||||
queryClient,
|
||||
message: updateMessage([codexEntry("loading"), other], "/repo-a"),
|
||||
});
|
||||
expect(requests).toBe(1);
|
||||
await applyProvidersSnapshotUpdate({
|
||||
client: createClient(),
|
||||
serverId,
|
||||
queryClient,
|
||||
message: updateMessage([codex, other], "/repo-a"),
|
||||
});
|
||||
expect(requests).toBe(1);
|
||||
await applyProvidersSnapshotUpdate({
|
||||
client: createClient(),
|
||||
serverId,
|
||||
queryClient,
|
||||
message: updateMessage([codex, { ...other, status: "ready" }], "/repo-a"),
|
||||
});
|
||||
expect(requests).toBe(1);
|
||||
await applyProvidersSnapshotUpdate({
|
||||
client: createClient(),
|
||||
serverId,
|
||||
queryClient,
|
||||
message: updateMessage(
|
||||
[
|
||||
{ ...codex, fetchedAt: "2026-01-01T00:00:02.000Z" },
|
||||
{ ...other, status: "ready" },
|
||||
],
|
||||
"/repo-a",
|
||||
),
|
||||
});
|
||||
expect(requests).toBe(1);
|
||||
queryClient.setQueryData(
|
||||
providersSnapshotQueryKey(serverId, "/repo-b"),
|
||||
providersSnapshot([codex]),
|
||||
);
|
||||
await applyProvidersSnapshotUpdate({
|
||||
client: createClient(),
|
||||
serverId,
|
||||
queryClient,
|
||||
message: updateMessage(
|
||||
[codexEntry("ready", [{ ...readyCodexModel, label: "Other checkout" }])],
|
||||
"/repo-b",
|
||||
),
|
||||
});
|
||||
expect(requests).toBe(1);
|
||||
await applyProvidersSnapshotUpdate({
|
||||
client: createClient(),
|
||||
serverId,
|
||||
queryClient,
|
||||
message: updateMessage(
|
||||
[
|
||||
codexEntry("ready", [{ ...readyCodexModel, label: "Updated" }]),
|
||||
{ ...other, status: "ready" },
|
||||
],
|
||||
"/repo-a",
|
||||
),
|
||||
});
|
||||
await observer.refetch({ cancelRefetch: false });
|
||||
expect(requests).toBe(2);
|
||||
unsubscribe();
|
||||
queryClient.clear();
|
||||
});
|
||||
|
||||
it("retries a failed command discovery when its provider first becomes ready", async () => {
|
||||
const key = sessionAgentCommandsQueryKey({ serverId, agentId: "agent-1" });
|
||||
let ready = false;
|
||||
let requests = 0;
|
||||
const observer = new QueryObserver(queryClient, {
|
||||
queryKey: key,
|
||||
queryFn: async () => {
|
||||
requests++;
|
||||
if (!ready) throw new Error("provider unavailable");
|
||||
return [{ name: "review" }];
|
||||
},
|
||||
retry: false,
|
||||
meta: { agentCommandProvider: "codex", agentCommandCwd: "/repo-a" },
|
||||
});
|
||||
const unsubscribe = observer.subscribe(() => {});
|
||||
await observer.refetch({ cancelRefetch: false });
|
||||
expect(observer.getCurrentResult().isError).toBe(true);
|
||||
ready = true;
|
||||
await applyProvidersSnapshotUpdate({
|
||||
client: createClient(),
|
||||
serverId,
|
||||
queryClient,
|
||||
message: updateMessage([codexEntry("ready", [readyCodexModel])], "/repo-a"),
|
||||
});
|
||||
await observer.refetch({ cancelRefetch: false });
|
||||
expect(requests).toBe(2);
|
||||
expect(observer.getCurrentResult().data).toEqual([{ name: "review" }]);
|
||||
unsubscribe();
|
||||
queryClient.clear();
|
||||
});
|
||||
|
||||
it("refreshes again when its provider changes during an active refresh", async () => {
|
||||
const key = sessionAgentCommandsQueryKey({ serverId, agentId: "agent-1" });
|
||||
queryClient.setQueryData(key, [{ name: "old" }]);
|
||||
let requests = 0;
|
||||
const waiting = new Promise<{ name: string }[]>(() => {});
|
||||
const observer = new QueryObserver(queryClient, {
|
||||
queryKey: key,
|
||||
queryFn: async () => (++requests === 1 ? waiting : [{ name: "new" }]),
|
||||
staleTime: Infinity,
|
||||
meta: { agentCommandProvider: "codex", agentCommandCwd: "/repo-a" },
|
||||
});
|
||||
const unsubscribe = observer.subscribe(() => {});
|
||||
queryClient.setQueryData(
|
||||
providersSnapshotQueryKey(serverId, "/repo-a"),
|
||||
providersSnapshot([codexEntry("ready", [readyCodexModel])]),
|
||||
);
|
||||
const send = (label: string) =>
|
||||
applyProvidersSnapshotUpdate({
|
||||
client: createClient(),
|
||||
serverId,
|
||||
queryClient,
|
||||
message: updateMessage([codexEntry("ready", [{ ...readyCodexModel, label }])], "/repo-a"),
|
||||
});
|
||||
await send("First change");
|
||||
expect(requests).toBe(1);
|
||||
await send("Second change");
|
||||
expect(requests).toBe(2);
|
||||
await observer.refetch({ cancelRefetch: false });
|
||||
expect(observer.getCurrentResult().data).toEqual([{ name: "new" }]);
|
||||
unsubscribe();
|
||||
queryClient.clear();
|
||||
});
|
||||
|
||||
it("routes updates to the home query cache when the message carries no cwd", async () => {
|
||||
await applyProvidersSnapshotUpdate({
|
||||
client: createClient(),
|
||||
@@ -602,10 +455,6 @@ describe("applyProvidersSnapshotUpdate", () => {
|
||||
draftConfig: { provider: "codex", cwd: "/repo-a" },
|
||||
});
|
||||
queryClient.setQueryData(commandsKey, [{ name: "compact", description: "", argumentHint: "" }]);
|
||||
queryClient.setQueryData(
|
||||
providersSnapshotQueryKey(serverId, "/repo-a"),
|
||||
providersSnapshot([codexEntry("ready")]),
|
||||
);
|
||||
|
||||
await applyProvidersSnapshotUpdate({
|
||||
client: createClient(),
|
||||
|
||||
@@ -371,6 +371,10 @@ export const ar: TranslationResources = {
|
||||
insertAndSend: "أدخل النسخ وأرسل",
|
||||
failed: "فشل الإملاء:{{error}}",
|
||||
failedRetry: "فشل الإملاء. اضغط على إعادة المحاولة.",
|
||||
empty: {
|
||||
noAudio: "لم يُسجَّل أي صوت. هل يستخدم تطبيق آخر الميكروفون؟",
|
||||
noTranscript: "لم يتم إرجاع نص. اضغط على إعادة المحاولة.",
|
||||
},
|
||||
},
|
||||
question: {
|
||||
responseFailed: "تعذر إرسال ردك. حاول مرة أخرى.",
|
||||
|
||||
@@ -368,6 +368,10 @@ export const en = {
|
||||
insertAndSend: "Insert transcription and send",
|
||||
failed: "Dictation failed: {{error}}",
|
||||
failedRetry: "Dictation failed. Tap retry.",
|
||||
empty: {
|
||||
noAudio: "No audio was recorded. Is another app using the microphone?",
|
||||
noTranscript: "No transcription was returned. Tap retry to try again.",
|
||||
},
|
||||
},
|
||||
question: {
|
||||
responseFailed: "Could not send your response. Try again.",
|
||||
|
||||
@@ -376,6 +376,10 @@ export const es: TranslationResources = {
|
||||
insertAndSend: "Insertar transcripción y enviar",
|
||||
failed: "Fallo en el dictado:{{error}}",
|
||||
failedRetry: "El dictado falló. Toca reintentar.",
|
||||
empty: {
|
||||
noAudio: "No se grabó audio. ¿Otra app está usando el micrófono?",
|
||||
noTranscript: "No se devolvió ninguna transcripción. Toca reintentar.",
|
||||
},
|
||||
},
|
||||
question: {
|
||||
responseFailed: "No se pudo enviar tu respuesta. Inténtalo de nuevo.",
|
||||
|
||||
@@ -376,6 +376,10 @@ export const fr: TranslationResources = {
|
||||
insertAndSend: "Insérer la transcription et envoyer",
|
||||
failed: "Échec de la dictée : {{error}}",
|
||||
failedRetry: "La dictée a échoué. Appuyez sur Réessayer.",
|
||||
empty: {
|
||||
noAudio: "Aucun son n'a été enregistré. Une autre app utilise-t-elle le micro ?",
|
||||
noTranscript: "Aucune transcription reçue. Appuyez sur Réessayer.",
|
||||
},
|
||||
},
|
||||
question: {
|
||||
responseFailed: "Impossible d’envoyer votre réponse. Réessayez.",
|
||||
|
||||
@@ -376,6 +376,10 @@ export const ja: TranslationResources = {
|
||||
insertAndSend: "文字起こしを挿入して送信",
|
||||
failed: "音声入力に失敗しました: {{error}}",
|
||||
failedRetry: "音声入力に失敗しました。再試行をタップしてください。",
|
||||
empty: {
|
||||
noAudio: "音声が録音されませんでした。別のアプリがマイクを使用していませんか?",
|
||||
noTranscript: "文字起こしが返されませんでした。再試行をタップしてください。",
|
||||
},
|
||||
},
|
||||
question: {
|
||||
responseFailed: "回答を送信できませんでした。もう一度お試しください。",
|
||||
|
||||
@@ -372,6 +372,10 @@ export const ko: TranslationResources = {
|
||||
insertAndSend: "전사 삽입 후 보내기",
|
||||
failed: "받아쓰기 실패: {{error}}",
|
||||
failedRetry: "받아쓰기에 실패했습니다. 다시 시도하려면 누르세요.",
|
||||
empty: {
|
||||
noAudio: "녹음된 오디오가 없습니다. 다른 앱이 마이크를 사용 중인가요?",
|
||||
noTranscript: "전사 결과가 없습니다. 다시 시도하려면 누르세요.",
|
||||
},
|
||||
},
|
||||
question: {
|
||||
responseFailed: "응답을 보내지 못했습니다. 다시 시도해 주세요.",
|
||||
|
||||
@@ -375,6 +375,10 @@ export const ptBR: TranslationResources = {
|
||||
insertAndSend: "Inserir transcrição e enviar",
|
||||
failed: "Falha no ditado: {{error}}",
|
||||
failedRetry: "Falha no ditado. Toque para tentar novamente.",
|
||||
empty: {
|
||||
noAudio: "Nenhum áudio foi gravado. Outro app está usando o microfone?",
|
||||
noTranscript: "Nenhuma transcrição foi retornada. Toque para tentar novamente.",
|
||||
},
|
||||
},
|
||||
question: {
|
||||
responseFailed: "Não foi possível enviar sua resposta. Tente novamente.",
|
||||
|
||||
@@ -375,6 +375,10 @@ export const ru: TranslationResources = {
|
||||
insertAndSend: "Вставить транскрипцию и отправить",
|
||||
failed: "Диктовка не удалась: {{error}}",
|
||||
failedRetry: "Диктовка не удалась. Нажмите «Повторить».",
|
||||
empty: {
|
||||
noAudio: "Звук не записан. Возможно, микрофон занят другим приложением?",
|
||||
noTranscript: "Текст не получен. Нажмите «Повторить».",
|
||||
},
|
||||
},
|
||||
question: {
|
||||
responseFailed: "Не удалось отправить ответ. Попробуйте ещё раз.",
|
||||
|
||||
@@ -371,6 +371,10 @@ export const zhCN: TranslationResources = {
|
||||
insertAndSend: "插入转写并发送",
|
||||
failed: "听写失败:{{error}}",
|
||||
failedRetry: "听写失败。点按重试。",
|
||||
empty: {
|
||||
noAudio: "未录到音频。是否有其他应用正在使用麦克风?",
|
||||
noTranscript: "未返回转写文本。点按重试。",
|
||||
},
|
||||
},
|
||||
question: {
|
||||
responseFailed: "未能发送你的回复,请重试。",
|
||||
|
||||
@@ -28,7 +28,6 @@ import { FileDropZone } from "@/components/file-drop/file-drop-zone";
|
||||
import { useRetainedPanelActive } from "@/components/retained-panel";
|
||||
import { RetainedChatContent } from "./retained-chat-content";
|
||||
import { Composer } from "@/composer";
|
||||
import { AgentCommandsProvider } from "@/agent-commands";
|
||||
import {
|
||||
useComposerEditingSession,
|
||||
useComposerFullscreen,
|
||||
@@ -1256,7 +1255,7 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
|
||||
</ChatSurface>
|
||||
);
|
||||
|
||||
const content = (
|
||||
return (
|
||||
<RewindComposerRestoreProvider
|
||||
textSource={agentInputDraft.textSource}
|
||||
setText={agentInputDraft.replaceText}
|
||||
@@ -1275,40 +1274,8 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
|
||||
</View>
|
||||
</RewindComposerRestoreProvider>
|
||||
);
|
||||
return wrapAgentCommandProvider({
|
||||
enabled: showsComposer && hasActiveComposer,
|
||||
serverId,
|
||||
agentId,
|
||||
editingSession: composerEditingSession,
|
||||
children: content,
|
||||
});
|
||||
});
|
||||
|
||||
function wrapAgentCommandProvider({
|
||||
enabled,
|
||||
serverId,
|
||||
agentId,
|
||||
editingSession,
|
||||
children,
|
||||
}: {
|
||||
enabled: boolean;
|
||||
serverId: string;
|
||||
agentId: string;
|
||||
editingSession: ComposerEditingSession;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<AgentCommandsProvider
|
||||
serverId={serverId}
|
||||
agentId={agentId}
|
||||
editingSession={editingSession}
|
||||
enabled={enabled}
|
||||
>
|
||||
{children}
|
||||
</AgentCommandsProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function ChatSurface({
|
||||
children,
|
||||
disabled,
|
||||
|
||||
@@ -5,7 +5,7 @@ import type {
|
||||
ProviderSnapshotEntry,
|
||||
} from "@getpaseo/protocol/agent-types";
|
||||
import type { AgentProviderDefinition } from "@getpaseo/protocol/provider-manifest";
|
||||
import type { DraftCommandTarget } from "@/agent-commands";
|
||||
import type { DraftCommandTarget } from "@/hooks/use-agent-commands-query";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import { compareMatchScores, scoreTextFields } from "@getpaseo/protocol/search/text-match";
|
||||
import { filterSelectableModels } from "./model-catalog";
|
||||
|
||||
@@ -16,8 +16,7 @@ import {
|
||||
normalizeWorkspaceDescriptor,
|
||||
useSessionStore,
|
||||
} from "@/stores/session-store";
|
||||
import { normalizeAgentSnapshot, projectAgentSnapshot } from "@/utils/agent-snapshots";
|
||||
import { deriveProjectPlacementFromCwd } from "@/utils/project-placement";
|
||||
import { normalizeAgentSnapshot } from "@/utils/agent-snapshots";
|
||||
import { selectWorkspaceDirectoryServerIds } from "@/stores/session-store-hooks/selectors";
|
||||
import { useWorkspaceLabels } from "@/workspace-labels";
|
||||
import type { DirectoryReplicaMutation } from "@/runtime/replica-cache";
|
||||
@@ -42,15 +41,12 @@ class FakeDirectoryClient {
|
||||
supportsWorkspaceLabels = false;
|
||||
listWorkspaceLabelsCalls = 0;
|
||||
fetchAgentsCalls = 0;
|
||||
observeAgentsCalls = 0;
|
||||
lastAgentOptions: unknown;
|
||||
fetchWorkspacesCalls = 0;
|
||||
observeWorkspacesCalls = 0;
|
||||
lastWorkspaceOptions: unknown;
|
||||
listProjectsCalls = 0;
|
||||
lastProjectOptions: unknown;
|
||||
projectResult: ProjectListResult | null = null;
|
||||
readonly listSnapshots: Promise<unknown>[] = [];
|
||||
private pendingAgentFetch: Promise<AgentFetchResult> | null = null;
|
||||
private pendingWorkspaceFetch: Promise<WorkspaceFetchResult> | null = null;
|
||||
private pendingProjectFetch: Promise<ProjectListResult> | null = null;
|
||||
@@ -155,22 +151,15 @@ class FakeDirectoryClient {
|
||||
}
|
||||
|
||||
observeAgents(options: Parameters<DaemonClient["observeAgents"]>[0]) {
|
||||
this.observeAgentsCalls += 1;
|
||||
const subscription = subscriptionFixture(
|
||||
this.fetchAgents({ ...options, subscribe: {} }),
|
||||
(receive) => this.on("agent_update", receive),
|
||||
return subscriptionFixture(this.fetchAgents({ ...options, subscribe: {} }), (receive) =>
|
||||
this.on("agent_update", receive),
|
||||
);
|
||||
this.listSnapshots.push(subscription.ready);
|
||||
return subscription;
|
||||
}
|
||||
|
||||
observeWorkspaces(options: Parameters<DaemonClient["observeWorkspaces"]>[0]) {
|
||||
this.observeWorkspacesCalls += 1;
|
||||
const subscription = subscriptionFixture(this.fetchWorkspaces(options), (receive) =>
|
||||
return subscriptionFixture(this.fetchWorkspaces(options), (receive) =>
|
||||
this.on("workspace_update", receive),
|
||||
);
|
||||
this.listSnapshots.push(subscription.ready);
|
||||
return subscription;
|
||||
}
|
||||
|
||||
observeEvents(events: readonly SessionOutboundMessage["type"][]) {
|
||||
@@ -603,83 +592,6 @@ describe("DirectorySync session readiness", () => {
|
||||
directory.dispose();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["full", "before"],
|
||||
["full", "after"],
|
||||
["route", "before"],
|
||||
["route", "after"],
|
||||
] as const)(
|
||||
"restores live directory updates when %s demand returns %s refresh completion",
|
||||
async (demand, timing) => {
|
||||
const serverId = `released-directory-${demand}-${timing}`;
|
||||
const { client, directory } = createDirectory(serverId);
|
||||
const store = useSessionStore.getState();
|
||||
store.initializeSession(serverId, client as unknown as DaemonClient, 1);
|
||||
store.updateSessionServerInfo(serverId, {
|
||||
serverId,
|
||||
hostname: null,
|
||||
version: "test",
|
||||
features: { workspaceMultiplicity: true, projectList: true },
|
||||
});
|
||||
const source = {};
|
||||
function setDemand(demanded: boolean): void {
|
||||
if (demand === "full") directory.setDemand(source, demanded);
|
||||
else directory.setAgentRouteDemand(demanded ? ["agent-1"] : []);
|
||||
}
|
||||
const releaseProjects = client.holdProjectFetch();
|
||||
const projects: ProjectListResult = { requestId: "projects", projects: [] };
|
||||
|
||||
try {
|
||||
setDemand(true);
|
||||
const refresh = directory.refreshDemand();
|
||||
await expect
|
||||
.poll(() => [client.observeAgentsCalls, client.observeWorkspacesCalls])
|
||||
.toEqual([1, 1]);
|
||||
|
||||
await Promise.all(client.listSnapshots);
|
||||
setDemand(false);
|
||||
if (timing === "before") setDemand(true);
|
||||
releaseProjects(projects);
|
||||
await refresh;
|
||||
if (timing === "after") setDemand(true);
|
||||
|
||||
await expect
|
||||
.poll(() => [client.observeAgentsCalls, client.observeWorkspacesCalls])
|
||||
.toEqual([2, 2]);
|
||||
client.emit({
|
||||
type: "agent_update",
|
||||
payload: {
|
||||
kind: "upsert",
|
||||
agent: {
|
||||
...projectAgentSnapshot(createAgent(serverId, "agent-1")),
|
||||
title: "Live title",
|
||||
},
|
||||
project: deriveProjectPlacementFromCwd("/repo"),
|
||||
},
|
||||
});
|
||||
client.emit({
|
||||
type: "workspace_update",
|
||||
payload: {
|
||||
kind: "upsert",
|
||||
workspace: { ...createWorkspaceEntry("workspace-1"), name: "Live workspace" },
|
||||
},
|
||||
});
|
||||
|
||||
await expect
|
||||
.poll(() => {
|
||||
const session = useSessionStore.getState().sessions[serverId];
|
||||
return [
|
||||
session.agents.get("agent-1")?.title,
|
||||
session.workspaces.get("workspace-1")?.name,
|
||||
];
|
||||
})
|
||||
.toEqual(["Live title", "Live workspace"]);
|
||||
} finally {
|
||||
directory.dispose();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("publishes cached directory data before the authoritative request completes", async () => {
|
||||
const serverId = "cached-directory";
|
||||
serverIds.add(serverId);
|
||||
|
||||
@@ -160,7 +160,6 @@ export class DirectorySync {
|
||||
private readonly fullDemandSources = new Set<object>();
|
||||
private readonly scriptStatusDemand = new Map<object, string>();
|
||||
private demandRefresh: Promise<void> | null = null;
|
||||
private subscriptionGeneration = 0;
|
||||
private satisfiedDemandSource: DirectorySourceToken | null = null;
|
||||
private cursors: DirectoryCheckpoint = {};
|
||||
|
||||
@@ -263,7 +262,6 @@ export class DirectorySync {
|
||||
}
|
||||
|
||||
private releaseSubscriptions(): void {
|
||||
this.subscriptionGeneration += 1;
|
||||
for (const subscription of [
|
||||
this.agentSubscription,
|
||||
this.workspaceSubscription,
|
||||
@@ -364,7 +362,6 @@ export class DirectorySync {
|
||||
this.observeDirectoryEvents();
|
||||
this.observeScriptStatusEvents();
|
||||
const source = this.connection.source;
|
||||
const subscriptionGeneration = this.subscriptionGeneration;
|
||||
if (
|
||||
!force &&
|
||||
this.satisfiedDemandSource?.clientGeneration === source.clientGeneration &&
|
||||
@@ -381,19 +378,17 @@ export class DirectorySync {
|
||||
]).then(() => undefined);
|
||||
this.demandRefresh = refresh
|
||||
.then(() => {
|
||||
if (this.subscriptionGeneration === subscriptionGeneration) {
|
||||
this.satisfiedDemandSource = source;
|
||||
}
|
||||
this.satisfiedDemandSource = source;
|
||||
return undefined;
|
||||
})
|
||||
.finally(() => {
|
||||
this.demandRefresh = null;
|
||||
const current = this.connection.source;
|
||||
const sourceChanged =
|
||||
current.clientGeneration !== source.clientGeneration ||
|
||||
current.connectionEpoch !== source.connectionEpoch;
|
||||
const subscriptionsReleased = this.subscriptionGeneration !== subscriptionGeneration;
|
||||
if (this.hasDemand() && (sourceChanged || subscriptionsReleased)) {
|
||||
if (
|
||||
this.hasDemand() &&
|
||||
(current.clientGeneration !== source.clientGeneration ||
|
||||
current.connectionEpoch !== source.connectionEpoch)
|
||||
) {
|
||||
void this.requestDemandRefresh().catch(() => undefined);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -48,7 +48,8 @@ export interface TerminalCellStyleResolver {
|
||||
export const DEFAULT_TERMINAL_THEME = toXtermTheme(darkTheme.colors.terminal);
|
||||
|
||||
export const NATIVE_TERMINAL_SELECTION_COLORS = {
|
||||
background: 0x472684ff,
|
||||
background: 0xffffff00,
|
||||
foreground: 0xff000000,
|
||||
} as const;
|
||||
|
||||
function build256Palette(theme: ITheme): number[] {
|
||||
|
||||
@@ -77,6 +77,7 @@ export function TerminalGridView({
|
||||
background: resolver.backgroundColor,
|
||||
cursor: resolver.cursorColor,
|
||||
selectionBackground: NATIVE_TERMINAL_SELECTION_COLORS.background,
|
||||
selectionForeground: NATIVE_TERMINAL_SELECTION_COLORS.foreground,
|
||||
}),
|
||||
[resolver],
|
||||
);
|
||||
|
||||
@@ -1,411 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { createNativeHeadlessTerminal } from "./headless-terminal-state";
|
||||
import {
|
||||
createTerminalSelectionModel,
|
||||
extractTerminalSelectedText,
|
||||
resolveTerminalSelectionRects,
|
||||
} from "./terminal-selection";
|
||||
import {
|
||||
createTerminalSelectionController,
|
||||
terminalSelectionHandles,
|
||||
} from "./terminal-selection-controller";
|
||||
|
||||
describe("selection handle controller", () => {
|
||||
it("preserves the grab offset while moving a handle", () => {
|
||||
const range = { start: { row: 1, col: 2 }, end: { row: 1, col: 5 }, coordinateEpoch: 0 };
|
||||
const moves: Array<{ row: number; col: number }> = [];
|
||||
const controller = createTerminalSelectionController({
|
||||
getGeometry: () => ({
|
||||
range,
|
||||
viewport: { firstRow: 0, rows: 10, cols: 10 },
|
||||
metrics: { cellWidth: 10, cellHeight: 10 },
|
||||
}),
|
||||
onBeginHandle: () => {},
|
||||
onMoveHandle: (coordinate) => moves.push(coordinate),
|
||||
onLongPress: () => {},
|
||||
onTap: () => {},
|
||||
onScroll: () => {},
|
||||
schedule: () => 1,
|
||||
cancel: () => {},
|
||||
});
|
||||
controller.press({ x: 23, y: 15 });
|
||||
controller.move({ x: 63, y: 15 });
|
||||
controller.release();
|
||||
expect(moves).toEqual([{ row: 1, col: 5 }]);
|
||||
});
|
||||
});
|
||||
|
||||
it("selects on hold, preserves a handle tap, and cancels an active drag", () => {
|
||||
const actions: string[] = [];
|
||||
let timer: (() => void) | null = null;
|
||||
const controller = createTerminalSelectionController({
|
||||
getGeometry: () => ({
|
||||
range: { start: { row: 2, col: 2 }, end: { row: 2, col: 5 }, coordinateEpoch: 0 },
|
||||
viewport: { firstRow: 0, rows: 10, cols: 10 },
|
||||
metrics: { cellWidth: 10, cellHeight: 10 },
|
||||
}),
|
||||
onBeginHandle: (endpoint) => actions.push(endpoint),
|
||||
onMoveHandle: () => actions.push("move"),
|
||||
onLongPress: () => actions.push("long"),
|
||||
onTap: () => actions.push("tap"),
|
||||
onScroll: () => actions.push("scroll"),
|
||||
schedule: (callback) => {
|
||||
timer = callback;
|
||||
return 1;
|
||||
},
|
||||
cancel: () => {
|
||||
timer = null;
|
||||
},
|
||||
});
|
||||
controller.press({ x: 90, y: 80 });
|
||||
(timer as (() => void) | null)?.();
|
||||
controller.release();
|
||||
controller.press({ x: 20, y: 25 });
|
||||
controller.release();
|
||||
controller.press({ x: 20, y: 25 });
|
||||
controller.cancel();
|
||||
controller.move({ x: 50, y: 25 });
|
||||
expect(actions).toEqual(["long", "start", "start"]);
|
||||
});
|
||||
|
||||
it("scrolls selection into history while holding a handle at the edge", () => {
|
||||
let firstRow = 10;
|
||||
let timer: (() => void) | null = null;
|
||||
const coordinates: Array<{ row: number; col: number }> = [];
|
||||
const controller = createTerminalSelectionController({
|
||||
getGeometry: () => ({
|
||||
range: { start: { row: 12, col: 2 }, end: { row: 13, col: 5 }, coordinateEpoch: 0 },
|
||||
viewport: { firstRow, rows: 10, cols: 10 },
|
||||
metrics: { cellWidth: 10, cellHeight: 10 },
|
||||
}),
|
||||
onBeginHandle: () => {},
|
||||
onMoveHandle: (point) => coordinates.push(point),
|
||||
onLongPress: () => {},
|
||||
onTap: () => {},
|
||||
onScroll: (direction) => {
|
||||
if (direction === "up") firstRow--;
|
||||
},
|
||||
schedule: (callback) => {
|
||||
timer = callback;
|
||||
return 1;
|
||||
},
|
||||
cancel: () => {
|
||||
timer = null;
|
||||
},
|
||||
});
|
||||
controller.press({ x: 20, y: 25 });
|
||||
controller.move({ x: 20, y: 1 });
|
||||
(timer as (() => void) | null)?.();
|
||||
(timer as (() => void) | null)?.();
|
||||
controller.release();
|
||||
expect(coordinates).toEqual([
|
||||
{ row: 10, col: 2 },
|
||||
{ row: 9, col: 2 },
|
||||
{ row: 8, col: 2 },
|
||||
]);
|
||||
expect(timer).toBeNull();
|
||||
});
|
||||
|
||||
it("scrolls outside handles without clearing selection and clears on an outside tap", () => {
|
||||
const actions: string[] = [];
|
||||
const controller = createTerminalSelectionController({
|
||||
getGeometry: () => ({
|
||||
range: { start: { row: 2, col: 2 }, end: { row: 2, col: 5 }, coordinateEpoch: 0 },
|
||||
viewport: { firstRow: 0, rows: 10, cols: 10 },
|
||||
metrics: { cellWidth: 10, cellHeight: 10 },
|
||||
}),
|
||||
onBeginHandle: () => actions.push("handle"),
|
||||
onMoveHandle: () => actions.push("move"),
|
||||
onLongPress: () => actions.push("long"),
|
||||
onTap: () => actions.push("tap"),
|
||||
onScroll: (direction, rows) => actions.push(`${direction}:${rows}`),
|
||||
schedule: () => 1,
|
||||
cancel: () => {},
|
||||
});
|
||||
controller.press({ x: 95, y: 70 });
|
||||
controller.move({ x: 95, y: 90 });
|
||||
controller.release();
|
||||
controller.press({ x: 95, y: 70 });
|
||||
controller.release();
|
||||
expect(actions).toEqual(["up:2", "tap"]);
|
||||
});
|
||||
|
||||
it("extends the selection after a long press and drag", () => {
|
||||
let timer: (() => void) | null = null;
|
||||
const moves: Array<{ row: number; col: number }> = [];
|
||||
const controller = createTerminalSelectionController({
|
||||
getGeometry: () => ({
|
||||
range: null,
|
||||
viewport: { firstRow: 0, rows: 10, cols: 10 },
|
||||
metrics: { cellWidth: 10, cellHeight: 10 },
|
||||
}),
|
||||
onBeginHandle: () => {},
|
||||
onMoveHandle: (coordinate) => moves.push(coordinate),
|
||||
onLongPress: () => {},
|
||||
onTap: () => {},
|
||||
onScroll: () => {},
|
||||
schedule: (callback) => {
|
||||
timer = callback;
|
||||
return 1;
|
||||
},
|
||||
cancel: () => {
|
||||
timer = null;
|
||||
},
|
||||
});
|
||||
controller.press({ x: 25, y: 25 });
|
||||
(timer as (() => void) | null)?.();
|
||||
controller.move({ x: 65, y: 35 });
|
||||
controller.release();
|
||||
expect(moves).toEqual([{ row: 3, col: 6 }]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
endpoint: "start" as const,
|
||||
startX: 20,
|
||||
crossedX: 80,
|
||||
crossedText: "gh",
|
||||
crossedStart: 6,
|
||||
crossedEnd: 7,
|
||||
backX: 10,
|
||||
backText: "bcdef",
|
||||
backStart: 1,
|
||||
backEnd: 5,
|
||||
},
|
||||
{
|
||||
endpoint: "end" as const,
|
||||
startX: 60,
|
||||
crossedX: 10,
|
||||
crossedText: "b",
|
||||
crossedStart: 1,
|
||||
crossedEnd: 1,
|
||||
backX: 80,
|
||||
backText: "cdefgh",
|
||||
backStart: 2,
|
||||
backEnd: 7,
|
||||
},
|
||||
])("tracks the $endpoint handle through crossing and back", async (scenario) => {
|
||||
const terminal = createNativeHeadlessTerminal({ rows: 4, cols: 10 });
|
||||
try {
|
||||
await terminal.write("abcdefghij");
|
||||
const bounds = terminal.getBufferBounds();
|
||||
const model = createTerminalSelectionModel();
|
||||
model.begin({ coordinate: { row: 0, col: 2 }, bounds });
|
||||
model.update({ coordinate: { row: 0, col: 5 }, bounds });
|
||||
const viewport = { firstRow: 0, rows: 4, cols: 10 };
|
||||
const metrics = { cellWidth: 10, cellHeight: 10 };
|
||||
const geometry = () => ({ range: model.getSnapshot().range, viewport, metrics });
|
||||
const controller = createTerminalSelectionController({
|
||||
getGeometry: geometry,
|
||||
onBeginHandle: (endpoint, cols) => model.beginEndpointDrag(endpoint, cols),
|
||||
onMoveHandle: (coordinate) => {
|
||||
model.update({ coordinate, bounds });
|
||||
},
|
||||
onLongPress: () => {},
|
||||
onTap: () => {},
|
||||
onScroll: () => {},
|
||||
schedule: () => 1,
|
||||
cancel: () => {},
|
||||
});
|
||||
const check = (start: number, end: number, text: string) => {
|
||||
const range = model.getSnapshot().range;
|
||||
expect(range).toEqual({
|
||||
start: { row: 0, col: start },
|
||||
end: { row: 0, col: end },
|
||||
coordinateEpoch: bounds.coordinateEpoch,
|
||||
});
|
||||
expect(terminalSelectionHandles(geometry())).toMatchObject([
|
||||
{ endpoint: "start", x: start * 10, y: 5 },
|
||||
{ endpoint: "end", x: (end + 1) * 10, y: 5 },
|
||||
]);
|
||||
expect(resolveTerminalSelectionRects({ selection: range, viewport, metrics })).toEqual([
|
||||
{
|
||||
key: `0:${start}:${end}`,
|
||||
x: start * 10,
|
||||
y: 0,
|
||||
width: (end - start + 1) * 10,
|
||||
height: 10,
|
||||
},
|
||||
]);
|
||||
expect(extractTerminalSelectedText({ terminal, selection: range })).toBe(text);
|
||||
};
|
||||
controller.press({ x: scenario.startX, y: 5 });
|
||||
controller.move({ x: scenario.crossedX, y: 5 });
|
||||
check(scenario.crossedStart, scenario.crossedEnd, scenario.crossedText);
|
||||
controller.move({ x: scenario.backX, y: 5 });
|
||||
check(scenario.backStart, scenario.backEnd, scenario.backText);
|
||||
controller.release();
|
||||
} finally {
|
||||
terminal.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
endpoint: "end" as const,
|
||||
initialRow: 0,
|
||||
targetRow: 1,
|
||||
targetX: 0,
|
||||
expectedRow: 0,
|
||||
expectedCol: 9,
|
||||
text: "cdefghij",
|
||||
},
|
||||
{
|
||||
endpoint: "start" as const,
|
||||
initialRow: 1,
|
||||
targetRow: 0,
|
||||
targetX: 100,
|
||||
expectedRow: 1,
|
||||
expectedCol: 0,
|
||||
text: "KLMNOP",
|
||||
},
|
||||
])("preserves a $endpoint boundary at a row edge", async (scenario) => {
|
||||
const terminal = createNativeHeadlessTerminal({ rows: 4, cols: 10 });
|
||||
try {
|
||||
await terminal.write("abcdefghij\r\nKLMNOPQRST");
|
||||
const bounds = terminal.getBufferBounds();
|
||||
const model = createTerminalSelectionModel();
|
||||
model.begin({ coordinate: { row: scenario.initialRow, col: 2 }, bounds });
|
||||
model.update({ coordinate: { row: scenario.initialRow, col: 5 }, bounds });
|
||||
const viewport = { firstRow: 0, rows: 4, cols: 10 };
|
||||
const metrics = { cellWidth: 10, cellHeight: 10 };
|
||||
const geometry = () => ({ range: model.getSnapshot().range, viewport, metrics });
|
||||
const controller = createTerminalSelectionController({
|
||||
getGeometry: geometry,
|
||||
onBeginHandle: (endpoint, cols) => model.beginEndpointDrag(endpoint, cols),
|
||||
onMoveHandle: (coordinate) => {
|
||||
model.update({ coordinate, bounds });
|
||||
},
|
||||
onLongPress: () => {},
|
||||
onTap: () => {},
|
||||
onScroll: () => {},
|
||||
schedule: () => 1,
|
||||
cancel: () => {},
|
||||
});
|
||||
controller.press({ x: scenario.endpoint === "end" ? 60 : 20, y: scenario.initialRow * 10 + 5 });
|
||||
controller.move({ x: scenario.targetX, y: scenario.targetRow * 10 + 5 });
|
||||
const range = model.getSnapshot().range;
|
||||
expect(range?.[scenario.endpoint]).toEqual({
|
||||
row: scenario.expectedRow,
|
||||
col: scenario.expectedCol,
|
||||
});
|
||||
expect(extractTerminalSelectedText({ terminal, selection: range })).toBe(scenario.text);
|
||||
expect(
|
||||
terminalSelectionHandles(geometry()).find((handle) => handle.endpoint === scenario.endpoint),
|
||||
).toMatchObject({
|
||||
x: scenario.endpoint === "end" ? 100 : 0,
|
||||
y: scenario.expectedRow * 10 + 5,
|
||||
});
|
||||
controller.release();
|
||||
} finally {
|
||||
terminal.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("cancels a drag when buffer coordinates are invalidated", () => {
|
||||
const model = createTerminalSelectionModel();
|
||||
const bounds = { oldestRow: 0, newestRow: 9, coordinateEpoch: 0 };
|
||||
model.begin({ coordinate: { row: 2, col: 2 }, bounds });
|
||||
model.update({ coordinate: { row: 2, col: 5 }, bounds });
|
||||
const viewport = { firstRow: 0, rows: 10, cols: 10 };
|
||||
const metrics = { cellWidth: 10, cellHeight: 10 };
|
||||
const controller = createTerminalSelectionController({
|
||||
getGeometry: () => ({ range: model.getSnapshot().range, viewport, metrics }),
|
||||
onBeginHandle: (endpoint, cols) => model.beginEndpointDrag(endpoint, cols),
|
||||
onMoveHandle: (coordinate) => {
|
||||
model.update({ coordinate, bounds });
|
||||
},
|
||||
onLongPress: () => {},
|
||||
onTap: () => {},
|
||||
onScroll: () => {},
|
||||
schedule: () => 1,
|
||||
cancel: () => {},
|
||||
});
|
||||
controller.press({ x: 20, y: 25 });
|
||||
const previous = model.getSnapshot().range;
|
||||
const snapshot = model.sync({ bounds: { ...bounds, coordinateEpoch: 1 } });
|
||||
if (previous && !snapshot.range) controller.cancel();
|
||||
controller.move({ x: 80, y: 25 });
|
||||
controller.release();
|
||||
expect(model.getSnapshot().range).toBeNull();
|
||||
});
|
||||
|
||||
it("preserves a newly selected word through small movement at the viewport edge", () => {
|
||||
const model = createTerminalSelectionModel();
|
||||
const bounds = { oldestRow: 0, newestRow: 9, coordinateEpoch: 0 };
|
||||
let timer: (() => void) | null = null;
|
||||
const controller = createTerminalSelectionController({
|
||||
getGeometry: () => ({
|
||||
range: model.getSnapshot().range,
|
||||
viewport: { firstRow: 0, rows: 10, cols: 20 },
|
||||
metrics: { cellWidth: 10, cellHeight: 10 },
|
||||
}),
|
||||
onBeginHandle: (endpoint, cols) => model.beginEndpointDrag(endpoint, cols),
|
||||
onMoveHandle: (coordinate) => {
|
||||
model.update({ coordinate, bounds });
|
||||
},
|
||||
onLongPress: () => {
|
||||
model.begin({ coordinate: { row: 0, col: 2 }, bounds });
|
||||
model.update({ coordinate: { row: 0, col: 6 }, bounds });
|
||||
},
|
||||
onTap: () => {},
|
||||
onScroll: () => {},
|
||||
schedule: (callback) => {
|
||||
timer = callback;
|
||||
return 1;
|
||||
},
|
||||
cancel: () => {
|
||||
timer = null;
|
||||
},
|
||||
});
|
||||
controller.press({ x: 45, y: 5 });
|
||||
const fire = timer as (() => void) | null;
|
||||
timer = null;
|
||||
fire?.();
|
||||
controller.move({ x: 44, y: 4 });
|
||||
controller.release();
|
||||
expect(model.getSnapshot().range).toEqual({
|
||||
start: { row: 0, col: 2 },
|
||||
end: { row: 0, col: 6 },
|
||||
coordinateEpoch: 0,
|
||||
});
|
||||
expect(timer).toBeNull();
|
||||
});
|
||||
|
||||
it("places mirrored teardrop grips below the selected row", () => {
|
||||
const handles = terminalSelectionHandles({
|
||||
range: { start: { row: 2, col: 2 }, end: { row: 2, col: 5 }, coordinateEpoch: 0 },
|
||||
viewport: { firstRow: 0, rows: 10, cols: 10 },
|
||||
metrics: { cellWidth: 10, cellHeight: 10 },
|
||||
});
|
||||
expect(handles).toMatchObject([
|
||||
{ endpoint: "start", x: 20, y: 25, gripX: 11, gripY: 39, gripDirection: "left" },
|
||||
{ endpoint: "end", x: 60, y: 25, gripX: 69, gripY: 39, gripDirection: "right" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps edge grips reachable and preserves the offset from the cell when dragging a grip", () => {
|
||||
const range = { start: { row: 0, col: 0 }, end: { row: 9, col: 9 }, coordinateEpoch: 0 };
|
||||
const viewport = { firstRow: 0, rows: 10, cols: 10 };
|
||||
const metrics = { cellWidth: 10, cellHeight: 10 };
|
||||
const handles = terminalSelectionHandles({ range, viewport, metrics });
|
||||
expect(handles.map(({ gripX, gripY }) => ({ gripX, gripY }))).toEqual([
|
||||
{ gripX: 9, gripY: 19 },
|
||||
{ gripX: 91, gripY: 81 },
|
||||
]);
|
||||
const moves: Array<{ row: number; col: number }> = [];
|
||||
const controller = createTerminalSelectionController({
|
||||
getGeometry: () => ({ range, viewport, metrics }),
|
||||
onBeginHandle: () => {},
|
||||
onMoveHandle: (coordinate) => moves.push(coordinate),
|
||||
onLongPress: () => {},
|
||||
onTap: () => {},
|
||||
onScroll: () => {},
|
||||
schedule: () => 1,
|
||||
cancel: () => {},
|
||||
});
|
||||
controller.press({ x: 9, y: 19 });
|
||||
controller.move({ x: 19, y: 29 });
|
||||
controller.release();
|
||||
expect(moves).toEqual([{ row: 1, col: 1 }]);
|
||||
});
|
||||
@@ -1,208 +0,0 @@
|
||||
import type { TerminalGridCellMetrics } from "./terminal-grid-metrics";
|
||||
import type {
|
||||
TerminalBufferCoordinate,
|
||||
TerminalSelectionPoint,
|
||||
TerminalSelectionRange,
|
||||
TerminalSelectionViewport,
|
||||
} from "./terminal-selection";
|
||||
export const TERMINAL_SELECTION_GRIP_SIZE = 18;
|
||||
const TERMINAL_GESTURE_LONG_PRESS_MS = 450;
|
||||
const TERMINAL_GESTURE_TAP_TOLERANCE_PX = 8;
|
||||
|
||||
type Endpoint = "start" | "end";
|
||||
interface Geometry {
|
||||
range: TerminalSelectionRange | null;
|
||||
viewport: TerminalSelectionViewport;
|
||||
metrics: TerminalGridCellMetrics;
|
||||
}
|
||||
interface Ports {
|
||||
getGeometry(): Geometry | null;
|
||||
onBeginHandle(endpoint: Endpoint, cols: number): void;
|
||||
onMoveHandle(coordinate: TerminalBufferCoordinate): void;
|
||||
onLongPress(point: TerminalSelectionPoint): void;
|
||||
onTap(): void;
|
||||
onScroll(direction: "up" | "down", rows: number): void;
|
||||
schedule(callback: () => void, delay: number): number;
|
||||
cancel(timer: number): void;
|
||||
}
|
||||
|
||||
export function terminalSelectionHandles(geometry: Geometry): Array<{
|
||||
endpoint: Endpoint;
|
||||
x: number;
|
||||
y: number;
|
||||
gripX: number;
|
||||
gripY: number;
|
||||
gripDirection: "left" | "right";
|
||||
gripAbove: boolean;
|
||||
stemTop: number;
|
||||
stemHeight: number;
|
||||
}> {
|
||||
const { range, viewport, metrics } = geometry;
|
||||
if (!range) return [];
|
||||
return (["start", "end"] as const).flatMap((endpoint) => {
|
||||
const cell = range[endpoint];
|
||||
if (cell.row < viewport.firstRow || cell.row >= viewport.firstRow + viewport.rows) return [];
|
||||
const x = (cell.col + (endpoint === "end" ? 1 : 0)) * metrics.cellWidth;
|
||||
const stemTop = (cell.row - viewport.firstRow) * metrics.cellHeight;
|
||||
const size = TERMINAL_SELECTION_GRIP_SIZE;
|
||||
const width = viewport.cols * metrics.cellWidth;
|
||||
const height = viewport.rows * metrics.cellHeight;
|
||||
const wantsLeft = endpoint === "start";
|
||||
const gripDirection =
|
||||
(wantsLeft && x >= size) || (!wantsLeft && x > width - size) ? "left" : "right";
|
||||
const gripAbove = stemTop + metrics.cellHeight + size > height;
|
||||
const gripTop = gripAbove ? Math.max(0, stemTop - size) : stemTop + metrics.cellHeight;
|
||||
return [
|
||||
{
|
||||
endpoint,
|
||||
x,
|
||||
y: stemTop + metrics.cellHeight / 2,
|
||||
gripX: x + (gripDirection === "left" ? -size / 2 : size / 2),
|
||||
gripY: gripTop + size / 2,
|
||||
gripDirection,
|
||||
gripAbove,
|
||||
stemTop,
|
||||
stemHeight: metrics.cellHeight,
|
||||
},
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
export function createTerminalSelectionController(ports: Ports) {
|
||||
let press: {
|
||||
start: TerminalSelectionPoint;
|
||||
point: TerminalSelectionPoint;
|
||||
endpoint: Endpoint | null;
|
||||
offset: TerminalSelectionPoint;
|
||||
fixed: TerminalBufferCoordinate | null;
|
||||
moved: boolean;
|
||||
long: boolean;
|
||||
scrolling: boolean;
|
||||
remainder: number;
|
||||
} | null = null;
|
||||
let timer: number | null = null;
|
||||
function stopTimer() {
|
||||
if (timer !== null) ports.cancel(timer);
|
||||
timer = null;
|
||||
}
|
||||
function updateHandle() {
|
||||
const geometry = ports.getGeometry();
|
||||
if (!press || (!press.endpoint && !press.long) || !geometry) return;
|
||||
const { viewport, metrics } = geometry;
|
||||
const x = press.point.x - press.offset.x;
|
||||
const y = press.point.y - press.offset.y;
|
||||
let row =
|
||||
viewport.firstRow +
|
||||
Math.max(0, Math.min(viewport.rows - 1, Math.floor(y / metrics.cellHeight)));
|
||||
let col = Math.floor(x / metrics.cellWidth);
|
||||
if (press.endpoint && press.fixed) {
|
||||
const boundary = Math.round(x / metrics.cellWidth);
|
||||
const isEnd =
|
||||
row > press.fixed.row || (row === press.fixed.row && boundary > press.fixed.col);
|
||||
col = boundary - (isEnd ? 1 : 0);
|
||||
if (col < 0 && isEnd) {
|
||||
row -= 1;
|
||||
col = viewport.cols - 1;
|
||||
} else if (col >= viewport.cols && !isEnd) {
|
||||
row += 1;
|
||||
col = 0;
|
||||
}
|
||||
}
|
||||
col = Math.max(0, Math.min(viewport.cols - 1, col));
|
||||
ports.onMoveHandle({ row, col });
|
||||
}
|
||||
function edgeTick() {
|
||||
timer = null;
|
||||
const geometry = ports.getGeometry();
|
||||
if (!press || (!press.endpoint && !press.long) || !geometry) return;
|
||||
const y = press.point.y - press.offset.y;
|
||||
const height = geometry.viewport.rows * geometry.metrics.cellHeight;
|
||||
let direction: "up" | "down" | null = null;
|
||||
if (y < geometry.metrics.cellHeight) direction = "up";
|
||||
else if (y > height - geometry.metrics.cellHeight) direction = "down";
|
||||
if (!direction) return;
|
||||
ports.onScroll(direction, 1);
|
||||
if (!press) return;
|
||||
updateHandle();
|
||||
if (press) timer = ports.schedule(edgeTick, 100);
|
||||
}
|
||||
return {
|
||||
press(point: TerminalSelectionPoint) {
|
||||
stopTimer();
|
||||
const geometry = ports.getGeometry();
|
||||
const handles = geometry ? terminalSelectionHandles(geometry) : [];
|
||||
const handle = handles
|
||||
.map((item) => ({
|
||||
endpoint: item.endpoint,
|
||||
x: item.x,
|
||||
y: item.y,
|
||||
distance: Math.hypot(point.x - item.gripX, point.y - item.gripY),
|
||||
}))
|
||||
.filter((item) => item.distance <= 28)
|
||||
.sort((a, b) => a.distance - b.distance)[0];
|
||||
press = {
|
||||
start: point,
|
||||
point,
|
||||
endpoint: handle?.endpoint ?? null,
|
||||
offset: handle ? { x: point.x - handle.x, y: point.y - handle.y } : { x: 0, y: 0 },
|
||||
fixed:
|
||||
handle && geometry?.range
|
||||
? geometry.range[handle.endpoint === "start" ? "end" : "start"]
|
||||
: null,
|
||||
moved: false,
|
||||
long: false,
|
||||
scrolling: false,
|
||||
remainder: 0,
|
||||
};
|
||||
if (handle && geometry) {
|
||||
ports.onBeginHandle(handle.endpoint, geometry.viewport.cols);
|
||||
return;
|
||||
}
|
||||
timer = ports.schedule(() => {
|
||||
timer = null;
|
||||
if (press && !press.moved) {
|
||||
press.long = true;
|
||||
ports.onLongPress(press.start);
|
||||
}
|
||||
}, TERMINAL_GESTURE_LONG_PRESS_MS);
|
||||
},
|
||||
move(point: TerminalSelectionPoint) {
|
||||
if (!press) return;
|
||||
const previous = press.point;
|
||||
press.point = point;
|
||||
const dx = point.x - press.start.x,
|
||||
dy = point.y - press.start.y;
|
||||
if (Math.hypot(dx, dy) > TERMINAL_GESTURE_TAP_TOLERANCE_PX) {
|
||||
press.moved = true;
|
||||
if (!press.endpoint) stopTimer();
|
||||
}
|
||||
if (press.endpoint || press.long) {
|
||||
if (press.endpoint || press.moved) {
|
||||
updateHandle();
|
||||
stopTimer();
|
||||
if (press) timer = ports.schedule(edgeTick, 100);
|
||||
}
|
||||
} else if (!press.long) {
|
||||
if (!press.scrolling && Math.abs(dy) > 12 && Math.abs(dy) > Math.abs(dx)) {
|
||||
press.scrolling = true;
|
||||
press.remainder = dy;
|
||||
} else if (press.scrolling) press.remainder += point.y - previous.y;
|
||||
const height = ports.getGeometry()?.metrics.cellHeight ?? 0;
|
||||
if (press.scrolling && height > 0) {
|
||||
const rows = Math.trunc(press.remainder / height);
|
||||
press.remainder -= rows * height;
|
||||
if (rows) ports.onScroll(rows > 0 ? "up" : "down", Math.abs(rows));
|
||||
}
|
||||
}
|
||||
},
|
||||
release() {
|
||||
stopTimer();
|
||||
if (press && !press.endpoint && !press.long && !press.moved) ports.onTap();
|
||||
press = null;
|
||||
},
|
||||
cancel() {
|
||||
stopTimer();
|
||||
press = null;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,354 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
TERMINAL_GESTURE_LONG_PRESS_MS,
|
||||
TERMINAL_GESTURE_TAP_TOLERANCE_PX,
|
||||
TERMINAL_GESTURE_VERTICAL_SCROLL_THRESHOLD_PX,
|
||||
advanceTerminalScrollGesture,
|
||||
classifyTerminalGestureIntent,
|
||||
resolveTerminalGestureReleaseAction,
|
||||
} from "./terminal-selection-gesture";
|
||||
|
||||
describe("native terminal gesture policy", () => {
|
||||
describe("advanceTerminalScrollGesture", () => {
|
||||
it("keeps consuming a slow drag after scroll intent arms below one row", () => {
|
||||
let state = { lastDy: 0, rowRemainder: 0, didScroll: false };
|
||||
const rowDeltas: number[] = [];
|
||||
|
||||
for (const currentDy of [13, 15, 18, 22, 28]) {
|
||||
const update = advanceTerminalScrollGesture({
|
||||
state,
|
||||
currentDy,
|
||||
cellHeight: 14,
|
||||
});
|
||||
state = update.state;
|
||||
rowDeltas.push(update.rowDelta);
|
||||
}
|
||||
|
||||
expect({ rowDeltas, state }).toEqual({
|
||||
rowDeltas: [0, 1, 0, 0, 1],
|
||||
state: { lastDy: 28, rowRemainder: 0, didScroll: true },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("classifyTerminalGestureIntent", () => {
|
||||
it("treats a motionless press as a tap", () => {
|
||||
expect(
|
||||
classifyTerminalGestureIntent({
|
||||
status: "pressing",
|
||||
dx: 0,
|
||||
dy: 0,
|
||||
vx: 0,
|
||||
vy: 0,
|
||||
}),
|
||||
).toEqual("tap");
|
||||
});
|
||||
|
||||
it("treats a tiny jitter within tap tolerance as a tap", () => {
|
||||
expect(
|
||||
classifyTerminalGestureIntent({
|
||||
status: "pressing",
|
||||
dx: TERMINAL_GESTURE_TAP_TOLERANCE_PX - 4,
|
||||
dy: TERMINAL_GESTURE_TAP_TOLERANCE_PX - 4,
|
||||
vx: 0,
|
||||
vy: 0,
|
||||
}),
|
||||
).toEqual("tap");
|
||||
});
|
||||
|
||||
it("leaves horizontal movement available to terminal selection", () => {
|
||||
expect(
|
||||
classifyTerminalGestureIntent({
|
||||
status: "pressing",
|
||||
dx: TERMINAL_GESTURE_TAP_TOLERANCE_PX + 20,
|
||||
dy: 4,
|
||||
vx: 0,
|
||||
vy: 0,
|
||||
}),
|
||||
).toEqual("pending");
|
||||
});
|
||||
|
||||
it("does not infer selection from slow horizontal drag dwell", () => {
|
||||
expect(
|
||||
classifyTerminalGestureIntent({
|
||||
status: "pressing",
|
||||
dx: TERMINAL_GESTURE_TAP_TOLERANCE_PX + 40,
|
||||
dy: 3,
|
||||
vx: 0,
|
||||
vy: 0,
|
||||
elapsedMs: TERMINAL_GESTURE_LONG_PRESS_MS + 50,
|
||||
}),
|
||||
).toEqual("pending");
|
||||
});
|
||||
|
||||
it("keeps tiny horizontal jitter inside tap tolerance as a tap", () => {
|
||||
expect(
|
||||
classifyTerminalGestureIntent({
|
||||
status: "pressing",
|
||||
dx: TERMINAL_GESTURE_TAP_TOLERANCE_PX - 1,
|
||||
dy: 1,
|
||||
vx: 2,
|
||||
vy: 0,
|
||||
elapsedMs: 20,
|
||||
}),
|
||||
).toEqual("tap");
|
||||
});
|
||||
|
||||
it("keeps horizontal movement below navigation distance pending", () => {
|
||||
expect(
|
||||
classifyTerminalGestureIntent({
|
||||
status: "pressing",
|
||||
dx: TERMINAL_GESTURE_TAP_TOLERANCE_PX + 10,
|
||||
dy: 2,
|
||||
vx: 0,
|
||||
vy: 0,
|
||||
}),
|
||||
).toEqual("pending");
|
||||
});
|
||||
|
||||
it("treats a clearly vertical drag as scroll", () => {
|
||||
expect(
|
||||
classifyTerminalGestureIntent({
|
||||
status: "pressing",
|
||||
dx: 4,
|
||||
dy: TERMINAL_GESTURE_VERTICAL_SCROLL_THRESHOLD_PX + 5,
|
||||
vx: 0,
|
||||
vy: 0.2,
|
||||
}),
|
||||
).toEqual("scroll");
|
||||
});
|
||||
|
||||
it("does not navigate on a fast rightward swipe", () => {
|
||||
expect(
|
||||
classifyTerminalGestureIntent({
|
||||
status: "pressing",
|
||||
dx: TERMINAL_GESTURE_TAP_TOLERANCE_PX + 40,
|
||||
dy: 4,
|
||||
vx: 2,
|
||||
vy: 0,
|
||||
}),
|
||||
).toEqual("pending");
|
||||
});
|
||||
|
||||
it("does not navigate on a slow rightward swipe", () => {
|
||||
expect(
|
||||
classifyTerminalGestureIntent({
|
||||
status: "pressing",
|
||||
dx: TERMINAL_GESTURE_TAP_TOLERANCE_PX + 40,
|
||||
dy: 4,
|
||||
vx: 0,
|
||||
vy: 0,
|
||||
}),
|
||||
).toEqual("pending");
|
||||
});
|
||||
|
||||
it("does not navigate on a fast leftward swipe", () => {
|
||||
expect(
|
||||
classifyTerminalGestureIntent({
|
||||
status: "pressing",
|
||||
dx: -(TERMINAL_GESTURE_TAP_TOLERANCE_PX + 40),
|
||||
dy: -4,
|
||||
vx: -2,
|
||||
vy: 0,
|
||||
}),
|
||||
).toEqual("pending");
|
||||
});
|
||||
|
||||
it("does not navigate while movement stays inside tap tolerance", () => {
|
||||
expect(
|
||||
classifyTerminalGestureIntent({
|
||||
status: "pressing",
|
||||
dx: TERMINAL_GESTURE_TAP_TOLERANCE_PX - 1,
|
||||
dy: 2,
|
||||
vx: 2,
|
||||
vy: 0,
|
||||
}),
|
||||
).toEqual("tap");
|
||||
});
|
||||
|
||||
it("keeps selection intent once selection is active", () => {
|
||||
expect(
|
||||
classifyTerminalGestureIntent({
|
||||
status: "selecting",
|
||||
dx: 100,
|
||||
dy: 50,
|
||||
vx: 2,
|
||||
vy: 1,
|
||||
}),
|
||||
).toEqual("select");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveTerminalGestureReleaseAction", () => {
|
||||
it("focuses the terminal after a normal tap", () => {
|
||||
expect(
|
||||
resolveTerminalGestureReleaseAction({
|
||||
status: "pressing",
|
||||
didScroll: false,
|
||||
didNavigate: false,
|
||||
movedBeyondTapTolerance: false,
|
||||
pressDurationMs: 80,
|
||||
longPressMs: TERMINAL_GESTURE_LONG_PRESS_MS,
|
||||
scrollMode: "following",
|
||||
}),
|
||||
).toEqual("focus");
|
||||
});
|
||||
|
||||
it("focuses the terminal after a normal tap while scrolled", () => {
|
||||
expect(
|
||||
resolveTerminalGestureReleaseAction({
|
||||
status: "pressing",
|
||||
didScroll: false,
|
||||
didNavigate: false,
|
||||
movedBeyondTapTolerance: false,
|
||||
pressDurationMs: 80,
|
||||
longPressMs: TERMINAL_GESTURE_LONG_PRESS_MS,
|
||||
scrollMode: "scrolled",
|
||||
}),
|
||||
).toEqual("focus");
|
||||
});
|
||||
|
||||
it("starts selection after a long press", () => {
|
||||
expect(
|
||||
resolveTerminalGestureReleaseAction({
|
||||
status: "pressing",
|
||||
didScroll: false,
|
||||
didNavigate: false,
|
||||
movedBeyondTapTolerance: false,
|
||||
pressDurationMs: TERMINAL_GESTURE_LONG_PRESS_MS + 50,
|
||||
longPressMs: TERMINAL_GESTURE_LONG_PRESS_MS,
|
||||
scrollMode: "following",
|
||||
}),
|
||||
).toEqual("select");
|
||||
});
|
||||
|
||||
it("starts selection after a 500ms hold", () => {
|
||||
expect(
|
||||
resolveTerminalGestureReleaseAction({
|
||||
status: "pressing",
|
||||
didScroll: false,
|
||||
didNavigate: false,
|
||||
movedBeyondTapTolerance: false,
|
||||
pressDurationMs: 500,
|
||||
longPressMs: TERMINAL_GESTURE_LONG_PRESS_MS,
|
||||
scrollMode: "following",
|
||||
}),
|
||||
).toEqual("select");
|
||||
});
|
||||
|
||||
it("keeps a 400ms press as a tap", () => {
|
||||
expect(
|
||||
resolveTerminalGestureReleaseAction({
|
||||
status: "pressing",
|
||||
didScroll: false,
|
||||
didNavigate: false,
|
||||
movedBeyondTapTolerance: false,
|
||||
pressDurationMs: 400,
|
||||
longPressMs: TERMINAL_GESTURE_LONG_PRESS_MS,
|
||||
scrollMode: "following",
|
||||
}),
|
||||
).toEqual("focus");
|
||||
});
|
||||
|
||||
it("does nothing after a scroll gesture", () => {
|
||||
expect(
|
||||
resolveTerminalGestureReleaseAction({
|
||||
status: "pressing",
|
||||
didScroll: true,
|
||||
didNavigate: false,
|
||||
movedBeyondTapTolerance: true,
|
||||
pressDurationMs: 80,
|
||||
longPressMs: TERMINAL_GESTURE_LONG_PRESS_MS,
|
||||
scrollMode: "scrolled",
|
||||
}),
|
||||
).toEqual("none");
|
||||
});
|
||||
|
||||
it("does nothing after a navigation swipe", () => {
|
||||
expect(
|
||||
resolveTerminalGestureReleaseAction({
|
||||
status: "pressing",
|
||||
didScroll: false,
|
||||
didNavigate: true,
|
||||
movedBeyondTapTolerance: true,
|
||||
pressDurationMs: 80,
|
||||
longPressMs: TERMINAL_GESTURE_LONG_PRESS_MS,
|
||||
scrollMode: "following",
|
||||
}),
|
||||
).toEqual("none");
|
||||
});
|
||||
|
||||
it("does nothing while actively selecting", () => {
|
||||
expect(
|
||||
resolveTerminalGestureReleaseAction({
|
||||
status: "selecting",
|
||||
didScroll: false,
|
||||
didNavigate: false,
|
||||
movedBeyondTapTolerance: true,
|
||||
pressDurationMs: 80,
|
||||
longPressMs: TERMINAL_GESTURE_LONG_PRESS_MS,
|
||||
scrollMode: "following",
|
||||
}),
|
||||
).toEqual("none");
|
||||
});
|
||||
|
||||
it("clears an existing selection after a short tap", () => {
|
||||
expect(
|
||||
resolveTerminalGestureReleaseAction({
|
||||
status: "selecting",
|
||||
startedWithSelection: true,
|
||||
didScroll: false,
|
||||
didNavigate: false,
|
||||
movedBeyondTapTolerance: false,
|
||||
pressDurationMs: 80,
|
||||
longPressMs: TERMINAL_GESTURE_LONG_PRESS_MS,
|
||||
scrollMode: "following",
|
||||
}),
|
||||
).toEqual("clear");
|
||||
});
|
||||
|
||||
it("preserves a word selection created by the current long press", () => {
|
||||
expect(
|
||||
resolveTerminalGestureReleaseAction({
|
||||
status: "selecting",
|
||||
startedWithSelection: false,
|
||||
didScroll: false,
|
||||
didNavigate: false,
|
||||
movedBeyondTapTolerance: false,
|
||||
pressDurationMs: TERMINAL_GESTURE_LONG_PRESS_MS + 50,
|
||||
longPressMs: TERMINAL_GESTURE_LONG_PRESS_MS,
|
||||
scrollMode: "following",
|
||||
}),
|
||||
).toEqual("none");
|
||||
});
|
||||
|
||||
it("does not focus after an undecided fast drag", () => {
|
||||
expect(
|
||||
resolveTerminalGestureReleaseAction({
|
||||
status: "pressing",
|
||||
didScroll: false,
|
||||
didNavigate: false,
|
||||
movedBeyondTapTolerance: true,
|
||||
pressDurationMs: 80,
|
||||
longPressMs: TERMINAL_GESTURE_LONG_PRESS_MS,
|
||||
scrollMode: "following",
|
||||
}),
|
||||
).toEqual("none");
|
||||
});
|
||||
|
||||
it("does nothing from idle", () => {
|
||||
expect(
|
||||
resolveTerminalGestureReleaseAction({
|
||||
status: "idle",
|
||||
didScroll: false,
|
||||
didNavigate: false,
|
||||
movedBeyondTapTolerance: false,
|
||||
pressDurationMs: 80,
|
||||
longPressMs: TERMINAL_GESTURE_LONG_PRESS_MS,
|
||||
scrollMode: "following",
|
||||
}),
|
||||
).toEqual("none");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,108 @@
|
||||
export type TerminalGestureStatus = "idle" | "pressing" | "selecting";
|
||||
export type TerminalGestureIntent = "tap" | "pending" | "select" | "scroll";
|
||||
export type TerminalGestureScrollMode = "following" | "scrolled";
|
||||
|
||||
export interface TerminalGestureMoveInput {
|
||||
status: TerminalGestureStatus;
|
||||
dx: number;
|
||||
dy: number;
|
||||
vx: number;
|
||||
vy: number;
|
||||
elapsedMs?: number;
|
||||
}
|
||||
|
||||
export interface TerminalGestureReleaseInput {
|
||||
status: TerminalGestureStatus;
|
||||
startedWithSelection?: boolean;
|
||||
didScroll: boolean;
|
||||
didNavigate: boolean;
|
||||
movedBeyondTapTolerance: boolean;
|
||||
pressDurationMs: number;
|
||||
longPressMs: number;
|
||||
scrollMode: TerminalGestureScrollMode;
|
||||
}
|
||||
|
||||
export interface TerminalScrollGestureState {
|
||||
lastDy: number;
|
||||
rowRemainder: number;
|
||||
didScroll: boolean;
|
||||
}
|
||||
|
||||
export interface TerminalScrollGestureUpdate {
|
||||
state: TerminalScrollGestureState;
|
||||
rowDelta: number;
|
||||
}
|
||||
|
||||
export type TerminalGestureAction = "none" | "focus" | "select" | "clear";
|
||||
|
||||
export const TERMINAL_GESTURE_TAP_TOLERANCE_PX = 8;
|
||||
export const TERMINAL_GESTURE_LONG_PRESS_MS = 450;
|
||||
export const TERMINAL_GESTURE_VERTICAL_SCROLL_THRESHOLD_PX = 12;
|
||||
|
||||
export function classifyTerminalGestureIntent(
|
||||
input: TerminalGestureMoveInput,
|
||||
): TerminalGestureIntent {
|
||||
if (input.status === "selecting") {
|
||||
return "select";
|
||||
}
|
||||
|
||||
const absDx = Math.abs(input.dx);
|
||||
const absDy = Math.abs(input.dy);
|
||||
|
||||
if (absDy > TERMINAL_GESTURE_VERTICAL_SCROLL_THRESHOLD_PX && absDy > absDx) {
|
||||
return "scroll";
|
||||
}
|
||||
|
||||
if (Math.hypot(input.dx, input.dy) > TERMINAL_GESTURE_TAP_TOLERANCE_PX) {
|
||||
return "pending";
|
||||
}
|
||||
|
||||
return "tap";
|
||||
}
|
||||
|
||||
export function advanceTerminalScrollGesture(input: {
|
||||
state: TerminalScrollGestureState;
|
||||
currentDy: number;
|
||||
cellHeight: number;
|
||||
}): TerminalScrollGestureUpdate {
|
||||
const deltaY = input.currentDy - input.state.lastDy;
|
||||
const accumulatedRows = input.state.rowRemainder + deltaY;
|
||||
const rowDelta = Math.trunc(accumulatedRows / input.cellHeight);
|
||||
return {
|
||||
state: {
|
||||
lastDy: input.currentDy,
|
||||
rowRemainder: accumulatedRows - rowDelta * input.cellHeight,
|
||||
didScroll: input.state.didScroll || rowDelta !== 0,
|
||||
},
|
||||
rowDelta,
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveTerminalGestureReleaseAction(
|
||||
input: TerminalGestureReleaseInput,
|
||||
): TerminalGestureAction {
|
||||
if (input.didScroll || input.didNavigate) {
|
||||
return "none";
|
||||
}
|
||||
|
||||
if (input.status === "selecting") {
|
||||
if (!input.startedWithSelection) {
|
||||
return "none";
|
||||
}
|
||||
return input.movedBeyondTapTolerance ? "none" : "clear";
|
||||
}
|
||||
|
||||
if (input.status !== "pressing") {
|
||||
return "none";
|
||||
}
|
||||
|
||||
if (input.pressDurationMs >= input.longPressMs) {
|
||||
return "select";
|
||||
}
|
||||
|
||||
if (input.movedBeyondTapTolerance) {
|
||||
return "none";
|
||||
}
|
||||
|
||||
return "focus";
|
||||
}
|
||||
@@ -483,51 +483,3 @@ describe("native terminal selection", () => {
|
||||
expect(copied).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("endpoint dragging", () => {
|
||||
it.each([
|
||||
{
|
||||
endpoint: "start" as const,
|
||||
fixed: { row: 2, col: 9 },
|
||||
target: { row: 3, col: 2 },
|
||||
expected: { row: 3, col: 0 },
|
||||
},
|
||||
{
|
||||
endpoint: "end" as const,
|
||||
fixed: { row: 2, col: 0 },
|
||||
target: { row: 1, col: 7 },
|
||||
expected: { row: 1, col: 9 },
|
||||
},
|
||||
])(
|
||||
"preserves the fixed boundary across a row edge for $endpoint",
|
||||
({ endpoint, fixed, target, expected }) => {
|
||||
const selection = createTerminalSelectionModel();
|
||||
const bounds = { oldestRow: 0, newestRow: 10, coordinateEpoch: 1 };
|
||||
selection.begin({ coordinate: fixed, bounds });
|
||||
selection.update({ coordinate: fixed, bounds });
|
||||
selection.beginEndpointDrag(endpoint, 10);
|
||||
selection.update({ coordinate: target, bounds });
|
||||
expect(selection.getSnapshot().range?.[endpoint === "start" ? "start" : "end"]).toEqual(
|
||||
expected,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["start", "end"] as const)(
|
||||
"keeps the opposite endpoint fixed as %s crosses it",
|
||||
(endpoint) => {
|
||||
const selection = createTerminalSelectionModel();
|
||||
const bounds = { oldestRow: 0, newestRow: 10, coordinateEpoch: 1 };
|
||||
selection.begin({ coordinate: { row: 2, col: 2 }, bounds });
|
||||
selection.update({ coordinate: { row: 3, col: 4 }, bounds });
|
||||
selection.beginEndpointDrag(endpoint, 10);
|
||||
const coordinate = endpoint === "start" ? { row: 4, col: 5 } : { row: 1, col: 1 };
|
||||
selection.update({ coordinate, bounds });
|
||||
expect(selection.getSnapshot().range).toEqual(
|
||||
endpoint === "start"
|
||||
? { start: { row: 3, col: 5 }, end: coordinate, coordinateEpoch: 1 }
|
||||
: { start: coordinate, end: { row: 2, col: 1 }, coordinateEpoch: 1 },
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -25,7 +25,6 @@ export interface TerminalSelectionBounds {
|
||||
export interface TerminalSelectionModel {
|
||||
begin(input: TerminalSelectionUpdateInput): TerminalSelectionSnapshot;
|
||||
update(input: TerminalSelectionUpdateInput): TerminalSelectionSnapshot;
|
||||
beginEndpointDrag(endpoint: "start" | "end", cols: number): void;
|
||||
clear(): TerminalSelectionSnapshot;
|
||||
sync(input: TerminalSelectionSyncInput): TerminalSelectionSnapshot;
|
||||
getSnapshot(): TerminalSelectionSnapshot;
|
||||
@@ -253,7 +252,6 @@ export function resolveTerminalSelectionRects(
|
||||
|
||||
export function createTerminalSelectionModel(): TerminalSelectionModel {
|
||||
let state: TerminalSelectionState = { anchor: null, range: null };
|
||||
let drag: { endpoint: "start" | "end"; cols: number } | null = null;
|
||||
|
||||
function snapshot(): TerminalSelectionSnapshot {
|
||||
return { range: state.range };
|
||||
@@ -261,31 +259,18 @@ export function createTerminalSelectionModel(): TerminalSelectionModel {
|
||||
|
||||
function setSelection(input: TerminalSelectionUpdateInput): TerminalSelectionSnapshot {
|
||||
const coordinate = clampCoordinate(input.coordinate, input.bounds);
|
||||
const fixed = state.anchor ?? coordinate;
|
||||
let anchor = fixed;
|
||||
if (drag?.endpoint === "start" && compareCoordinates(coordinate, fixed) > 0) {
|
||||
anchor =
|
||||
fixed.col + 1 < drag.cols
|
||||
? { row: fixed.row, col: fixed.col + 1 }
|
||||
: { row: fixed.row + 1, col: 0 };
|
||||
} else if (drag?.endpoint === "end" && compareCoordinates(coordinate, fixed) < 0) {
|
||||
anchor =
|
||||
fixed.col > 0
|
||||
? { row: fixed.row, col: fixed.col - 1 }
|
||||
: { row: fixed.row - 1, col: drag.cols - 1 };
|
||||
}
|
||||
const anchor = state.anchor ?? coordinate;
|
||||
const range = normalizeTerminalSelection({
|
||||
anchor,
|
||||
focus: coordinate,
|
||||
coordinateEpoch: input.bounds.coordinateEpoch,
|
||||
});
|
||||
state = { anchor: fixed, range };
|
||||
state = { anchor, range };
|
||||
return snapshot();
|
||||
}
|
||||
|
||||
return {
|
||||
begin(input: TerminalSelectionUpdateInput): TerminalSelectionSnapshot {
|
||||
drag = null;
|
||||
const coordinate = clampCoordinate(input.coordinate, input.bounds);
|
||||
state = {
|
||||
anchor: coordinate,
|
||||
@@ -300,14 +285,7 @@ export function createTerminalSelectionModel(): TerminalSelectionModel {
|
||||
update(input: TerminalSelectionUpdateInput): TerminalSelectionSnapshot {
|
||||
return setSelection(input);
|
||||
},
|
||||
beginEndpointDrag(endpoint, cols) {
|
||||
if (state.range) {
|
||||
drag = { endpoint, cols };
|
||||
state = { ...state, anchor: state.range[endpoint === "start" ? "end" : "start"] };
|
||||
}
|
||||
},
|
||||
clear(): TerminalSelectionSnapshot {
|
||||
drag = null;
|
||||
state = { anchor: null, range: null };
|
||||
return snapshot();
|
||||
},
|
||||
@@ -315,7 +293,6 @@ export function createTerminalSelectionModel(): TerminalSelectionModel {
|
||||
if (!state.range || rangeIsSafe(state.range, input.bounds)) {
|
||||
return snapshot();
|
||||
}
|
||||
drag = null;
|
||||
state = { anchor: null, range: null };
|
||||
return snapshot();
|
||||
},
|
||||
|
||||
@@ -82,7 +82,6 @@ import {
|
||||
createTerminalResizeEvent,
|
||||
encodeTerminalOutput,
|
||||
TerminalEmulatorRuntime,
|
||||
type TerminalClipboard,
|
||||
} from "./terminal-emulator-runtime";
|
||||
|
||||
interface StubTerminal {
|
||||
@@ -639,97 +638,3 @@ describe("terminal-emulator-runtime", () => {
|
||||
expect(fitAndEmitResize).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("terminal-emulator-runtime clipboard shortcuts", () => {
|
||||
type KeyHandler = (event: KeyboardEvent) => boolean;
|
||||
|
||||
function createClipboard(available: boolean) {
|
||||
return {
|
||||
isAvailable: () => available,
|
||||
readText: vi.fn(async () => "clipboard text"),
|
||||
read: vi.fn(async () => []),
|
||||
writeText: vi.fn(async (_text: string) => undefined),
|
||||
} satisfies TerminalClipboard;
|
||||
}
|
||||
|
||||
function attachKeyHandler(input: { clipboard: TerminalClipboard; selection: string }) {
|
||||
const runtime = new TerminalEmulatorRuntime({ isMac: false }, input.clipboard);
|
||||
let handler: KeyHandler | null = null;
|
||||
const paste = vi.fn();
|
||||
runtime.attachKeyEventHandler({
|
||||
attachCustomKeyEventHandler: (next: KeyHandler) => {
|
||||
handler = next;
|
||||
},
|
||||
hasSelection: () => input.selection.length > 0,
|
||||
getSelection: () => input.selection,
|
||||
paste,
|
||||
input: vi.fn(),
|
||||
scrollToBottom: vi.fn(),
|
||||
});
|
||||
if (!handler) throw new Error("key handler was not attached");
|
||||
return { handler: handler as KeyHandler, paste };
|
||||
}
|
||||
|
||||
function ctrlKey(key: string) {
|
||||
const preventDefault = vi.fn();
|
||||
const event = {
|
||||
type: "keydown",
|
||||
key,
|
||||
isComposing: false,
|
||||
ctrlKey: true,
|
||||
shiftKey: false,
|
||||
altKey: false,
|
||||
metaKey: false,
|
||||
preventDefault,
|
||||
stopPropagation: vi.fn(),
|
||||
} as unknown as KeyboardEvent;
|
||||
return { event, preventDefault };
|
||||
}
|
||||
|
||||
it("leaves Ctrl+C with a selection to the native copy event without the Clipboard API", () => {
|
||||
const clipboard = createClipboard(false);
|
||||
const { handler } = attachKeyHandler({ clipboard, selection: "selected text" });
|
||||
const { event, preventDefault } = ctrlKey("c");
|
||||
|
||||
expect(handler(event)).toBe(false);
|
||||
expect(clipboard.writeText).not.toHaveBeenCalled();
|
||||
expect(preventDefault).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("leaves Ctrl+V to the native paste event without the Clipboard API", () => {
|
||||
const clipboard = createClipboard(false);
|
||||
const { handler, paste } = attachKeyHandler({ clipboard, selection: "" });
|
||||
const { event, preventDefault } = ctrlKey("v");
|
||||
|
||||
expect(handler(event)).toBe(false);
|
||||
expect(clipboard.readText).not.toHaveBeenCalled();
|
||||
expect(preventDefault).not.toHaveBeenCalled();
|
||||
expect(paste).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("lets xterm send ^C for Ctrl+C without a selection when the Clipboard API is missing", () => {
|
||||
const clipboard = createClipboard(false);
|
||||
const { handler } = attachKeyHandler({ clipboard, selection: "" });
|
||||
const { event, preventDefault } = ctrlKey("c");
|
||||
|
||||
expect(handler(event)).toBe(true);
|
||||
expect(clipboard.writeText).not.toHaveBeenCalled();
|
||||
expect(preventDefault).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("copies and pastes through the Clipboard API when it is available", async () => {
|
||||
const clipboard = createClipboard(true);
|
||||
const { handler, paste } = attachKeyHandler({ clipboard, selection: "selected text" });
|
||||
|
||||
const copy = ctrlKey("c");
|
||||
expect(handler(copy.event)).toBe(false);
|
||||
expect(clipboard.writeText).toHaveBeenCalledWith("selected text");
|
||||
expect(copy.preventDefault).not.toHaveBeenCalled();
|
||||
|
||||
const pasteKey = ctrlKey("v");
|
||||
expect(handler(pasteKey.event)).toBe(false);
|
||||
expect(pasteKey.preventDefault).toHaveBeenCalledTimes(1);
|
||||
expect(clipboard.readText).toHaveBeenCalledTimes(1);
|
||||
await vi.waitFor(() => expect(paste).toHaveBeenCalledWith("clipboard text"));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -182,26 +182,15 @@ function withOverviewRulerBorderHidden(theme: ITheme): ITheme {
|
||||
}
|
||||
|
||||
export interface TerminalClipboard {
|
||||
/** Whether the async Clipboard API is usable. Browsers omit it outside secure contexts. */
|
||||
isAvailable?(): boolean;
|
||||
readText(): Promise<string>;
|
||||
read(): Promise<readonly Pick<ClipboardItem, "types" | "getType">[]>;
|
||||
writeText(text: string): Promise<void>;
|
||||
}
|
||||
|
||||
function getBrowserClipboard(): Clipboard | undefined {
|
||||
return typeof navigator !== "undefined" ? navigator.clipboard : undefined;
|
||||
}
|
||||
|
||||
function rejectUnavailableClipboard(): Promise<never> {
|
||||
return Promise.reject(new Error("Clipboard API is unavailable"));
|
||||
}
|
||||
|
||||
const browserClipboard: TerminalClipboard = {
|
||||
isAvailable: () => !!getBrowserClipboard(),
|
||||
readText: () => getBrowserClipboard()?.readText() ?? rejectUnavailableClipboard(),
|
||||
read: () => getBrowserClipboard()?.read() ?? rejectUnavailableClipboard(),
|
||||
writeText: (text) => getBrowserClipboard()?.writeText(text) ?? rejectUnavailableClipboard(),
|
||||
readText: () => navigator.clipboard.readText(),
|
||||
read: () => navigator.clipboard.read(),
|
||||
writeText: (text) => navigator.clipboard.writeText(text),
|
||||
};
|
||||
|
||||
async function readClipboardImage(clipboard: TerminalClipboard): Promise<TerminalFile | null> {
|
||||
@@ -379,7 +368,22 @@ export class TerminalEmulatorRuntime {
|
||||
!event.altKey &&
|
||||
!event.metaKey
|
||||
) {
|
||||
return !this.handleCtrlClipboardShortcut(terminal, event);
|
||||
const key = event.key.toLowerCase();
|
||||
|
||||
// Ctrl+C: copy selection to clipboard if text is selected, otherwise let xterm send SIGINT
|
||||
if (key === "c" && terminal.hasSelection()) {
|
||||
void this.clipboard.writeText(terminal.getSelection());
|
||||
return false;
|
||||
}
|
||||
|
||||
// Ctrl+V: paste clipboard text, or the clipboard image when there is no text
|
||||
if (key === "v") {
|
||||
event.preventDefault();
|
||||
this.pasteClipboard(terminal);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
if (this.maybeSendMacEditingShortcut(terminal, event)) {
|
||||
@@ -428,36 +432,6 @@ export class TerminalEmulatorRuntime {
|
||||
});
|
||||
}
|
||||
|
||||
/** Returns true when a non-Mac Ctrl+C / Ctrl+V clipboard shortcut was handled. */
|
||||
private handleCtrlClipboardShortcut(
|
||||
terminal: Pick<Terminal, "hasSelection" | "getSelection" | "paste">,
|
||||
event: KeyboardEvent,
|
||||
): boolean {
|
||||
const key = event.key.toLowerCase();
|
||||
// Without the Clipboard API (e.g. plain http on a LAN address), the browser's native
|
||||
// copy/paste events still fire and xterm handles them, so leave the default action.
|
||||
const clipboardAvailable = this.clipboard.isAvailable?.() ?? true;
|
||||
|
||||
// Ctrl+C: copy selection to clipboard if text is selected, otherwise let xterm send SIGINT
|
||||
if (key === "c" && terminal.hasSelection()) {
|
||||
if (clipboardAvailable) {
|
||||
void this.clipboard.writeText(terminal.getSelection());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Ctrl+V: paste clipboard text, or the clipboard image when there is no text
|
||||
if (key === "v") {
|
||||
if (clipboardAvailable) {
|
||||
event.preventDefault();
|
||||
this.pasteClipboard(terminal);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private handleFindShortcut(event: KeyboardEvent): boolean {
|
||||
if (!isFindShortcut(event, this.options) || !this.callbacks.onFindRequest) return false;
|
||||
event.preventDefault();
|
||||
|
||||
@@ -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/creation-status.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/daemon-e2e/terminal-worker-lifecycle.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 src/server/plugins/usage-sources.e2e.test.ts src/server/plugins/lifecycle.e2e.test.ts src/server/connected-hosts/hosts.e2e.test.ts src/server/owned-subscriptions.e2e.test.ts && vitest run --maxWorkers=1 src/server/agent/providers/omp/history.e2e.test.ts src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts -t \"merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history\"",
|
||||
"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/terminal-worker-lifecycle.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 src/server/plugins/usage-sources.e2e.test.ts src/server/plugins/lifecycle.e2e.test.ts src/server/connected-hosts/hosts.e2e.test.ts src/server/owned-subscriptions.e2e.test.ts && vitest run --maxWorkers=1 src/server/agent/providers/omp/history.e2e.test.ts src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts -t \"merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history\"",
|
||||
"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",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { copyFile, mkdir } from "node:fs/promises";
|
||||
import { mkdir } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
@@ -27,10 +27,4 @@ for (const directory of ["", "v2/"]) {
|
||||
target: "es2022",
|
||||
outfile: outputPath,
|
||||
});
|
||||
if (directory === "v2/") {
|
||||
await copyFile(
|
||||
new URL("../src/server/agent/providers/opencode/v2/state.mjs", import.meta.url),
|
||||
path.join(path.dirname(outputPath), "state.mjs"),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1220,74 +1220,6 @@ test("orders buffered pre-steer output before an immediately accepted steer", as
|
||||
}
|
||||
});
|
||||
|
||||
test("a steer the provider names without echoing it can be rewound to", async () => {
|
||||
// Claude takes a steered message into the running turn without echoing it back as a user
|
||||
// message, so the id it minted for the message reaches the manager only through the admission.
|
||||
class SilentSteeringSession extends SteeringTestSession {
|
||||
override readonly capabilities = {
|
||||
...TEST_CAPABILITIES,
|
||||
supportsRewindFiles: true,
|
||||
};
|
||||
rewindMessageIds: string[] = [];
|
||||
|
||||
override async steerActiveTurn(
|
||||
_prompt: AgentPromptInput,
|
||||
options: import("./agent-sdk-types.js").SteerActiveTurnOptions,
|
||||
): Promise<import("./agent-sdk-types.js").SteerResult> {
|
||||
if (options.expectedTurnId !== `active-turn-${this.startCount}`) {
|
||||
return { status: "unavailable" };
|
||||
}
|
||||
return { status: "accepted", providerMessageId: `provider-${options.clientMessageId}` };
|
||||
}
|
||||
|
||||
override async revertFiles({ messageId }: { messageId: string }): Promise<void> {
|
||||
this.rewindMessageIds.push(messageId);
|
||||
}
|
||||
}
|
||||
const session = new SilentSteeringSession({ provider: "codex", cwd: process.cwd() });
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-steer-rewind-"));
|
||||
const manager = new AgentManager({
|
||||
clients: {
|
||||
codex: new (class extends TestAgentClient {
|
||||
override async createSession(): Promise<AgentSession> {
|
||||
return session;
|
||||
}
|
||||
})(),
|
||||
},
|
||||
logger,
|
||||
});
|
||||
let agentId: string | null = null;
|
||||
try {
|
||||
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
agentId = agent.id;
|
||||
const run = manager.streamAgent(agent.id, "initial");
|
||||
void (async () => {
|
||||
for await (const _event of run) {
|
||||
}
|
||||
})();
|
||||
await manager.waitForAgentRunStart(agent.id);
|
||||
|
||||
await expect(
|
||||
manager.steerAgentRun(agent.id, "steered", { clientMessageId: "steer-client" }),
|
||||
).resolves.toMatchObject({ status: "accepted" });
|
||||
const row = manager
|
||||
.fetchTimeline(agent.id, { limit: 0 })
|
||||
.rows.find((candidate) => candidate.item.type === "user_message");
|
||||
expect(row).toMatchObject({
|
||||
providerMessageId: "provider-steer-client",
|
||||
item: { text: "steered", clientMessageId: "steer-client" },
|
||||
});
|
||||
|
||||
await manager.rewind(agent.id, "steer-client", "files");
|
||||
expect(session.rewindMessageIds).toEqual(["provider-steer-client"]);
|
||||
} finally {
|
||||
if (agentId) await manager.closeAgent(agentId).catch(() => undefined);
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("orders a concurrent replacement after a pending accepted steer", async () => {
|
||||
const entered = deferred<void>();
|
||||
const release = deferred<void>();
|
||||
|
||||
@@ -3029,13 +3029,7 @@ export class AgentManager {
|
||||
expectedTurnId,
|
||||
});
|
||||
if (admission.status === "accepted") {
|
||||
await this.recordAcceptedSteer(
|
||||
agent,
|
||||
prompt,
|
||||
options?.clientMessageId,
|
||||
expectedTurnId,
|
||||
admission.providerMessageId,
|
||||
);
|
||||
await this.recordAcceptedSteer(agent, prompt, options?.clientMessageId, expectedTurnId);
|
||||
}
|
||||
return admission;
|
||||
});
|
||||
@@ -3068,13 +3062,7 @@ export class AgentManager {
|
||||
expectedTurnId,
|
||||
});
|
||||
if (admission.status === "accepted") {
|
||||
await this.recordAcceptedSteer(
|
||||
agent,
|
||||
prompt,
|
||||
options?.clientMessageId,
|
||||
expectedTurnId,
|
||||
admission.providerMessageId,
|
||||
);
|
||||
await this.recordAcceptedSteer(agent, prompt, options?.clientMessageId, expectedTurnId);
|
||||
}
|
||||
return admission;
|
||||
})
|
||||
@@ -3179,7 +3167,6 @@ export class AgentManager {
|
||||
prompt: AgentPromptInput,
|
||||
clientMessageId: string | undefined,
|
||||
expectedTurnId: string,
|
||||
providerMessageId: string | undefined,
|
||||
): Promise<void> {
|
||||
if (!clientMessageId) {
|
||||
return;
|
||||
@@ -3187,7 +3174,6 @@ export class AgentManager {
|
||||
this.recordSubmittedPrompt(agent, prompt, clientMessageId, "accepted", {
|
||||
messageId: clientMessageId,
|
||||
turnId: expectedTurnId,
|
||||
...(providerMessageId ? { providerMessageId } : {}),
|
||||
});
|
||||
this.emitState(agent);
|
||||
}
|
||||
@@ -3519,10 +3505,6 @@ export class AgentManager {
|
||||
"agent.rewind.complete",
|
||||
);
|
||||
} catch (error) {
|
||||
// Native rewind can commit a fork before history refresh fails. Recovery
|
||||
// must resume that latest handle rather than the abandoned conversation.
|
||||
this.refreshSessionPersistence(agent);
|
||||
await this.persistSnapshot(agent);
|
||||
this.logger.warn(
|
||||
{ err: error, agentId, provider: agent.provider, messageId, mode },
|
||||
"agent.rewind.failed",
|
||||
|
||||
@@ -208,11 +208,7 @@ export interface AgentSteerOptions extends AgentRunOptions {
|
||||
clearPendingPermissions?: boolean;
|
||||
}
|
||||
|
||||
// providerMessageId names the steered message in the provider's own history, when the provider
|
||||
// mints one. Rewinding to the message needs it.
|
||||
export type SteerResult =
|
||||
| { status: "accepted"; providerMessageId?: string }
|
||||
| { status: "unavailable" };
|
||||
export type SteerResult = { status: "accepted" } | { status: "unavailable" };
|
||||
|
||||
export interface SteerActiveTurnOptions extends AgentSteerOptions {
|
||||
expectedTurnId: string;
|
||||
@@ -697,7 +693,6 @@ export interface AgentSession {
|
||||
requestId: string,
|
||||
response: AgentPermissionResponse,
|
||||
): Promise<AgentPermissionResult | void>;
|
||||
/** Null until a new provider process could resume this session; see docs/providers.md. */
|
||||
describePersistence(): AgentPersistenceHandle | null;
|
||||
/**
|
||||
* Resolve once every foreground turn that predates this call can no longer run or become active.
|
||||
|
||||
@@ -53,7 +53,6 @@ const CAPABILITIES = [
|
||||
interface ProviderHarnessOptions {
|
||||
capabilities?: ProviderConnection["capabilities"];
|
||||
completeTurn?: boolean;
|
||||
closeAcknowledgementOnly?: boolean;
|
||||
openChildren?: (rootSessionId: string, emit: (event: ProviderEvent) => void) => void;
|
||||
handleInput?: (input: ProviderInput, emit: (event: ProviderEvent) => void) => Promise<boolean>;
|
||||
}
|
||||
@@ -209,7 +208,6 @@ function createProviderHarness(options: ProviderHarnessOptions = {}) {
|
||||
}
|
||||
if (input.type === "session.close") {
|
||||
emit({ type: "session.closed", sessionId: input.sessionId });
|
||||
if (options.closeAcknowledgementOnly) return;
|
||||
}
|
||||
if ("requestId" in input) {
|
||||
emit({ type: "request.completed", requestId: input.requestId });
|
||||
@@ -248,572 +246,6 @@ function eventsOfType(events: AgentStreamEvent[], type: AgentStreamEvent["type"]
|
||||
return events.filter((event) => event.type === type);
|
||||
}
|
||||
|
||||
function createRewindProviderHarness(
|
||||
options: {
|
||||
reuseAnswerId?: boolean;
|
||||
forkOnRevert?: boolean;
|
||||
handleInput?: ProviderHarnessOptions["handleInput"];
|
||||
} = {},
|
||||
) {
|
||||
const nativeMessages: string[] = [];
|
||||
let originalMessages: string[] | null = null;
|
||||
const harness = createProviderHarness({
|
||||
closeAcknowledgementOnly: true,
|
||||
capabilities: [
|
||||
...CAPABILITIES,
|
||||
"session.revert.conversation",
|
||||
"session.revert.files",
|
||||
"session.revert.both",
|
||||
],
|
||||
async handleInput(input, emit) {
|
||||
if (await options.handleInput?.(input, emit)) return true;
|
||||
if (input.type === "session.open" && input.history === "replay") {
|
||||
emit({
|
||||
type: "session.opened",
|
||||
requestId: input.requestId,
|
||||
sessionId: input.sessionId,
|
||||
capabilities: [
|
||||
...CAPABILITIES,
|
||||
"session.revert.conversation",
|
||||
"session.revert.files",
|
||||
"session.revert.both",
|
||||
],
|
||||
restoration: "core",
|
||||
persistence: input.persistence ?? { version: 1, data: { token: "root" } },
|
||||
cwd: input.config.cwd,
|
||||
});
|
||||
const messages =
|
||||
options.forkOnRevert &&
|
||||
(input.persistence?.data as { token?: string })?.token === "root" &&
|
||||
originalMessages
|
||||
? originalMessages
|
||||
: nativeMessages;
|
||||
for (const [index, text] of messages.entries()) {
|
||||
emit({
|
||||
type: "timeline.item",
|
||||
sessionId: input.sessionId,
|
||||
item: { type: "user_message", id: `user-${text}`, text, revertToken: text },
|
||||
});
|
||||
emit({
|
||||
type: "timeline.item",
|
||||
sessionId: input.sessionId,
|
||||
item: {
|
||||
type: "assistant_message",
|
||||
id: options.reuseAnswerId ? `answer-${index + 1}` : `answer-${text}`,
|
||||
text: `Reply ${text}`,
|
||||
},
|
||||
});
|
||||
}
|
||||
emit({ type: "session.ready", requestId: input.requestId, sessionId: input.sessionId });
|
||||
return true;
|
||||
}
|
||||
if (input.type === "session.prompt") {
|
||||
if (input.prompt.input.type !== "message") throw new Error("Expected a message");
|
||||
const text = input.prompt.input.content
|
||||
.flatMap((part) => (part.type === "text" ? [part.text] : []))
|
||||
.join("");
|
||||
nativeMessages.push(text);
|
||||
const turnId = `turn-${text}`;
|
||||
emit({
|
||||
type: "session.prompt_result",
|
||||
sessionId: input.sessionId,
|
||||
clientMessageId: input.prompt.clientMessageId,
|
||||
result: { type: "turn", turnId },
|
||||
});
|
||||
emit({ type: "session.turn", sessionId: input.sessionId, turnId, state: "started" });
|
||||
emit({
|
||||
type: "timeline.item",
|
||||
sessionId: input.sessionId,
|
||||
item: {
|
||||
type: "user_message",
|
||||
id: `user-${text}`,
|
||||
text,
|
||||
clientMessageId: input.prompt.clientMessageId,
|
||||
revertToken: text,
|
||||
},
|
||||
});
|
||||
emit({
|
||||
type: "timeline.item",
|
||||
sessionId: input.sessionId,
|
||||
item: {
|
||||
type: "assistant_message",
|
||||
id: options.reuseAnswerId ? `answer-${nativeMessages.length}` : `answer-${text}`,
|
||||
text: `Reply ${text}`,
|
||||
},
|
||||
});
|
||||
emit({ type: "session.turn", sessionId: input.sessionId, turnId, state: "completed" });
|
||||
return true;
|
||||
}
|
||||
if (input.type === "session.revert") {
|
||||
if (options.forkOnRevert && input.scope !== "files") {
|
||||
originalMessages = [...nativeMessages];
|
||||
emit({
|
||||
type: "session.persistence",
|
||||
sessionId: input.sessionId,
|
||||
persistence: { version: 1, data: { token: "fork" } },
|
||||
});
|
||||
}
|
||||
if (input.scope !== "files")
|
||||
nativeMessages.splice(nativeMessages.indexOf(String(input.token)));
|
||||
emit({ type: "request.completed", requestId: input.requestId });
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
});
|
||||
return { ...harness, nativeMessages };
|
||||
}
|
||||
|
||||
async function withRewindAgent(
|
||||
run: (context: {
|
||||
manager: AgentManager;
|
||||
agentId: string;
|
||||
nativeMessages: string[];
|
||||
messages: () => string[];
|
||||
}) => Promise<void>,
|
||||
options: Parameters<typeof createRewindProviderHarness>[0] = {},
|
||||
) {
|
||||
const harness = createRewindProviderHarness(options);
|
||||
const logger = createTestLogger();
|
||||
const registry = new PluginAgentClientRegistry(logger);
|
||||
registry.replace([harness.registration]);
|
||||
const manager = new AgentManager({
|
||||
logger,
|
||||
clients: registry.clients(),
|
||||
providerDefinitions: registry.definitions(),
|
||||
});
|
||||
const agent = await manager.createAgent(
|
||||
{ provider: harness.registration.id, cwd: tmpdir() },
|
||||
undefined,
|
||||
{ workspaceId: undefined },
|
||||
);
|
||||
const messages = () =>
|
||||
manager
|
||||
.getTimeline(agent.id)
|
||||
.flatMap((item) =>
|
||||
item.type === "user_message" || item.type === "assistant_message" ? [item.text] : [],
|
||||
);
|
||||
try {
|
||||
await manager.runAgent(agent.id, "A", { clientMessageId: "client-A" });
|
||||
await manager.runAgent(agent.id, "B", { clientMessageId: "client-B" });
|
||||
await manager.runAgent(agent.id, "C", { clientMessageId: "client-C" });
|
||||
expect(messages()).toEqual(["A", "Reply A", "B", "Reply B", "C", "Reply C"]);
|
||||
await run({ manager, agentId: agent.id, nativeMessages: harness.nativeMessages, messages });
|
||||
} finally {
|
||||
await manager.closeAgent(agent.id);
|
||||
await registry.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
test("conversation rewind discards withdrawn plugin turns before and after a replacement prompt", async () => {
|
||||
await withRewindAgent(async ({ manager, agentId, nativeMessages, messages }) => {
|
||||
await manager.rewind(agentId, "user-B", "conversation");
|
||||
const afterRewind = messages();
|
||||
expect(nativeMessages).toEqual(["A"]);
|
||||
await manager.runAgent(agentId, "D", { clientMessageId: "client-D" });
|
||||
const afterReplacement = messages();
|
||||
expect(nativeMessages).toEqual(["A", "D"]);
|
||||
expect({ afterRewind, afterReplacement }).toEqual({
|
||||
afterRewind: ["A", "Reply A"],
|
||||
afterReplacement: ["A", "Reply A", "D", "Reply D"],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test("file-only plugin rewind preserves the conversation before and after a replacement prompt", async () => {
|
||||
await withRewindAgent(async ({ manager, agentId, nativeMessages, messages }) => {
|
||||
await manager.rewind(agentId, "user-B", "files");
|
||||
expect(nativeMessages).toEqual(["A", "B", "C"]);
|
||||
expect(messages()).toEqual(["A", "Reply A", "B", "Reply B", "C", "Reply C"]);
|
||||
await manager.runAgent(agentId, "D", { clientMessageId: "client-D" });
|
||||
expect(messages()).toEqual(["A", "Reply A", "B", "Reply B", "C", "Reply C", "D", "Reply D"]);
|
||||
});
|
||||
});
|
||||
|
||||
test("plugin rewind restores translation state when a replacement reuses a discarded item id", async () => {
|
||||
const harness = createRewindProviderHarness({ reuseAnswerId: true });
|
||||
const registry = new PluginAgentClientRegistry(createTestLogger());
|
||||
registry.replace([harness.registration]);
|
||||
const client = registry.clients()[harness.registration.id]!;
|
||||
const session = await client.createSession({ provider: harness.registration.id, cwd: tmpdir() });
|
||||
const live: AgentStreamEvent[] = [];
|
||||
try {
|
||||
await session.run("A");
|
||||
await session.run("B");
|
||||
session.subscribe((event) => live.push(event));
|
||||
await session.revertConversation!({ messageId: "user-B" });
|
||||
live.length = 0;
|
||||
await session.run("B revised");
|
||||
const assistant = live.flatMap((event) =>
|
||||
event.type === "timeline" && event.item.type === "assistant_message" ? [event.item.text] : [],
|
||||
);
|
||||
expect(harness.nativeMessages).toEqual(["A", "B revised"]);
|
||||
expect(assistant).toEqual(["Reply B revised"]);
|
||||
} finally {
|
||||
await session.close();
|
||||
await registry.shutdown();
|
||||
}
|
||||
});
|
||||
|
||||
async function withPluginRewindSession(
|
||||
options: Parameters<typeof createRewindProviderHarness>[0],
|
||||
run: (
|
||||
session: Awaited<ReturnType<AgentClient["createSession"]>>,
|
||||
harness: ReturnType<typeof createRewindProviderHarness>,
|
||||
) => Promise<void>,
|
||||
) {
|
||||
const harness = createRewindProviderHarness(options);
|
||||
const registry = new PluginAgentClientRegistry(createTestLogger());
|
||||
registry.replace([harness.registration]);
|
||||
const client = registry.clients()[harness.registration.id]!;
|
||||
const session = await client.createSession({ provider: harness.registration.id, cwd: tmpdir() });
|
||||
try {
|
||||
await session.run("A");
|
||||
await session.run("B");
|
||||
await session.run("C");
|
||||
await run(session, harness);
|
||||
} finally {
|
||||
await session.close();
|
||||
await registry.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
async function pluginMessages(session: Awaited<ReturnType<AgentClient["createSession"]>>) {
|
||||
const events = await Array.fromAsync(session.streamHistory());
|
||||
return events.flatMap((event) =>
|
||||
event.type === "timeline" &&
|
||||
(event.item.type === "user_message" || event.item.type === "assistant_message")
|
||||
? [event.item.text]
|
||||
: [],
|
||||
);
|
||||
}
|
||||
|
||||
test("combined plugin rewind replays the retained native branch", async () => {
|
||||
await withPluginRewindSession({}, async (session) => {
|
||||
await session.revertBoth!({ messageId: "user-B" });
|
||||
expect(await pluginMessages(session)).toEqual(["A", "Reply A"]);
|
||||
await session.revertConversation!({ messageId: "user-A" });
|
||||
expect(await pluginMessages(session)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
test("plugin rewind resumes the latest persistence rather than the original handle", async () => {
|
||||
await withPluginRewindSession(
|
||||
{
|
||||
handleInput: async (input, emit) => {
|
||||
if (input.type === "session.revert")
|
||||
emit({
|
||||
type: "session.persistence",
|
||||
sessionId: input.sessionId,
|
||||
persistence: { version: 1, data: { token: "fork" } },
|
||||
});
|
||||
return false;
|
||||
},
|
||||
},
|
||||
async (session, harness) => {
|
||||
await session.revertConversation!({ messageId: "user-B" });
|
||||
expect(harness.inputs.findLast((input) => input.type === "session.open")).toMatchObject({
|
||||
persistence: { version: 1, data: { token: "fork" } },
|
||||
history: "replay",
|
||||
});
|
||||
expect(await pluginMessages(session)).toEqual(["A", "Reply A"]);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test("failed native plugin rewind preserves history and does not reopen", async () => {
|
||||
await withPluginRewindSession(
|
||||
{
|
||||
handleInput: async (input, emit) => {
|
||||
if (input.type !== "session.revert") return false;
|
||||
emit({
|
||||
type: "request.failed",
|
||||
requestId: input.requestId,
|
||||
error: { message: "native rewind failed" },
|
||||
});
|
||||
return true;
|
||||
},
|
||||
},
|
||||
async (session, harness) => {
|
||||
await expect(session.revertConversation!({ messageId: "user-B" })).rejects.toThrow(
|
||||
"native rewind failed",
|
||||
);
|
||||
expect(await pluginMessages(session)).toEqual([
|
||||
"A",
|
||||
"Reply A",
|
||||
"B",
|
||||
"Reply B",
|
||||
"C",
|
||||
"Reply C",
|
||||
]);
|
||||
expect(harness.inputs.filter((input) => input.type === "session.open")).toHaveLength(1);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test("failed plugin rewind replay blocks prompts until retry without repeating native rewind", async () => {
|
||||
let failReplay = true;
|
||||
await withPluginRewindSession(
|
||||
{
|
||||
handleInput: async (input, emit) => {
|
||||
if (input.type !== "session.open" || input.history !== "replay" || !failReplay)
|
||||
return false;
|
||||
failReplay = false;
|
||||
emit({
|
||||
type: "request.failed",
|
||||
requestId: input.requestId,
|
||||
error: { message: "replay failed" },
|
||||
});
|
||||
return true;
|
||||
},
|
||||
},
|
||||
async (session, harness) => {
|
||||
await expect(session.revertConversation!({ messageId: "user-B" })).rejects.toThrow(
|
||||
"replay failed",
|
||||
);
|
||||
await expect(session.run("D")).rejects.toThrow("Retry the rewind or reload");
|
||||
await session.revertConversation!({ messageId: "user-B" });
|
||||
await session.run("D");
|
||||
expect(await pluginMessages(session)).toEqual(["A", "Reply A", "D", "Reply D"]);
|
||||
expect(harness.inputs.filter((input) => input.type === "session.revert")).toHaveLength(1);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test("retrying a failed plugin rewind replay replaces the manager timeline before prompting", async () => {
|
||||
let failReplay = true;
|
||||
await withRewindAgent(
|
||||
async ({ manager, agentId, messages }) => {
|
||||
await expect(manager.rewind(agentId, "user-B", "conversation")).rejects.toThrow(
|
||||
"replay failed",
|
||||
);
|
||||
await expect(manager.runAgent(agentId, "D")).rejects.toThrow("Retry the rewind or reload");
|
||||
await manager.rewind(agentId, "user-B", "conversation");
|
||||
expect(messages()).toEqual(["A", "Reply A"]);
|
||||
await manager.runAgent(agentId, "D");
|
||||
expect(messages()).toEqual(["A", "Reply A", "D", "Reply D"]);
|
||||
},
|
||||
{
|
||||
handleInput: async (input, emit) => {
|
||||
if (input.type !== "session.open" || input.history !== "replay" || !failReplay)
|
||||
return false;
|
||||
failReplay = false;
|
||||
emit({
|
||||
type: "request.failed",
|
||||
requestId: input.requestId,
|
||||
error: { message: "replay failed" },
|
||||
});
|
||||
return true;
|
||||
},
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test("reload after failed plugin rewind replay resumes the committed fork", async () => {
|
||||
let failReplay = true;
|
||||
await withRewindAgent(
|
||||
async ({ manager, agentId, messages }) => {
|
||||
await expect(manager.rewind(agentId, "user-B", "conversation")).rejects.toThrow(
|
||||
"replay failed",
|
||||
);
|
||||
await manager.reloadAgentSession(agentId, undefined, { rehydrateFromDisk: true });
|
||||
await manager.hydrateTimelineFromProvider(agentId, { force: true });
|
||||
expect(messages()).toEqual(["A", "Reply A"]);
|
||||
},
|
||||
{
|
||||
forkOnRevert: true,
|
||||
handleInput: async (input, emit) => {
|
||||
if (input.type === "session.close") {
|
||||
emit({ type: "request.completed", requestId: input.requestId });
|
||||
return true;
|
||||
}
|
||||
if (input.type !== "session.open" || input.history !== "replay" || !failReplay)
|
||||
return false;
|
||||
failReplay = false;
|
||||
emit({
|
||||
type: "request.failed",
|
||||
requestId: input.requestId,
|
||||
error: { message: "replay failed" },
|
||||
});
|
||||
return true;
|
||||
},
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test("closing during plugin rewind replay closes each native binding once", async () => {
|
||||
let opened!: () => void;
|
||||
let release!: () => void;
|
||||
const replayStarted = new Promise<void>((resolve) => {
|
||||
opened = resolve;
|
||||
});
|
||||
const replayAllowed = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
await withPluginRewindSession(
|
||||
{
|
||||
handleInput: async (input) => {
|
||||
if (input.type === "session.open" && input.history === "replay") {
|
||||
opened();
|
||||
await replayAllowed;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
},
|
||||
async (session, harness) => {
|
||||
const rewind = session.revertConversation!({ messageId: "user-B" });
|
||||
await replayStarted;
|
||||
const closing = session.close();
|
||||
release();
|
||||
await Promise.all([rewind, closing]);
|
||||
const closes = harness.inputs.flatMap((input) =>
|
||||
input.type === "session.close" ? [input.sessionId] : [],
|
||||
);
|
||||
expect(closes).toHaveLength(2);
|
||||
expect(new Set(closes).size).toBe(2);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test("plugin rewind retries a failed close before reopening the native writer", async () => {
|
||||
let failClose = true;
|
||||
await withPluginRewindSession(
|
||||
{
|
||||
handleInput: async (input, emit) => {
|
||||
if (input.type !== "session.close" || !failClose) return false;
|
||||
failClose = false;
|
||||
emit({
|
||||
type: "request.failed",
|
||||
requestId: input.requestId,
|
||||
error: { message: "close failed" },
|
||||
});
|
||||
return true;
|
||||
},
|
||||
},
|
||||
async (session, harness) => {
|
||||
await expect(session.revertConversation!({ messageId: "user-B" })).rejects.toThrow(
|
||||
"close failed",
|
||||
);
|
||||
expect(harness.inputs.filter((input) => input.type === "session.open")).toHaveLength(1);
|
||||
expect(await pluginMessages(session)).toEqual(["A", "Reply A"]);
|
||||
expect(harness.inputs.filter((input) => input.type === "session.revert")).toHaveLength(1);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test("plugin rewind retries permission settlement before retiring its session", async () => {
|
||||
let failPermission = true;
|
||||
await withPluginRewindSession(
|
||||
{
|
||||
handleInput: async (input) => {
|
||||
if (input.type !== "session.permission" || !failPermission) return false;
|
||||
failPermission = false;
|
||||
throw new Error("permission delivery failed");
|
||||
},
|
||||
},
|
||||
async (session, harness) => {
|
||||
const opened = harness.inputs.find((input) => input.type === "session.open")!;
|
||||
if (opened.type !== "session.open") throw new Error("Missing root");
|
||||
harness.emit({
|
||||
type: "session.permission",
|
||||
sessionId: opened.sessionId,
|
||||
request: { id: "pending", name: "tool", kind: "tool" },
|
||||
});
|
||||
await expect(session.revertConversation!({ messageId: "user-B" })).rejects.toThrow(
|
||||
"permission delivery failed",
|
||||
);
|
||||
expect(session.getPendingPermissions()).toHaveLength(1);
|
||||
expect(harness.inputs.filter((input) => input.type === "session.close")).toHaveLength(0);
|
||||
expect(await pluginMessages(session)).toEqual(["A", "Reply A"]);
|
||||
expect(session.getPendingPermissions()).toEqual([]);
|
||||
expect(harness.inputs.filter((input) => input.type === "session.permission")).toHaveLength(2);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test("plugin rewind replaces child listeners and settles old pending permissions", async () => {
|
||||
await withPluginRewindSession({}, async (session, harness) => {
|
||||
const root = harness.inputs.find((input) => input.type === "session.open")!;
|
||||
if (root.type !== "session.open") throw new Error("Missing root");
|
||||
harness.emit({
|
||||
type: "session.permission",
|
||||
sessionId: root.sessionId,
|
||||
request: { id: "old-permission", name: "tool", kind: "tool", title: "Run tool" },
|
||||
});
|
||||
expect(session.getPendingPermissions()).toHaveLength(1);
|
||||
await session.revertConversation!({ messageId: "user-B" });
|
||||
expect(session.getPendingPermissions()).toEqual([]);
|
||||
expect(harness.inputs).toContainEqual(
|
||||
expect.objectContaining({
|
||||
type: "session.permission",
|
||||
permissionId: "old-permission",
|
||||
response: { behavior: "deny", message: "Session replaced after rewind" },
|
||||
}),
|
||||
);
|
||||
harness.emit({
|
||||
type: "timeline.item",
|
||||
sessionId: "child-1",
|
||||
item: { type: "assistant_message", id: "child-message", text: "Discarded child update" },
|
||||
});
|
||||
const history = await Array.fromAsync(session.streamHistory());
|
||||
expect(history.filter((event) => event.type === "provider_subagent")).toEqual([]);
|
||||
const reopened = harness.inputs.findLast((input) => input.type === "session.open")!;
|
||||
if (reopened.type !== "session.open") throw new Error("Missing reopened root");
|
||||
harness.emit({
|
||||
type: "session.opened",
|
||||
sessionId: "child-1",
|
||||
parentSessionId: reopened.sessionId,
|
||||
capabilities: [],
|
||||
restoration: "parent",
|
||||
cwd: tmpdir(),
|
||||
});
|
||||
harness.emit({
|
||||
type: "timeline.item",
|
||||
sessionId: "child-1",
|
||||
item: { type: "assistant_message", id: "child-message", text: "New child reply" },
|
||||
});
|
||||
const next = await Array.fromAsync(session.streamHistory());
|
||||
expect(next).toContainEqual(
|
||||
expect.objectContaining({
|
||||
type: "provider_subagent",
|
||||
event: expect.objectContaining({
|
||||
type: "timeline",
|
||||
item: expect.objectContaining({ text: "New child reply" }),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
test("nonpersisted plugin sessions reject conversation rewind before native mutation", async () => {
|
||||
await withPluginRewindSession(
|
||||
{
|
||||
handleInput: async (input, emit) => {
|
||||
if (input.type !== "session.open") return false;
|
||||
emit({
|
||||
type: "session.opened",
|
||||
requestId: input.requestId,
|
||||
sessionId: input.sessionId,
|
||||
capabilities: [...CAPABILITIES, "session.revert.conversation", "session.revert.files"],
|
||||
restoration: "core",
|
||||
cwd: input.config.cwd,
|
||||
});
|
||||
emit({ type: "session.ready", requestId: input.requestId, sessionId: input.sessionId });
|
||||
return true;
|
||||
},
|
||||
},
|
||||
async (session, harness) => {
|
||||
expect(session.capabilities.supportsRewindConversation).toBe(false);
|
||||
await expect(session.revertConversation!({ messageId: "user-B" })).rejects.toThrow(
|
||||
"requires session persistence",
|
||||
);
|
||||
expect(harness.inputs.filter((input) => input.type === "session.revert")).toEqual([]);
|
||||
await session.revertFiles!({ messageId: "user-B" });
|
||||
expect(harness.nativeMessages).toEqual(["A", "B", "C"]);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
function openNestedChildren(rootSessionId: string, emit: (event: ProviderEvent) => void) {
|
||||
for (const [sessionId, parentSessionId] of [
|
||||
["a", rootSessionId],
|
||||
|
||||
@@ -603,7 +603,6 @@ class ProviderRuntimeSession {
|
||||
>();
|
||||
private readonly activeTurnIds = new Set<string>();
|
||||
private terminal = false;
|
||||
private closePromise: Promise<void> | null = null;
|
||||
config: ProviderConfigState = { models: [], modes: [], thinkingOptions: [], settings: [] };
|
||||
commands: Array<{ name: string; description: string; argumentHint?: string }> = [];
|
||||
persistence: ProviderPersistence | null = null;
|
||||
@@ -725,14 +724,6 @@ class ProviderRuntimeSession {
|
||||
this.runtime.removeSession(this.id, this.providerSessionId);
|
||||
return;
|
||||
}
|
||||
this.closePromise ??= this.closeNativeSession().catch((error) => {
|
||||
this.closePromise = null;
|
||||
throw error;
|
||||
});
|
||||
await this.closePromise;
|
||||
}
|
||||
|
||||
private async closeNativeSession(): Promise<void> {
|
||||
try {
|
||||
await this.runtime.complete({
|
||||
type: "session.close",
|
||||
@@ -741,9 +732,9 @@ class ProviderRuntimeSession {
|
||||
});
|
||||
} catch (error) {
|
||||
if (!this.runtime.isClosed) throw error;
|
||||
} finally {
|
||||
this.runtime.removeSession(this.id, this.providerSessionId);
|
||||
}
|
||||
// A failed close still needs its routing for a subsequent session.closed ack.
|
||||
this.runtime.removeSession(this.id, this.providerSessionId);
|
||||
}
|
||||
|
||||
beginOpen(requestId: string): Promise<void> {
|
||||
@@ -1101,40 +1092,11 @@ class PluginAgentClient implements AgentClient {
|
||||
persistence: input.persistence,
|
||||
history: input.history,
|
||||
});
|
||||
const forget = () => {
|
||||
for (const [id, owner] of this.rootsBySession) {
|
||||
if (owner === session) this.rootsBySession.delete(id);
|
||||
}
|
||||
};
|
||||
const bind = (next: ProviderRuntimeSession) => {
|
||||
this.rootsBySession.set(next.id, session);
|
||||
this.attachPendingChildren();
|
||||
};
|
||||
const config = mapSessionConfig(input.config, input.launchContext, input.persist);
|
||||
const session = new PluginAgentSession(
|
||||
this.provider,
|
||||
bridge,
|
||||
forget,
|
||||
async (persistence, state) => {
|
||||
forget();
|
||||
return await this.runtime.openSession({
|
||||
sessionId: randomUUID(),
|
||||
config: {
|
||||
...config,
|
||||
model: state.model,
|
||||
mode: state.mode,
|
||||
thinkingOption: state.thinkingOption,
|
||||
settings: Object.fromEntries(
|
||||
state.settings.map((setting) => [setting.id, setting.value]),
|
||||
),
|
||||
},
|
||||
persistence,
|
||||
history: "replay",
|
||||
});
|
||||
},
|
||||
bind,
|
||||
);
|
||||
bind(bridge);
|
||||
const session = new PluginAgentSession(this.provider, bridge, () => {
|
||||
this.rootsBySession.delete(bridge.id);
|
||||
});
|
||||
this.rootsBySession.set(bridge.id, session);
|
||||
this.attachPendingChildren();
|
||||
return session;
|
||||
}
|
||||
|
||||
@@ -1195,32 +1157,16 @@ class PluginAgentSession implements AgentSession {
|
||||
private readonly revertTokens = new Map<string, ProviderTimelineItem["revertToken"]>();
|
||||
private readonly timelineSnapshots = new Map<string, TimelineTextSnapshot>();
|
||||
private readonly subagentIdsBySession = new Map<string, string | null>();
|
||||
private readonly children = new Map<
|
||||
string,
|
||||
{ session: ProviderRuntimeSession; unsubscribe: () => void }
|
||||
>();
|
||||
private readonly childUnsubscribes = new Map<string, () => void>();
|
||||
private readonly childSnapshots = new Map<string, Map<string, TimelineTextSnapshot>>();
|
||||
private unsubscribe: (() => void) | null = null;
|
||||
private currentTurnId: string | null = null;
|
||||
private closed = false;
|
||||
private replay: {
|
||||
persistence: ProviderPersistence;
|
||||
config: ProviderConfigState;
|
||||
messageId: string;
|
||||
scope: "conversation" | "both";
|
||||
closed: boolean;
|
||||
} | null = null;
|
||||
private replaying: Promise<void> | null = null;
|
||||
|
||||
constructor(
|
||||
readonly provider: string,
|
||||
private bridge: ProviderRuntimeSession,
|
||||
private readonly bridge: ProviderRuntimeSession,
|
||||
private readonly onClose: () => void,
|
||||
private readonly reopen: (
|
||||
persistence: ProviderPersistence,
|
||||
state: ProviderConfigState,
|
||||
) => Promise<ProviderRuntimeSession>,
|
||||
private readonly onBind: (bridge: ProviderRuntimeSession) => void,
|
||||
) {
|
||||
this.subagentIdsBySession.set(bridge.id, null);
|
||||
for (const event of bridge.history) this.accept(event, false);
|
||||
@@ -1237,13 +1183,7 @@ class PluginAgentSession implements AgentSession {
|
||||
}
|
||||
|
||||
get capabilities(): AgentCapabilityFlags {
|
||||
const capabilities = agentCapabilities(this.bridge.negotiatedCapabilities);
|
||||
const resumable = this.canReplayHistory;
|
||||
return {
|
||||
...capabilities,
|
||||
supportsRewindConversation: capabilities.supportsRewindConversation && resumable,
|
||||
supportsRewindBoth: capabilities.supportsRewindBoth && resumable,
|
||||
};
|
||||
return agentCapabilities(this.bridge.negotiatedCapabilities);
|
||||
}
|
||||
|
||||
get features(): AgentFeature[] {
|
||||
@@ -1271,7 +1211,6 @@ class PluginAgentSession implements AgentSession {
|
||||
prompt: AgentPromptInput,
|
||||
options: AgentRunOptions = {},
|
||||
): Promise<{ turnId: string }> {
|
||||
this.assertReplayComplete();
|
||||
const clientMessageId = options.clientMessageId ?? randomUUID();
|
||||
const result = await this.bridge.prompt({
|
||||
clientMessageId,
|
||||
@@ -1294,7 +1233,6 @@ class PluginAgentSession implements AgentSession {
|
||||
prompt: AgentPromptInput,
|
||||
options: SteerActiveTurnOptions,
|
||||
): Promise<SteerResult> {
|
||||
this.assertReplayComplete();
|
||||
if (!this.bridge.negotiatedCapabilities.includes("prompt.steer")) {
|
||||
return { status: "unavailable" };
|
||||
}
|
||||
@@ -1318,7 +1256,6 @@ class PluginAgentSession implements AgentSession {
|
||||
}
|
||||
|
||||
async *streamHistory(): AsyncGenerator<AgentStreamEvent> {
|
||||
await this.ensureReplay();
|
||||
for (const event of this.history.read(this.provider)) yield event;
|
||||
}
|
||||
|
||||
@@ -1346,7 +1283,6 @@ class PluginAgentSession implements AgentSession {
|
||||
}
|
||||
|
||||
async setMode(modeId: string): Promise<void> {
|
||||
this.assertReplayComplete();
|
||||
await this.bridge.configure({ mode: modeId });
|
||||
}
|
||||
|
||||
@@ -1383,10 +1319,17 @@ class PluginAgentSession implements AgentSession {
|
||||
async close(): Promise<void> {
|
||||
if (this.closed) return;
|
||||
this.closed = true;
|
||||
this.listeners.clear();
|
||||
await this.replaying?.catch(() => undefined);
|
||||
await this.clearBinding();
|
||||
this.replay = null;
|
||||
this.unsubscribe?.();
|
||||
this.unsubscribe = null;
|
||||
for (const unsubscribe of this.childUnsubscribes.values()) unsubscribe();
|
||||
this.childUnsubscribes.clear();
|
||||
this.subagentIdsBySession.clear();
|
||||
this.history.clear();
|
||||
this.timelineSnapshots.clear();
|
||||
this.childSnapshots.clear();
|
||||
this.revertTokens.clear();
|
||||
this.pendingPermissions.clear();
|
||||
this.permissionResponses.clear();
|
||||
this.listeners.clear();
|
||||
this.onClose();
|
||||
await this.bridge.close();
|
||||
@@ -1401,17 +1344,14 @@ class PluginAgentSession implements AgentSession {
|
||||
}
|
||||
|
||||
async setModel(modelId: string | null): Promise<void> {
|
||||
this.assertReplayComplete();
|
||||
await this.bridge.configure({ model: modelId });
|
||||
}
|
||||
|
||||
async setThinkingOption(thinkingOptionId: string | null): Promise<void> {
|
||||
this.assertReplayComplete();
|
||||
await this.bridge.configure({ thinkingOption: thinkingOptionId });
|
||||
}
|
||||
|
||||
async setFeature(featureId: string, value: unknown): Promise<void> {
|
||||
this.assertReplayComplete();
|
||||
await this.bridge.configure({
|
||||
settings: { [featureId]: toJsonValue(value, `setting '${featureId}'`) },
|
||||
});
|
||||
@@ -1475,10 +1415,10 @@ class PluginAgentSession implements AgentSession {
|
||||
const snapshots = new Map<string, TimelineTextSnapshot>();
|
||||
this.childSnapshots.set(childId, snapshots);
|
||||
for (const event of child.history) this.acceptChildEvent(childId, event, snapshots);
|
||||
this.children.set(child.id, {
|
||||
session: child,
|
||||
unsubscribe: child.onEvent((event) => this.acceptChildEvent(childId, event, snapshots)),
|
||||
});
|
||||
this.childUnsubscribes.set(
|
||||
child.id,
|
||||
child.onEvent((event) => this.acceptChildEvent(childId, event, snapshots)),
|
||||
);
|
||||
}
|
||||
|
||||
private accept(event: ProviderEvent, live: boolean): void {
|
||||
@@ -1696,84 +1636,7 @@ class PluginAgentSession implements AgentSession {
|
||||
}
|
||||
}
|
||||
|
||||
private async clearBinding(): Promise<void> {
|
||||
this.unsubscribe?.();
|
||||
this.unsubscribe = null;
|
||||
for (const child of this.children.values()) {
|
||||
child.unsubscribe();
|
||||
await child.session.close();
|
||||
}
|
||||
this.children.clear();
|
||||
this.subagentIdsBySession.clear();
|
||||
this.history.clear();
|
||||
this.timelineSnapshots.clear();
|
||||
this.childSnapshots.clear();
|
||||
this.revertTokens.clear();
|
||||
this.pendingPermissions.clear();
|
||||
this.permissionResponses.clear();
|
||||
this.currentTurnId = null;
|
||||
}
|
||||
|
||||
private assertReplayComplete(): void {
|
||||
if (this.replay) {
|
||||
throw new Error(
|
||||
"Plugin rewind history refresh is incomplete. Retry the rewind or reload the agent before continuing.",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// A native rewind has already committed. Until replay succeeds, neither history
|
||||
// nor a new prompt may use the retired binding. Keep its latest handle for retry.
|
||||
private async ensureReplay(): Promise<void> {
|
||||
if (!this.replay) return;
|
||||
if (this.closed) throw new StaleProviderSessionError(this.id);
|
||||
if (!this.replaying) {
|
||||
this.replaying = this.replayBinding().finally(() => {
|
||||
this.replaying = null;
|
||||
});
|
||||
}
|
||||
await this.replaying;
|
||||
}
|
||||
|
||||
private async replayBinding(): Promise<void> {
|
||||
const replay = this.replay!;
|
||||
if (!replay.closed) {
|
||||
for (const request of this.pendingPermissions.values()) {
|
||||
await this.respondToPermission(request.id, {
|
||||
behavior: "deny",
|
||||
message: "Session replaced after rewind",
|
||||
});
|
||||
this.pendingPermissions.delete(request.id);
|
||||
this.permissionResponses.delete(request.id);
|
||||
}
|
||||
await this.clearBinding();
|
||||
await this.bridge.close();
|
||||
replay.closed = true;
|
||||
}
|
||||
const bridge = await this.reopen(replay.persistence, replay.config);
|
||||
this.bridge = bridge;
|
||||
this.subagentIdsBySession.set(bridge.id, null);
|
||||
for (const event of bridge.history) this.accept(event, false);
|
||||
this.unsubscribe = bridge.onEvent((event) => this.accept(event, true));
|
||||
this.onBind(bridge);
|
||||
this.replay = null;
|
||||
}
|
||||
|
||||
private get canReplayHistory(): boolean {
|
||||
return (
|
||||
this.bridge.restoration === "core" &&
|
||||
this.bridge.persistence !== null &&
|
||||
this.bridge.negotiatedCapabilities.includes("session.persistence")
|
||||
);
|
||||
}
|
||||
|
||||
private async revert(messageId: string, scope: "conversation" | "files" | "both") {
|
||||
const pending = this.replay;
|
||||
await this.ensureReplay();
|
||||
if (pending?.messageId === messageId && pending.scope === scope) return;
|
||||
if (scope !== "files" && !this.canReplayHistory) {
|
||||
throw new Error("Plugin conversation rewind requires session persistence for history replay");
|
||||
}
|
||||
const token = this.revertTokens.get(messageId);
|
||||
if (token === undefined) throw new Error(`No provider revert token for message ${messageId}`);
|
||||
await this.bridge.revert({
|
||||
@@ -1783,12 +1646,6 @@ class PluginAgentSession implements AgentSession {
|
||||
token,
|
||||
scope,
|
||||
});
|
||||
if (scope !== "files") {
|
||||
const persistence = this.bridge.persistence;
|
||||
if (!persistence) throw new Error("Plugin rewind removed session persistence");
|
||||
this.replay = { persistence, config: this.bridge.config, messageId, scope, closed: false };
|
||||
await this.ensureReplay();
|
||||
}
|
||||
}
|
||||
|
||||
private publish(event: AgentStreamEvent): void {
|
||||
|
||||
@@ -22,12 +22,7 @@ interface CreateAgentProviderRuntimeOptions {
|
||||
export async function createAgentProviderRuntime(
|
||||
options: CreateAgentProviderRuntimeOptions,
|
||||
): Promise<AgentProviderRuntime> {
|
||||
const configuredPort =
|
||||
options.snapshotManager.runtimeSettings?.opencode?.env?.PASEO_OPENCODE_BRIDGE_PORT;
|
||||
const port = configuredPort === undefined ? undefined : Number(configuredPort);
|
||||
if (port !== undefined && (!Number.isInteger(port) || port < 1 || port > 65535))
|
||||
throw new Error("PASEO_OPENCODE_BRIDGE_PORT must be an integer between 1 and 65535");
|
||||
const bridge = new OpenCodeBridge({ paseoHome: options.paseoHome, logger: options.logger, port });
|
||||
const bridge = new OpenCodeBridge({ paseoHome: options.paseoHome, logger: options.logger });
|
||||
try {
|
||||
await bridge.start();
|
||||
const snapshotManager = new ProviderSnapshotManager({
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { type ChildProcess, type ChildProcessWithoutNullStreams } from "node:child_process";
|
||||
import { EventEmitter } from "node:events";
|
||||
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { createRequire } from "node:module";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
@@ -2634,72 +2634,6 @@ describe("ACPAgentSession slash commands", () => {
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("lists late command batches through the public ACP client", async () => {
|
||||
const artifacts = path.resolve(".artifacts");
|
||||
await mkdir(artifacts, { recursive: true });
|
||||
const directory = await mkdtemp(path.join(artifacts, "acp-command-inventory-"));
|
||||
const script = path.join(directory, "agent.mjs");
|
||||
await writeFile(
|
||||
script,
|
||||
`
|
||||
import { createInterface } from "node:readline";
|
||||
const send = (message) => process.stdout.write(JSON.stringify(message) + "\\n");
|
||||
const help = { name: "help", description: "Show available commands" };
|
||||
const skill = { name: "xlsx", description: "Work with spreadsheets", input: { hint: "[instructions]" } };
|
||||
const publish = (commands) => send({
|
||||
jsonrpc: "2.0", method: "session/update", params: {
|
||||
sessionId: "inventory-session", update: {
|
||||
sessionUpdate: "available_commands_update", availableCommands: commands,
|
||||
},
|
||||
},
|
||||
});
|
||||
createInterface({ input: process.stdin }).on("line", (line) => {
|
||||
const request = JSON.parse(line);
|
||||
if (request.method === "initialize") {
|
||||
send({ jsonrpc: "2.0", id: request.id, result: { protocolVersion: 1, agentCapabilities: {} } });
|
||||
} else if (request.method === "session/new") {
|
||||
// The first batch is already cached when createSession returns.
|
||||
publish([help]);
|
||||
send({ jsonrpc: "2.0", id: request.id, result: { sessionId: "inventory-session" } });
|
||||
setTimeout(() => publish([help]), 100);
|
||||
setTimeout(() => publish([help, skill]), 350);
|
||||
} else if (request.id !== undefined) {
|
||||
send({ jsonrpc: "2.0", id: request.id, error: { code: -32601, message: "Method not found" } });
|
||||
}
|
||||
});
|
||||
`,
|
||||
);
|
||||
const client = new GenericACPAgentClient({
|
||||
logger: createTestLogger(),
|
||||
command: [process.execPath, script],
|
||||
});
|
||||
try {
|
||||
const session = await client.createSession({ provider: "acp", cwd: directory });
|
||||
try {
|
||||
const commands = await session.listCommands!();
|
||||
expect(commands).toEqual([
|
||||
{
|
||||
name: "help",
|
||||
description: "Show available commands",
|
||||
argumentHint: "",
|
||||
kind: "command",
|
||||
},
|
||||
{
|
||||
name: "xlsx",
|
||||
description: "Work with spreadsheets",
|
||||
argumentHint: "[instructions]",
|
||||
kind: "command",
|
||||
},
|
||||
]);
|
||||
expect(await session.listCommands!()).toEqual(commands);
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("ACPAgentSession", () => {
|
||||
|
||||
@@ -142,26 +142,14 @@ function assertChildWithPipes(
|
||||
}
|
||||
}
|
||||
|
||||
// Watch process failures as well as spawn errors: the SDK leaves initialize
|
||||
// pending when the child exits without replying. `close` waits for stderr to
|
||||
// drain, so the failure includes the launcher's diagnostic.
|
||||
function rejectOnProcessFailure(child: ChildProcess, stderrChunks: string[]): Promise<never> {
|
||||
// Node reports a failed spawn (missing binary or missing cwd) as a child
|
||||
// `error` event; without a listener it becomes an uncaught exception.
|
||||
function rejectOnSpawnError(child: ChildProcess, stderrChunks: string[]): Promise<never> {
|
||||
return new Promise<never>((_, reject) => {
|
||||
child.once("error", (error) => {
|
||||
const stderr = stderrChunks.join("").trim();
|
||||
reject(new Error(stderr ? `${String(error)}\n${stderr}` : String(error)));
|
||||
});
|
||||
child.once("close", (code, signal) => {
|
||||
const stderr = stderrChunks.join("").trim();
|
||||
const status = signal ? `signal ${signal}` : `exit code ${code ?? "unknown"}`;
|
||||
reject(
|
||||
new Error(
|
||||
`ACP agent process exited before initialization completed (${status})${
|
||||
stderr ? `\n${stderr}` : ""
|
||||
}`,
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -337,14 +325,6 @@ const ACP_CLOSE_REQUEST_TIMEOUT_MS = 2_000;
|
||||
const ACP_IMPORT_HISTORY_LOAD_TIMEOUT_MS = 30_000;
|
||||
const ACP_IMPORT_HISTORY_BUDGET_MS = 60_000;
|
||||
|
||||
/**
|
||||
* An ACP agent publishes its slash-command inventory incrementally. Wait this
|
||||
* long without another batch before treating the inventory as complete. MiniMax
|
||||
* publishes its skills about 350ms after its built-in commands.
|
||||
*/
|
||||
const COMMAND_INVENTORY_QUIET_MS = 600;
|
||||
const COMMAND_INVENTORY_POLL_MS = 25;
|
||||
|
||||
function summarizeMalformedACPStdoutError(error: unknown): { type: string; message: string } {
|
||||
return {
|
||||
type: error instanceof Error ? error.name : typeof error,
|
||||
@@ -562,7 +542,7 @@ interface ACPProcessTransport {
|
||||
connection: ClientSideConnection;
|
||||
stderrChunks: string[];
|
||||
spawnReady: Promise<void>;
|
||||
processError: Promise<never>;
|
||||
spawnError: Promise<never>;
|
||||
}
|
||||
|
||||
interface ACPImportPromptPreviews {
|
||||
@@ -1400,7 +1380,6 @@ export class ACPAgentClient implements AgentClient {
|
||||
client?: ACPClient;
|
||||
},
|
||||
): Promise<SpawnedACPProcess> {
|
||||
const configuredOptions = ACPProviderOptionsSchema.parse(options?.providerOptions ?? {});
|
||||
const transport = await this.spawnTransport(launchEnv, options?.client);
|
||||
const probe: UninitializedACPProcess = {
|
||||
child: transport.child,
|
||||
@@ -1412,7 +1391,7 @@ export class ACPAgentClient implements AgentClient {
|
||||
const initialize = await this.initializeTransport(
|
||||
transport,
|
||||
options?.initializeTimeoutMs,
|
||||
configuredOptions.clientCapabilities,
|
||||
options?.providerOptions,
|
||||
);
|
||||
const initializedProbe: SpawnedACPProcess = {
|
||||
...probe,
|
||||
@@ -1446,7 +1425,7 @@ export class ACPAgentClient implements AgentClient {
|
||||
stderrChunks.push(chunk.toString());
|
||||
});
|
||||
|
||||
const processErrorPromise = rejectOnProcessFailure(child, stderrChunks);
|
||||
const spawnErrorPromise = rejectOnSpawnError(child, stderrChunks);
|
||||
const spawnReadyPromise = new Promise<void>((resolve) => {
|
||||
child.once("spawn", () => {
|
||||
resolve();
|
||||
@@ -1465,15 +1444,16 @@ export class ACPAgentClient implements AgentClient {
|
||||
connection,
|
||||
stderrChunks,
|
||||
spawnReady: spawnReadyPromise,
|
||||
processError: processErrorPromise,
|
||||
spawnError: spawnErrorPromise,
|
||||
};
|
||||
}
|
||||
|
||||
protected async initializeTransport(
|
||||
transport: ACPProcessTransport,
|
||||
initializeTimeoutMs?: number,
|
||||
clientCapabilities?: ACPClientCapabilities,
|
||||
providerOptions?: Record<string, unknown>,
|
||||
): Promise<InitializeResponse> {
|
||||
const configuredOptions = ACPProviderOptionsSchema.parse(providerOptions ?? {});
|
||||
let timeout: ReturnType<typeof setTimeout> | null = null;
|
||||
const initializeTimeoutPromise = initializeTimeoutMs
|
||||
? new Promise<never>((_, reject) => {
|
||||
@@ -1490,11 +1470,11 @@ export class ACPAgentClient implements AgentClient {
|
||||
protocolVersion: PROTOCOL_VERSION,
|
||||
clientCapabilities: buildACPClientCapabilities(
|
||||
this.clientCapabilityMeta,
|
||||
clientCapabilities ?? this.clientCapabilities,
|
||||
configuredOptions.clientCapabilities ?? this.clientCapabilities,
|
||||
),
|
||||
clientInfo: { name: "Paseo", version: "dev" },
|
||||
}),
|
||||
transport.processError,
|
||||
transport.spawnError,
|
||||
...(initializeTimeoutPromise ? [initializeTimeoutPromise] : []),
|
||||
]),
|
||||
);
|
||||
@@ -1575,7 +1555,7 @@ export class ACPAgentClient implements AgentClient {
|
||||
try {
|
||||
transport = await this.spawnTransport(PROBE_ENV);
|
||||
await withTimeout(
|
||||
Promise.race([transport.spawnReady, transport.processError]),
|
||||
Promise.race([transport.spawnReady, transport.spawnError]),
|
||||
phaseTimeoutMs,
|
||||
`ACP spawn timed out after ${phaseTimeoutMs}ms`,
|
||||
);
|
||||
@@ -1773,8 +1753,7 @@ export class ACPAgentSession implements AgentSession, ACPClient {
|
||||
private lastActivityAt: string | null = null;
|
||||
private configOptions: SessionConfigOption[] = [];
|
||||
private cachedCommands: AgentSlashCommand[] = [];
|
||||
/** When the last command batch arrived; null while nothing has been published. */
|
||||
private commandsUpdatedAt: number | null = null;
|
||||
private commandsReadyDeferred: { promise: Promise<void>; resolve: () => void } | null = null;
|
||||
private commandsReadySettled = false;
|
||||
private waitForInitialCommands: boolean;
|
||||
private initialCommandsWaitTimeoutMs: number;
|
||||
@@ -2072,39 +2051,58 @@ export class ACPAgentSession implements AgentSession, ACPClient {
|
||||
];
|
||||
}
|
||||
|
||||
private settleCommandsReady(): void {
|
||||
this.commandsReadySettled = true;
|
||||
private ensureCommandsReadyDeferred(): void {
|
||||
if (this.commandsReadyDeferred || this.commandsReadySettled || this.cachedCommands.length > 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
let resolve!: () => void;
|
||||
const promise = new Promise<void>((r) => {
|
||||
resolve = r;
|
||||
});
|
||||
this.commandsReadyDeferred = { promise, resolve };
|
||||
}
|
||||
|
||||
/**
|
||||
* Providers publish their command inventory incrementally. MiniMax sends its
|
||||
* built-in commands twice, then a third batch about 350ms later that merges in
|
||||
* every discovered skill. Returning after the first batch loses the skills.
|
||||
*
|
||||
* Wait for the inventory to go quiet rather than for the first batch. The
|
||||
* quiet window must exceed the gap between a provider's own batches; 600ms
|
||||
* covers MiniMax with margin. `initialCommandsWaitTimeoutMs` still bounds the
|
||||
* whole wait for providers that publish once or never publish at all.
|
||||
*/
|
||||
private async waitForCommandsToSettle(): Promise<void> {
|
||||
const deadline = Date.now() + this.initialCommandsWaitTimeoutMs;
|
||||
while (!this.commandsReadySettled && !this.closed) {
|
||||
const remaining = deadline - Date.now();
|
||||
if (remaining <= 0) return;
|
||||
const quietFor = this.commandsUpdatedAt === null ? 0 : Date.now() - this.commandsUpdatedAt;
|
||||
if (quietFor >= COMMAND_INVENTORY_QUIET_MS) return;
|
||||
await new Promise<void>((resolve) =>
|
||||
setTimeout(resolve, Math.min(remaining, COMMAND_INVENTORY_POLL_MS)),
|
||||
);
|
||||
private settleCommandsReady(): void {
|
||||
if (this.commandsReadySettled) {
|
||||
return;
|
||||
}
|
||||
this.commandsReadySettled = true;
|
||||
this.commandsReadyDeferred?.resolve();
|
||||
this.commandsReadyDeferred = null;
|
||||
}
|
||||
|
||||
private async waitForCommandsReady(): Promise<void> {
|
||||
const deferred = this.commandsReadyDeferred;
|
||||
if (!deferred) {
|
||||
return;
|
||||
}
|
||||
|
||||
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||
try {
|
||||
await Promise.race([
|
||||
deferred.promise,
|
||||
new Promise<void>((resolve) => {
|
||||
timer = setTimeout(resolve, this.initialCommandsWaitTimeoutMs);
|
||||
}),
|
||||
]);
|
||||
} finally {
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async listCommands(): Promise<AgentSlashCommand[]> {
|
||||
if (this.commandsReadySettled || this.closed || !this.waitForInitialCommands) {
|
||||
if (this.cachedCommands.length > 0) {
|
||||
return this.cachedCommands;
|
||||
}
|
||||
if (!this.waitForInitialCommands || this.closed) {
|
||||
return this.cachedCommands;
|
||||
}
|
||||
|
||||
await this.waitForCommandsToSettle();
|
||||
this.ensureCommandsReadyDeferred();
|
||||
await this.waitForCommandsReady();
|
||||
this.settleCommandsReady();
|
||||
return this.cachedCommands;
|
||||
}
|
||||
@@ -2735,12 +2733,14 @@ export class ACPAgentSession implements AgentSession, ACPClient {
|
||||
}
|
||||
}
|
||||
|
||||
// Cache an asynchronously-delivered slash-command batch from a provider that
|
||||
// supplies an extensionCommandsParser (e.g. a vendor extension notification).
|
||||
// An empty batch is the provider saying it has no commands, so it settles the
|
||||
// waiter immediately instead of letting it wait out the quiet window. An
|
||||
// optional sessionId scopes the batch to this session; notifications
|
||||
// addressed to a different session are ignored.
|
||||
// Cache an asynchronously-delivered slash-command batch and unblock any
|
||||
// listCommands() call that is waiting on the initial batch. Used when a
|
||||
// provider supplies an extensionCommandsParser whose result arrives after
|
||||
// session/new (e.g. via a vendor extension notification). The ready gate is
|
||||
// always settled — even for an empty batch — so a provider that legitimately
|
||||
// reports no commands does not leave listCommands() blocked for the full
|
||||
// initial-commands timeout. An optional sessionId scopes the batch to this
|
||||
// session; notifications addressed to a different session are ignored.
|
||||
private applyResolvedCommands(
|
||||
commands: AgentSlashCommand[],
|
||||
options?: { sessionId?: string },
|
||||
@@ -2754,13 +2754,7 @@ export class ACPAgentSession implements AgentSession, ACPClient {
|
||||
}
|
||||
|
||||
if (commands.length > 0) {
|
||||
this.commandsUpdatedAt = Date.now();
|
||||
this.cachedCommands = commands;
|
||||
// A non-empty batch may be followed by more. Let the quiet window decide
|
||||
// when the inventory is complete rather than settling here; an empty
|
||||
// batch is the provider saying it has nothing, which must still unblock
|
||||
// the waiter immediately.
|
||||
return;
|
||||
}
|
||||
this.settleCommandsReady();
|
||||
}
|
||||
@@ -2916,7 +2910,7 @@ export class ACPAgentSession implements AgentSession, ACPClient {
|
||||
child.stderr.on("data", (chunk: Buffer | string) => {
|
||||
stderrChunks.push(chunk.toString());
|
||||
});
|
||||
const processError = rejectOnProcessFailure(child, stderrChunks);
|
||||
const spawnError = rejectOnSpawnError(child, stderrChunks);
|
||||
child.once("exit", (code, signal) => {
|
||||
if (this.closed || this.historyRuntimeReleased) {
|
||||
return;
|
||||
@@ -2953,7 +2947,7 @@ export class ACPAgentSession implements AgentSession, ACPClient {
|
||||
),
|
||||
clientInfo: { name: "Paseo", version: "dev" },
|
||||
}),
|
||||
processError,
|
||||
spawnError,
|
||||
]),
|
||||
);
|
||||
|
||||
@@ -3144,19 +3138,13 @@ export class ACPAgentSession implements AgentSession, ACPClient {
|
||||
this.handleUsageUpdate(update);
|
||||
return pendingUserEvents;
|
||||
case "available_commands_update":
|
||||
this.commandsUpdatedAt = Date.now();
|
||||
this.cachedCommands = update.availableCommands.map((command) => ({
|
||||
name: command.name,
|
||||
description: command.description,
|
||||
argumentHint: command.input?.hint ?? "",
|
||||
kind: "command",
|
||||
}));
|
||||
// An empty batch means the agent has no commands and would otherwise
|
||||
// wait out the whole quiet window. A non-empty batch may be one of
|
||||
// several, so completion belongs to the quiet window.
|
||||
if (update.availableCommands.length === 0) {
|
||||
this.settleCommandsReady();
|
||||
}
|
||||
this.settleCommandsReady();
|
||||
return pendingUserEvents;
|
||||
default:
|
||||
return pendingUserEvents;
|
||||
|
||||
@@ -1,112 +0,0 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import { GenericACPAgentClient } from "./generic-acp-agent.js";
|
||||
import { createTestLogger } from "../../../test-utils/test-logger.js";
|
||||
|
||||
// Exercise the public catalog API with a real child, including stdout EOF and
|
||||
// stderr draining. No provider installation or external service is involved.
|
||||
const failingCommand: [string, ...string[]] = [
|
||||
process.execPath,
|
||||
"-e",
|
||||
"process.stdin.once('data', () => { process.stderr.write('launcher failed: fixture startup error\\n'); process.exitCode = 1; process.stdin.destroy(); });",
|
||||
];
|
||||
|
||||
describe("ACP catalog startup failures", () => {
|
||||
test("reports a process that exits during initialize with its stderr", async () => {
|
||||
const client = new GenericACPAgentClient({
|
||||
logger: createTestLogger(),
|
||||
command: failingCommand,
|
||||
});
|
||||
await expect(
|
||||
client.fetchCatalog({ scope: "workspace", cwd: process.cwd(), force: true }),
|
||||
).rejects.toThrow(/launcher failed: fixture startup error/);
|
||||
}, 5_000);
|
||||
|
||||
test("session startup reports the same process exit with its stderr", async () => {
|
||||
const client = new GenericACPAgentClient({
|
||||
logger: createTestLogger(),
|
||||
command: failingCommand,
|
||||
});
|
||||
await expect(client.createSession({ provider: "acp", cwd: process.cwd() })).rejects.toThrow(
|
||||
/launcher failed: fixture startup error/,
|
||||
);
|
||||
}, 5_000);
|
||||
|
||||
test("provider diagnostics report the startup exit instead of an initialize timeout", async () => {
|
||||
const client = new GenericACPAgentClient({
|
||||
logger: createTestLogger(),
|
||||
command: failingCommand,
|
||||
diagnosticPhaseTimeoutMs: 2_000,
|
||||
});
|
||||
const { diagnostic } = await client.getDiagnostic();
|
||||
expect(diagnostic).toContain(
|
||||
"ACP agent process exited before initialization completed (exit code 1)",
|
||||
);
|
||||
expect(diagnostic).toContain("launcher failed: fixture startup error");
|
||||
expect(diagnostic).not.toContain("initialize timed out");
|
||||
});
|
||||
|
||||
test("invalid provider options reject without crashing the host process", async () => {
|
||||
const clientModule = new URL("./generic-acp-agent.ts", import.meta.url).href;
|
||||
const loggerModule = new URL("../../../test-utils/test-logger.ts", import.meta.url).href;
|
||||
const script = `
|
||||
import { GenericACPAgentClient } from ${JSON.stringify(clientModule)};
|
||||
import { createTestLogger } from ${JSON.stringify(loggerModule)};
|
||||
const client = new GenericACPAgentClient({
|
||||
logger: createTestLogger(),
|
||||
command: [process.execPath, '-e', 'setInterval(() => {}, 1000)'],
|
||||
});
|
||||
try {
|
||||
await client.fetchCatalog({
|
||||
scope: 'workspace', cwd: process.cwd(), force: true,
|
||||
providerOptions: { clientCapabilities: { fs: 'invalid' } },
|
||||
});
|
||||
throw new Error('Expected invalid options to reject');
|
||||
} catch (error) {
|
||||
if (error.name !== 'ZodError') throw error;
|
||||
}
|
||||
// Let child cleanup and Node's unhandled-rejection check complete.
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
console.log('host stayed alive');
|
||||
`;
|
||||
const result = await promisify(execFile)(
|
||||
process.execPath,
|
||||
["--import", "tsx", "--input-type=module", "-e", script],
|
||||
{ timeout: 10_000 },
|
||||
);
|
||||
expect(result.stdout).toContain("host stayed alive");
|
||||
expect(result.stderr).toBe("");
|
||||
});
|
||||
|
||||
test("a successful catalog probe still returns its models and closes cleanly", async () => {
|
||||
const client = new GenericACPAgentClient({
|
||||
logger: createTestLogger(),
|
||||
command: [
|
||||
process.execPath,
|
||||
"-e",
|
||||
`
|
||||
require('node:readline').createInterface({ input: process.stdin }).on('line', (line) => {
|
||||
const request = JSON.parse(line);
|
||||
const result = request.method === 'initialize'
|
||||
? { protocolVersion: 1, agentCapabilities: {} }
|
||||
: { sessionId: 'fixture', models: {
|
||||
currentModelId: 'fixture-model',
|
||||
availableModels: [{ modelId: 'fixture-model', name: 'Fixture model' }]
|
||||
} };
|
||||
process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: request.id, result }) + '\\n');
|
||||
});
|
||||
`,
|
||||
],
|
||||
});
|
||||
const catalog = await client.fetchCatalog({
|
||||
scope: "workspace",
|
||||
cwd: process.cwd(),
|
||||
force: true,
|
||||
});
|
||||
expect(catalog.models).toEqual([
|
||||
expect.objectContaining({ id: "fixture-model", label: "Fixture model" }),
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -614,43 +614,6 @@ describe("ClaudeAgentSession persisted history load", () => {
|
||||
);
|
||||
});
|
||||
|
||||
test("replays a message steered into a running turn as the user's message", async () => {
|
||||
const queued = (commandMode: string, prompt: unknown, sourceUuid?: string) => ({
|
||||
type: "attachment",
|
||||
uuid: `attachment-${commandMode}`,
|
||||
parentUuid: "a1",
|
||||
attachment: {
|
||||
type: "queued_command",
|
||||
commandMode,
|
||||
prompt,
|
||||
...(sourceUuid ? { source_uuid: sourceUuid } : {}),
|
||||
},
|
||||
});
|
||||
const entries = [
|
||||
{ type: "user", uuid: "u1", parentUuid: null, message: { content: "first" } },
|
||||
{ type: "assistant", uuid: "a1", parentUuid: "u1", message: { content: "working" } },
|
||||
queued("prompt", [{ type: "text", text: "steered while working" }], "steered-1"),
|
||||
queued("task-notification", "<task-notification><task-id>t1</task-id></task-notification>"),
|
||||
{ type: "assistant", uuid: "a2", parentUuid: "a1", message: { content: "answer" } },
|
||||
];
|
||||
mkdirSync(path.dirname(transcriptPath()), { recursive: true });
|
||||
writeFileSync(transcriptPath(), entries.map((entry) => JSON.stringify(entry)).join("\n"));
|
||||
|
||||
const session = await resume();
|
||||
try {
|
||||
const users = [];
|
||||
for await (const event of session.streamHistory()) {
|
||||
if (event.type === "timeline" && event.item.type === "user_message") users.push(event.item);
|
||||
}
|
||||
expect(users).toEqual([
|
||||
{ type: "user_message", text: "first", messageId: "u1" },
|
||||
{ type: "user_message", text: "steered while working", messageId: "steered-1" },
|
||||
]);
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("loads readable history when the temporary directory is unavailable", async () => {
|
||||
const file = transcriptPath();
|
||||
const entry = { type: "assistant", message: { content: [{ type: "text", text: "saved" }] } };
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user