Compare commits

...
Author SHA1 Message Date
Mohamed Boudra 2c83dea127 refactor(app): extract daemon management toggle coordinator with unit tests
Fills the coverage gap left by deleting desktop-updates-section.test.tsx.
Extracts executeDaemonManagementToggle from useDaemonManagementToggle — pure
async coordinator with injected deps (no vi.mock). Unit tests verify the three
key invariants: settings persist before stop, stop is skipped when not
desktop-managed, and start/stop are invoked on enable/disable.
2026-05-04 22:33:07 +07:00
Mohamed Boudra 96b39d4c56 test(app): triage desktop test files — delete 16-mock component slop, tighten attachment store assertion
Removes desktop-updates-section.test.tsx (16 internal mocks, JSDOM, toHaveBeenCalledWith chains on component renders).
Tightens desktop-attachment-store.test.ts: toHaveBeenCalled() → toHaveBeenCalledWith(attachment).
2026-05-04 22:27:31 +07:00
Mohamed Boudra 13adfee3a4 refactor(app): make use-agent-input-draft storage injectable (#716)
Extract DraftStorage interface and createAgentInputDraftCore factory
to a new use-agent-input-draft-core.ts. Pure helper functions (resolveDraftKey,
resolveEffectiveComposerModelId, etc.) move there too, breaking the test
file's transitive dependency on AsyncStorage and useAgentFormState.

The test now imports directly from the core module, uses a Map-backed
in-memory storage, and has zero vi.mock calls. Tests assert behavior
("save then load returns the same draft") rather than call counts.
2026-05-04 23:23:36 +08:00
Mohamed Boudra 5387a16bb6 feat(app/e2e): introduce withWorkspace fixture and DSL helpers (#717)
Adds a `withWorkspace` Playwright fixture plus composable helpers
(permissions, sidebar, composer, agent-stream, settings) so specs read
as user-level intent. Migrates workspace-lifecycle and settings-host-page
to the new DSL as proof.
2026-05-04 23:22:59 +08:00
Mohamed Boudra 6d7848059e test(app): tighten weak assertions in utils tests (#714)
Replace toBeDefined/toBeTruthy guards with concrete shape assertions
using toContainEqual(expect.objectContaining(...)) in diff-highlighter
tests, and toMatch(/^script-draft-\d+$/) for the ID check in
project-config-form tests.
2026-05-04 23:13:09 +08:00
Mohamed Boudra a324ac5d71 refactor(app): extract pr-pane derivations into pure utils and unit tests (#713)
Move getStateLabel and getActivityVerb out of pr-pane.tsx into pr-pane-data.ts
so they can be tested without JSDOM, React, or vi.mock. Add exhaustive unit tests
for both helpers alongside the existing mapPrPaneData/formatAge/deriveAvatarColor
coverage. Delete pr-pane.test.tsx — the component test was asserting on derived
label/icon strings that are now covered by pure function tests.
2026-05-04 23:13:05 +08:00
25 changed files with 946 additions and 1144 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
import { expect, test } from "./fixtures";
import { buildHostWorkspaceRoute } from "@/utils/host-routes";
import { allowPermission, waitForPermissionPrompt } from "./helpers/app";
import { allowPermission, waitForPermissionPrompt } from "./helpers/permissions";
import { connectTerminalClient } from "./helpers/terminal-perf";
import { createTempGitRepo } from "./helpers/workspace";
+7 -1
View File
@@ -1,12 +1,13 @@
import { test as base, expect, type Page } from "@playwright/test";
import { buildCreateAgentPreferences, buildSeededHost } from "./helpers/daemon-registry";
import { createWithWorkspace, type WithWorkspace } from "./helpers/with-workspace";
// Test setup is wired through an `auto: true` fixture rather than `test.beforeEach`.
// `test.beforeEach` declared at the top level of a non-test fixture file is unreliable
// across spec-file boundaries — Playwright sometimes skips it for the first test of a
// subsequent spec when multiple specs run in the same worker. Auto fixtures run
// reliably for every test that uses this `test` object.
const test = base.extend<{ paseoE2ESetup: void }>({
const test = base.extend<{ paseoE2ESetup: void; withWorkspace: WithWorkspace }>({
baseURL: async ({}, provide) => {
const metroPort = process.env.E2E_METRO_PORT;
if (!metroPort) {
@@ -102,6 +103,11 @@ const test = base.extend<{ paseoE2ESetup: void }>({
},
{ auto: true },
],
withWorkspace: async ({ page }, provide) => {
const handle = createWithWorkspace(page);
await provide(handle.withWorkspace);
await handle.cleanup();
},
});
export { test, expect, type Page };
+17
View File
@@ -0,0 +1,17 @@
import { expect, type Page } from "@playwright/test";
export async function awaitAssistantMessage(page: Page, hasText?: string | RegExp): Promise<void> {
const messages = page.getByTestId("assistant-message");
const target = hasText === undefined ? messages.first() : messages.filter({ hasText }).first();
await expect(target).toBeVisible({ timeout: 30_000 });
}
export async function awaitToolCall(page: Page, toolName: string | RegExp): Promise<void> {
await expect(
page.getByTestId("tool-call-badge").filter({ hasText: toolName }).first(),
).toBeVisible({ timeout: 30_000 });
}
export async function expectAgentIdle(page: Page, timeout = 30_000): Promise<void> {
await expect(page.getByRole("button", { name: /stop|cancel/i })).toHaveCount(0, { timeout });
}
-17
View File
@@ -658,23 +658,6 @@ export const createAgentInRepo = async (
await createAgent(page, config.prompt);
};
export const waitForPermissionPrompt = async (page: Page, timeout = 30000) => {
const promptText = page.getByTestId("permission-request-question").first();
await expect(promptText).toBeVisible({ timeout });
};
export const allowPermission = async (page: Page) => {
const acceptButton = page.getByTestId("permission-request-accept").first();
await expect(acceptButton).toBeVisible({ timeout: 5000 });
await acceptButton.click();
};
export const denyPermission = async (page: Page) => {
const denyButton = page.getByTestId("permission-request-deny").first();
await expect(denyButton).toBeVisible({ timeout: 5000 });
await denyButton.click();
};
export async function waitForAgentFinishUI(page: Page, timeout = 30000) {
// Wait for the stop button to disappear
const stopButton = page.getByRole("button", { name: /stop|cancel/i });
+18
View File
@@ -0,0 +1,18 @@
import { expect, type Page } from "@playwright/test";
function composerInput(page: Page) {
return page.getByRole("textbox", { name: "Message agent..." }).first();
}
export async function submitMessage(page: Page, text: string): Promise<void> {
const input = composerInput(page);
await expect(input).toBeEditable({ timeout: 30_000 });
await input.fill(text);
await input.press("Enter");
}
export async function cancelAgent(page: Page): Promise<void> {
const stopButton = page.getByRole("button", { name: /stop|cancel/i }).first();
await expect(stopButton).toBeVisible({ timeout: 10_000 });
await stopButton.click();
}
+17
View File
@@ -0,0 +1,17 @@
import { expect, type Page } from "@playwright/test";
export async function waitForPermissionPrompt(page: Page, timeout = 30_000): Promise<void> {
await expect(page.getByTestId("permission-request-question").first()).toBeVisible({ timeout });
}
export async function allowPermission(page: Page): Promise<void> {
const acceptButton = page.getByTestId("permission-request-accept").first();
await expect(acceptButton).toBeVisible({ timeout: 5_000 });
await acceptButton.click();
}
export async function denyPermission(page: Page): Promise<void> {
const denyButton = page.getByTestId("permission-request-deny").first();
await expect(denyButton).toBeVisible({ timeout: 5_000 });
await denyButton.click();
}
+52
View File
@@ -0,0 +1,52 @@
import { expect, type Page } from "@playwright/test";
const SECTION_LABELS = {
general: "General",
shortcuts: "Shortcuts",
integrations: "Integrations",
permissions: "Permissions",
diagnostics: "Diagnostics",
about: "About",
} as const;
export type SettingsSection = keyof typeof SECTION_LABELS | "projects";
export async function openSettingsSection(page: Page, section: SettingsSection): Promise<void> {
const sidebar = page.getByTestId("settings-sidebar");
await expect(sidebar).toBeVisible();
if (section === "projects") {
await page.getByTestId("settings-projects").click();
await expect(page).toHaveURL(/\/settings\/projects$/);
return;
}
await sidebar.getByRole("button", { name: SECTION_LABELS[section], exact: true }).click();
await expect(page).toHaveURL(new RegExp(`/settings/${section}$`));
}
export async function openSettingsHost(page: Page, serverId: string): Promise<void> {
await page.getByTestId(`settings-host-entry-${serverId}`).click();
await expect(page.getByTestId(`settings-host-page-${serverId}`)).toBeVisible();
}
export async function expectSettingsHeader(page: Page, title: string): Promise<void> {
await expect(page.getByTestId("settings-detail-header-title")).toHaveText(title);
}
export async function openAddHostFlow(page: Page): Promise<void> {
await page.getByTestId("settings-add-host").click();
await expect(page.getByText("Add connection", { exact: true })).toBeVisible();
}
export async function selectHostConnectionType(
page: Page,
type: "direct" | "relay",
): Promise<void> {
const label = type === "direct" ? "Direct connection" : "Paste pairing link";
await page.getByRole("button", { name: label }).click();
}
export async function toggleHostAdvanced(page: Page): Promise<void> {
await page.getByTestId("direct-host-advanced-toggle").click();
}
+21
View File
@@ -0,0 +1,21 @@
import { expect, type Page } from "@playwright/test";
function requireServerId(): string {
const serverId = process.env.E2E_SERVER_ID;
if (!serverId) {
throw new Error("E2E_SERVER_ID is not set (expected from Playwright globalSetup).");
}
return serverId;
}
export async function selectWorkspaceInSidebar(page: Page, workspaceId: string): Promise<void> {
const row = page.getByTestId(`sidebar-workspace-row-${requireServerId()}:${workspaceId}`);
await expect(row).toBeVisible({ timeout: 30_000 });
await row.click();
}
export async function expectWorkspaceListed(page: Page, name: string): Promise<void> {
await expect(
page.locator('[data-testid^="sidebar-workspace-row-"]').filter({ hasText: name }).first(),
).toBeVisible({ timeout: 30_000 });
}
+105
View File
@@ -0,0 +1,105 @@
import { execSync } from "node:child_process";
import { realpath } from "node:fs/promises";
import path from "node:path";
import type { Page } from "@playwright/test";
import { waitForTabBar } from "./launcher";
import { selectWorkspaceInSidebar } from "./sidebar";
import { createTempGitRepo } from "./workspace";
import {
connectWorkspaceSetupClient,
openHomeWithProject,
type WorkspaceSetupDaemonClient,
} from "./workspace-setup";
export interface CreatedWorkspace {
workspaceId: string;
repoPath: string;
navigateTo(): Promise<void>;
}
export interface WithWorkspaceOptions {
worktree?: boolean;
prefix?: string;
}
export type WithWorkspace = (options?: WithWorkspaceOptions) => Promise<CreatedWorkspace>;
interface WorktreeRecord {
repoPath: string;
worktreePath: string;
}
export interface WithWorkspaceHandle {
withWorkspace: WithWorkspace;
cleanup: () => Promise<void>;
}
export function createWithWorkspace(page: Page): WithWorkspaceHandle {
let client: WorkspaceSetupDaemonClient | null = null;
const repos: Array<{ cleanup: () => Promise<void> }> = [];
const worktrees: WorktreeRecord[] = [];
const withWorkspace: WithWorkspace = async (options) => {
if (!client) {
client = await connectWorkspaceSetupClient();
}
const prefix = options?.prefix ?? (options?.worktree ? "wt-" : "ws-");
const repo = await createTempGitRepo(prefix);
repos.push(repo);
let workspacePath = repo.path;
if (options?.worktree) {
const tempRoot = await realpath("/tmp");
workspacePath = path.join(
tempRoot,
`paseo-wt-${Date.now()}-${Math.random().toString(36).slice(2)}`,
);
const branchName = `paseo-wt-${Date.now()}`;
execSync(
`git worktree add ${JSON.stringify(workspacePath)} -b ${JSON.stringify(branchName)} main`,
{ cwd: repo.path, stdio: "ignore" },
);
worktrees.push({ repoPath: repo.path, worktreePath: workspacePath });
// Register the parent project so the sidebar lists it before we navigate.
await client.openProject(repo.path);
}
const opened = await client.openProject(workspacePath);
if (!opened.workspace) {
throw new Error(opened.error ?? `Failed to open project ${workspacePath}`);
}
const workspaceId = opened.workspace.id;
return {
workspaceId,
repoPath: workspacePath,
navigateTo: async () => {
await openHomeWithProject(page, repo.path);
await selectWorkspaceInSidebar(page, workspaceId);
await waitForTabBar(page);
},
};
};
return {
withWorkspace,
cleanup: async () => {
for (const { repoPath, worktreePath } of worktrees) {
try {
execSync(`git worktree remove ${JSON.stringify(worktreePath)} --force`, {
cwd: repoPath,
stdio: "ignore",
});
} catch {
// Best-effort cleanup so the original test failure is preserved.
}
}
for (const repo of repos) {
await repo.cleanup();
}
if (client) {
await client.close().catch(() => undefined);
}
},
};
}
+5 -9
View File
@@ -1,6 +1,7 @@
import { test, expect, type Page } from "./fixtures";
import { gotoAppShell, openSettings } from "./helpers/app";
import { TEST_HOST_LABEL } from "./helpers/daemon-registry";
import { expectSettingsHeader, openSettingsHost } from "./helpers/settings";
function getSeededServerId(): string {
const serverId = process.env.E2E_SERVER_ID;
@@ -18,13 +19,8 @@ function getSeededDaemonPort(): string {
return port;
}
async function openHostPage(page: Page, serverId: string) {
await page.getByTestId(`settings-host-entry-${serverId}`).click();
await expect(page.getByTestId(`settings-host-page-${serverId}`)).toBeVisible();
}
async function expectHostLabelHeader(page: Page) {
await expect(page.getByTestId("settings-detail-header-title")).toHaveText(TEST_HOST_LABEL);
await expectSettingsHeader(page, TEST_HOST_LABEL);
await expect(page.getByTestId("host-page-label-edit-button")).toBeVisible();
await expect(page.getByTestId("host-page-label-input")).toHaveCount(0);
}
@@ -38,7 +34,7 @@ test.describe("Settings host page", () => {
await gotoAppShell(page);
await openSettings(page);
await openHostPage(page, serverId);
await openSettingsHost(page, serverId);
// Label renders in the detail header with a pencil edit affordance; the input is hidden until edit.
await expectHostLabelHeader(page);
@@ -67,7 +63,7 @@ test.describe("Settings host page", () => {
await gotoAppShell(page);
await openSettings(page);
await openHostPage(page, serverId);
await openSettingsHost(page, serverId);
await expect(page.getByTestId("host-page-label-input")).toHaveCount(0);
@@ -85,7 +81,7 @@ test.describe("Settings host page", () => {
await gotoAppShell(page);
await openSettings(page);
await openHostPage(page, serverId);
await openSettingsHost(page, serverId);
// TODO: add local-daemon fixture for positive Pair/Daemon coverage.
// Pair-device now lives behind a row that only the local host sees
+19 -167
View File
@@ -1,39 +1,9 @@
import { execSync } from "node:child_process";
import { realpathSync } from "node:fs";
import path from "node:path";
import { expect, test } from "./fixtures";
import { waitForTabBar } from "./helpers/launcher";
import { createTempGitRepo } from "./helpers/workspace";
import { test } from "./fixtures";
import {
createAgentChatFromLauncher,
createStandaloneTerminalFromLauncher,
expectTerminalCwd,
} from "./helpers/workspace-lifecycle";
import {
connectWorkspaceSetupClient,
openHomeWithProject,
seedProjectForWorkspaceSetup,
} from "./helpers/workspace-setup";
function getServerId(): string {
const serverId = process.env.E2E_SERVER_ID;
if (!serverId) {
throw new Error("E2E_SERVER_ID is not set.");
}
return serverId;
}
/** Navigate to a workspace via sidebar row testID and wait for the tab bar. */
async function navigateToWorkspaceViaSidebar(
page: import("@playwright/test").Page,
workspaceId: string,
): Promise<void> {
const testId = `sidebar-workspace-row-${getServerId()}:${workspaceId}`;
const row = page.getByTestId(testId);
await expect(row).toBeVisible({ timeout: 30_000 });
await row.click();
await waitForTabBar(page);
}
test.describe("Workspace lifecycle", () => {
// The first test after a spec-file switch can intermittently fail because
@@ -42,154 +12,36 @@ test.describe("Workspace lifecycle", () => {
test.describe.configure({ retries: 1 });
test.describe("Main checkout", () => {
test("creates an agent chat via New Chat", async ({ page }) => {
test("creates an agent chat via New Chat", async ({ page, withWorkspace }) => {
test.setTimeout(60_000);
const client = await connectWorkspaceSetupClient();
const repo = await createTempGitRepo("lifecycle-main-chat-");
try {
await seedProjectForWorkspaceSetup(client, repo.path);
const workspaceResult = await client.openProject(repo.path);
if (!workspaceResult.workspace) {
throw new Error(workspaceResult.error ?? `Failed to open project ${repo.path}`);
}
const workspaceId = workspaceResult.workspace.id;
await openHomeWithProject(page, repo.path);
await navigateToWorkspaceViaSidebar(page, workspaceId);
await createAgentChatFromLauncher(page);
} finally {
await client.close();
await repo.cleanup();
}
const workspace = await withWorkspace({ prefix: "lifecycle-main-chat-" });
await workspace.navigateTo();
await createAgentChatFromLauncher(page);
});
test("creates a terminal with correct CWD", async ({ page }) => {
test("creates a terminal with correct CWD", async ({ page, withWorkspace }) => {
test.setTimeout(60_000);
const client = await connectWorkspaceSetupClient();
const repo = await createTempGitRepo("lifecycle-main-shell-");
try {
await seedProjectForWorkspaceSetup(client, repo.path);
const workspaceResult = await client.openProject(repo.path);
if (!workspaceResult.workspace) {
throw new Error(workspaceResult.error ?? `Failed to open project ${repo.path}`);
}
const workspaceId = workspaceResult.workspace.id;
await openHomeWithProject(page, repo.path);
await navigateToWorkspaceViaSidebar(page, workspaceId);
await createStandaloneTerminalFromLauncher(page);
await expectTerminalCwd(page, repo.path);
} finally {
await client.close();
await repo.cleanup();
}
const workspace = await withWorkspace({ prefix: "lifecycle-main-shell-" });
await workspace.navigateTo();
await createStandaloneTerminalFromLauncher(page);
await expectTerminalCwd(page, workspace.repoPath);
});
});
test.describe("Worktree workspace", () => {
test("creates an agent chat via New Chat", async ({ page }) => {
test("creates an agent chat via New Chat", async ({ page, withWorkspace }) => {
test.setTimeout(90_000);
const client = await connectWorkspaceSetupClient();
const repo = await createTempGitRepo("lifecycle-wt-chat-");
const resolvedTmp = realpathSync("/tmp");
const worktreePath = path.join(
resolvedTmp,
`paseo-wt-${Date.now()}-${Math.random().toString(36).slice(2)}`,
);
const branchName = `lifecycle-wt-chat-${Date.now()}`;
let worktreeCreated = false;
try {
await seedProjectForWorkspaceSetup(client, repo.path);
execSync(
`git worktree add ${JSON.stringify(worktreePath)} -b ${JSON.stringify(branchName)} main`,
{
cwd: repo.path,
stdio: "ignore",
},
);
worktreeCreated = true;
const workspaceResult = await client.openProject(worktreePath);
if (!workspaceResult.workspace) {
throw new Error(workspaceResult.error ?? `Failed to open project ${worktreePath}`);
}
const workspaceId = workspaceResult.workspace.id;
await openHomeWithProject(page, repo.path);
await navigateToWorkspaceViaSidebar(page, workspaceId);
await createAgentChatFromLauncher(page);
} finally {
if (worktreeCreated) {
try {
execSync(`git worktree remove ${JSON.stringify(worktreePath)} --force`, {
cwd: repo.path,
stdio: "ignore",
});
} catch {
// Best-effort cleanup so test failures preserve the original error.
}
}
await client.close();
await repo.cleanup();
}
const workspace = await withWorkspace({ worktree: true, prefix: "lifecycle-wt-chat-" });
await workspace.navigateTo();
await createAgentChatFromLauncher(page);
});
test("creates a terminal with correct CWD", async ({ page }) => {
test("creates a terminal with correct CWD", async ({ page, withWorkspace }) => {
test.setTimeout(90_000);
const client = await connectWorkspaceSetupClient();
const repo = await createTempGitRepo("lifecycle-wt-shell-");
const resolvedTmp = realpathSync("/tmp");
const worktreePath = path.join(
resolvedTmp,
`paseo-wt-${Date.now()}-${Math.random().toString(36).slice(2)}`,
);
const branchName = `lifecycle-wt-shell-${Date.now()}`;
let worktreeCreated = false;
try {
await seedProjectForWorkspaceSetup(client, repo.path);
execSync(
`git worktree add ${JSON.stringify(worktreePath)} -b ${JSON.stringify(branchName)} main`,
{
cwd: repo.path,
stdio: "ignore",
},
);
worktreeCreated = true;
const workspaceResult = await client.openProject(worktreePath);
if (!workspaceResult.workspace) {
throw new Error(workspaceResult.error ?? `Failed to open project ${worktreePath}`);
}
const workspaceId = workspaceResult.workspace.id;
await openHomeWithProject(page, repo.path);
await navigateToWorkspaceViaSidebar(page, workspaceId);
await createStandaloneTerminalFromLauncher(page);
await expectTerminalCwd(page, worktreePath);
} finally {
if (worktreeCreated) {
try {
execSync(`git worktree remove ${JSON.stringify(worktreePath)} --force`, {
cwd: repo.path,
stdio: "ignore",
});
} catch {
// Best-effort cleanup so test failures preserve the original error.
}
}
await client.close();
await repo.cleanup();
}
const workspace = await withWorkspace({ worktree: true, prefix: "lifecycle-wt-shell-" });
await workspace.navigateTo();
await createStandaloneTerminalFromLauncher(page);
await expectTerminalCwd(page, workspace.repoPath);
});
});
});
@@ -1,169 +0,0 @@
import React from "react";
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { JSDOM } from "jsdom";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { PrPaneData } from "@/utils/pr-pane-data";
import { PrPane } from "./pr-pane";
const { theme } = vi.hoisted(() => ({
theme: {
spacing: { 1: 4, 2: 8, 3: 12, 4: 16 },
fontSize: { xs: 11, sm: 13, base: 15 },
fontWeight: { normal: "400" },
colors: {
surfaceSidebar: "#0b0b0b",
surfaceSidebarHover: "#151515",
border: "#222",
foreground: "#fff",
foregroundMuted: "#aaa",
statusSuccess: "#30d158",
statusDanger: "#ff453a",
statusWarning: "#f2c945",
statusMerged: "#a371f7",
},
},
}));
vi.mock("react-native-unistyles", () => ({
StyleSheet: {
create: (factory: unknown) => (typeof factory === "function" ? factory(theme) : factory),
},
useUnistyles: () => ({ theme }),
}));
vi.mock("lucide-react-native", () => {
const createIcon = (name: string) => (props: Record<string, unknown>) =>
React.createElement("span", { ...props, "data-icon": name });
return {
ChevronDown: createIcon("ChevronDown"),
ChevronRight: createIcon("ChevronRight"),
CircleCheck: createIcon("CircleCheck"),
CircleDot: createIcon("CircleDot"),
CircleSlash: createIcon("CircleSlash"),
CircleX: createIcon("CircleX"),
ExternalLink: createIcon("ExternalLink"),
GitMerge: createIcon("GitMerge"),
GitPullRequest: createIcon("GitPullRequest"),
GitPullRequestClosed: createIcon("GitPullRequestClosed"),
GitPullRequestDraft: createIcon("GitPullRequestDraft"),
MessageSquare: createIcon("MessageSquare"),
};
});
vi.mock("@/utils/open-external-url", () => ({
openExternalUrl: vi.fn(),
}));
let root: Root | null = null;
let container: HTMLElement | null = null;
beforeEach(() => {
const dom = new JSDOM("<!doctype html><html><body></body></html>");
vi.stubGlobal("React", React);
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
vi.stubGlobal("window", dom.window);
vi.stubGlobal("document", dom.window.document);
vi.stubGlobal("HTMLElement", dom.window.HTMLElement);
vi.stubGlobal("Node", dom.window.Node);
vi.stubGlobal("navigator", dom.window.navigator);
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
});
afterEach(() => {
if (root) {
act(() => {
root?.unmount();
});
}
root = null;
container = null;
vi.unstubAllGlobals();
});
function makeData(overrides: Partial<PrPaneData> = {}): PrPaneData {
return {
number: 1284,
title: "fix(server,app): coalesce tool call stream events",
state: "open",
url: "https://github.com/getpaseo/paseo/pull/1284",
reviewDecision: "changes_requested",
awaitingReviewers: [],
checks: [
{ name: "typecheck", workflow: "CI", status: "success", duration: "1m", url: "#" },
{ name: "test", workflow: "CI", status: "failure", duration: "2m", url: "#" },
],
activity: [
{
kind: "review",
author: "alicek",
avatarColor: "#8b5cf6",
reviewState: "approved",
body: "LGTM",
age: "2h ago",
url: "#",
},
{
kind: "comment",
author: "bmartin",
avatarColor: "#f97316",
body: "Worth a benchmark before/after.",
age: "3h ago",
url: "#",
},
],
...overrides,
};
}
function render(data: PrPaneData) {
act(() => {
root?.render(<PrPane data={data} />);
});
}
describe("PrPane", () => {
it("renders the PR title and 'Open' state label from the data prop", () => {
render(makeData());
expect(container?.textContent).toContain("fix(server,app): coalesce tool call stream events");
expect(container?.textContent).toContain("Open");
});
it("renders the correct state label and icon for each PR state", () => {
render(makeData({ state: "draft" }));
expect(container?.textContent).toContain("Draft");
expect(container?.querySelector('[data-icon="GitPullRequestDraft"]')).not.toBeNull();
render(makeData({ state: "merged" }));
expect(container?.textContent).toContain("Merged");
expect(container?.querySelector('[data-icon="GitMerge"]')).not.toBeNull();
render(makeData({ state: "closed" }));
expect(container?.textContent).toContain("Closed");
expect(container?.querySelector('[data-icon="GitPullRequestClosed"]')).not.toBeNull();
});
it("derives check summary counts from the data prop", () => {
render(makeData());
const text = container?.textContent ?? "";
expect(text).toContain("typecheck");
expect(text).toContain("test");
// 1 passed, 1 failed, 0 pending — so pending pill is hidden.
expect(text).toMatch(/1.*1/);
});
it("derives review summary counts and renders activity rows", () => {
render(makeData());
const text = container?.textContent ?? "";
expect(text).toContain("alicek");
expect(text).toContain("Approved");
expect(text).toContain("bmartin");
expect(text).toContain("Commented");
});
});
+1 -14
View File
@@ -16,6 +16,7 @@ import {
MessageSquare,
} from "lucide-react-native";
import { openExternalUrl } from "@/utils/open-external-url";
import { getActivityVerb, getStateLabel } from "@/utils/pr-pane-data";
import type {
CheckStatus,
PrPaneActivity,
@@ -283,13 +284,6 @@ function ActivityRow({ item }: { item: PrPaneActivity }) {
);
}
function getActivityVerb(item: PrPaneActivity): string {
if (item.kind === "comment") return "Commented";
if (item.reviewState === "approved") return "Approved";
if (item.reviewState === "changes_requested") return "Requested changes";
return "Reviewed";
}
function getStateColor(state: PrState, theme: ReturnType<typeof useUnistyles>["theme"]): string {
if (state === "open") return theme.colors.statusSuccess;
if (state === "draft") return theme.colors.foregroundMuted;
@@ -304,13 +298,6 @@ function getStateIcon(state: PrState) {
return GitPullRequest;
}
function getStateLabel(state: PrState): string {
if (state === "draft") return "Draft";
if (state === "merged") return "Merged";
if (state === "closed") return "Closed";
return "Open";
}
const styles = StyleSheet.create((theme) => ({
root: {
flex: 1,
@@ -139,7 +139,7 @@ describe("desktop attachment store", () => {
await store.garbageCollect({ referencedIds: new Set(["att_3"]) });
expect(readDesktopFileBase64Mock).toHaveBeenCalledWith("/managed/att_3.jpg");
expect(resolveDesktopPreviewUrlMock).toHaveBeenCalled();
expect(resolveDesktopPreviewUrlMock).toHaveBeenCalledWith(attachment);
expect(releaseDesktopPreviewUrlMock).toHaveBeenCalledWith({ url: "blob:test" });
expect(deleteDesktopAttachmentFileMock).toHaveBeenCalledWith({
path: "/managed/att_3.jpg",
@@ -1,362 +0,0 @@
/**
* @vitest-environment jsdom
*/
import { cleanup, fireEvent, render, waitFor } from "@testing-library/react";
import React from "react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { LocalDaemonSection } from "./desktop-updates-section";
const { alertMock, confirmDialogMock, settingsState, daemonStatusState } = vi.hoisted(() => ({
alertMock: vi.fn(),
confirmDialogMock: vi.fn(),
settingsState: {
settings: {
releaseChannel: "stable" as const,
daemon: {
manageBuiltInDaemon: true,
keepRunningAfterQuit: true,
},
},
updateSettings: vi.fn<
(updates: {
daemon?: {
manageBuiltInDaemon?: boolean;
keepRunningAfterQuit?: boolean;
};
}) => Promise<void>
>(),
},
daemonStatusState: {
data: {
status: {
serverId: "desktop",
status: "running" as const,
listen: null,
hostname: null,
pid: 123,
home: "/tmp/paseo",
version: "1.2.3",
desktopManaged: true,
error: null,
},
logs: {
logPath: "/tmp/paseo/daemon.log",
contents: "daemon log",
},
},
isLoading: false,
error: null as string | null,
setStatus: vi.fn(),
refetch: vi.fn(),
},
}));
vi.mock("react-native", () => ({
ActivityIndicator: () => React.createElement("div", { "data-testid": "loading-spinner" }),
Alert: { alert: alertMock },
Text: ({ children }: { children?: React.ReactNode }) =>
React.createElement("span", null, children),
View: ({ children }: { children?: React.ReactNode }) =>
React.createElement("div", null, children),
}));
vi.mock("react-native-unistyles", () => ({
StyleSheet: {
create: (factory: unknown) =>
typeof factory === "function"
? (factory as (theme: Record<string, unknown>) => unknown)({
spacing: { 1: 4, 2: 8, 3: 12, 6: 24 },
borderRadius: { lg: 12 },
fontSize: { xs: 12, sm: 14 },
colors: {
foreground: "#111",
foregroundMuted: "#666",
palette: { amber: { 500: "#f59e0b" } },
},
})
: factory,
},
useUnistyles: () => ({
theme: {
iconSize: { sm: 14 },
colors: {
foreground: "#111",
foregroundMuted: "#666",
},
},
}),
}));
vi.mock("expo-clipboard", () => ({
setStringAsync: vi.fn(() => Promise.resolve()),
}));
vi.mock("lucide-react-native", () => {
const icon = (name: string) => () => React.createElement("span", { "data-icon": name });
return {
Activity: icon("Activity"),
ArrowUpRight: icon("ArrowUpRight"),
Copy: icon("Copy"),
FileText: icon("FileText"),
};
});
vi.mock("@/styles/settings", () => ({
settingsStyles: new Proxy(
{},
{
get: (_target, prop) => String(prop),
},
),
}));
vi.mock("@/screens/settings/settings-section", () => ({
SettingsSection: ({
children,
title,
trailing,
}: {
children?: React.ReactNode;
title: string;
trailing?: React.ReactNode;
}) =>
React.createElement(
"section",
null,
React.createElement("h2", null, title),
trailing,
children,
),
}));
vi.mock("@/components/adaptive-modal-sheet", () => ({
AdaptiveModalSheet: ({
children,
visible,
title,
}: {
children?: React.ReactNode;
visible?: boolean;
title?: string;
}) => (visible ? React.createElement("div", { "data-title": title }, children) : null),
}));
vi.mock("@/components/ui/button", () => ({
Button: ({
children,
onPress,
disabled,
accessibilityLabel,
}: {
children?: React.ReactNode;
onPress?: () => void;
disabled?: boolean;
accessibilityLabel?: string;
}) =>
React.createElement(
"button",
{ type: "button", onClick: onPress, disabled, "aria-label": accessibilityLabel },
children,
),
}));
vi.mock("@/components/ui/switch", () => ({
Switch: ({
value,
onValueChange,
disabled,
accessibilityLabel,
}: {
value: boolean;
onValueChange?: (next: boolean) => void;
disabled?: boolean;
accessibilityLabel?: string;
}) =>
React.createElement("button", {
type: "button",
role: "switch",
"aria-label": accessibilityLabel,
"aria-checked": value,
disabled,
onClick: () => onValueChange?.(!value),
}),
}));
vi.mock("@/desktop/settings/desktop-settings", () => ({
useDesktopSettings: () => ({
...settingsState,
isLoading: false,
error: null,
}),
}));
vi.mock("@/desktop/hooks/use-daemon-status", () => ({
useDaemonStatus: () => daemonStatusState,
}));
vi.mock("@/utils/confirm-dialog", () => ({
confirmDialog: confirmDialogMock,
}));
vi.mock("@/utils/open-external-url", () => ({
openExternalUrl: vi.fn(),
}));
vi.mock("@/desktop/updates/desktop-updates", () => ({
isVersionMismatch: vi.fn(() => false),
}));
const daemonCommandMocks = vi.hoisted(() => ({
getCliDaemonStatusMock: vi.fn(),
startDesktopDaemonMock: vi.fn(),
stopDesktopDaemonMock: vi.fn(),
}));
vi.mock("@/desktop/daemon/desktop-daemon", () => ({
getCliDaemonStatus: daemonCommandMocks.getCliDaemonStatusMock,
shouldUseDesktopDaemon: vi.fn(() => true),
startDesktopDaemon: daemonCommandMocks.startDesktopDaemonMock,
stopDesktopDaemon: daemonCommandMocks.stopDesktopDaemonMock,
}));
vi.mock("@/utils/app-version", () => ({
resolveAppVersion: vi.fn(() => "1.2.3"),
}));
describe("LocalDaemonSection", () => {
afterEach(() => {
cleanup();
});
beforeEach(() => {
alertMock.mockReset();
confirmDialogMock.mockReset();
settingsState.settings.daemon.manageBuiltInDaemon = true;
settingsState.settings.daemon.keepRunningAfterQuit = true;
settingsState.updateSettings.mockReset();
settingsState.updateSettings.mockResolvedValue();
daemonStatusState.data.status.status = "running";
daemonStatusState.data.status.desktopManaged = true;
daemonStatusState.setStatus.mockReset();
daemonStatusState.refetch.mockReset();
daemonCommandMocks.startDesktopDaemonMock.mockReset();
daemonCommandMocks.startDesktopDaemonMock.mockResolvedValue({
...daemonStatusState.data.status,
status: "running",
desktopManaged: true,
});
daemonCommandMocks.stopDesktopDaemonMock.mockReset();
daemonCommandMocks.stopDesktopDaemonMock.mockResolvedValue({
...daemonStatusState.data.status,
status: "stopped",
});
daemonCommandMocks.getCliDaemonStatusMock.mockReset();
});
it("renders the daemon toggles as switches reflecting current settings", () => {
const screen = render(<LocalDaemonSection />);
expect(screen.getByText("Keep daemon running after quit")).toBeTruthy();
expect(screen.getByText("Manage built-in daemon")).toBeTruthy();
const keepRunningSwitch = screen.getByRole("switch", {
name: "Keep daemon running after quit",
});
expect(keepRunningSwitch.getAttribute("aria-checked")).toBe("true");
const manageSwitch = screen.getByRole("switch", { name: "Manage built-in daemon" });
expect(manageSwitch.getAttribute("aria-checked")).toBe("true");
});
it("does not render a duplicate restart-daemon control", () => {
const screen = render(<LocalDaemonSection />);
expect(screen.queryByText("Restart daemon")).toBeNull();
expect(screen.queryByText("Start daemon")).toBeNull();
});
it("updates keep-running-after-quit without changing daemon lifecycle", async () => {
const screen = render(<LocalDaemonSection />);
fireEvent.click(screen.getByRole("switch", { name: "Keep daemon running after quit" }));
await waitFor(() => {
expect(settingsState.updateSettings).toHaveBeenCalledWith({
daemon: {
keepRunningAfterQuit: false,
},
});
});
expect(confirmDialogMock).not.toHaveBeenCalled();
expect(daemonCommandMocks.stopDesktopDaemonMock).not.toHaveBeenCalled();
});
it("pauses built-in daemon management and persists the setting through desktop settings", async () => {
confirmDialogMock.mockResolvedValue(true);
const screen = render(<LocalDaemonSection />);
fireEvent.click(screen.getByRole("switch", { name: "Manage built-in daemon" }));
await waitFor(() => {
expect(daemonCommandMocks.stopDesktopDaemonMock).toHaveBeenCalledTimes(1);
});
expect(settingsState.updateSettings).toHaveBeenCalledWith({
daemon: {
manageBuiltInDaemon: false,
},
});
});
it("persists paused management before stopping the desktop-managed daemon", async () => {
confirmDialogMock.mockResolvedValue(true);
const screen = render(<LocalDaemonSection />);
fireEvent.click(screen.getByRole("switch", { name: "Manage built-in daemon" }));
await waitFor(() => {
expect(daemonCommandMocks.stopDesktopDaemonMock).toHaveBeenCalledTimes(1);
});
expect(settingsState.updateSettings.mock.invocationCallOrder[0]).toBeLessThan(
daemonCommandMocks.stopDesktopDaemonMock.mock.invocationCallOrder[0],
);
});
it("does not stop a manually managed daemon when pausing built-in daemon management", async () => {
confirmDialogMock.mockResolvedValue(true);
daemonStatusState.data.status.desktopManaged = false;
const screen = render(<LocalDaemonSection />);
fireEvent.click(screen.getByRole("switch", { name: "Manage built-in daemon" }));
await waitFor(() => {
expect(settingsState.updateSettings).toHaveBeenCalledWith({
daemon: {
manageBuiltInDaemon: false,
},
});
});
expect(daemonCommandMocks.stopDesktopDaemonMock).not.toHaveBeenCalled();
});
it("starts the built-in daemon when management is re-enabled", async () => {
settingsState.settings.daemon.manageBuiltInDaemon = false;
const screen = render(<LocalDaemonSection />);
fireEvent.click(screen.getByRole("switch", { name: "Manage built-in daemon" }));
await waitFor(() => {
expect(daemonCommandMocks.startDesktopDaemonMock).toHaveBeenCalledTimes(1);
});
expect(settingsState.updateSettings).toHaveBeenCalledWith({
daemon: {
manageBuiltInDaemon: true,
},
});
expect(daemonStatusState.setStatus).toHaveBeenCalledWith({
...daemonStatusState.data.status,
status: "running",
desktopManaged: true,
});
});
});
@@ -17,6 +17,7 @@ import {
startDesktopDaemon,
stopDesktopDaemon,
} from "@/desktop/daemon/desktop-daemon";
import { executeDaemonManagementToggle } from "@/desktop/daemon/daemon-management-toggle";
import { useDaemonStatus } from "@/desktop/hooks/use-daemon-status";
import { useDesktopSettings, type DesktopSettings } from "@/desktop/settings/desktop-settings";
import type { DesktopDaemonStatus } from "@/desktop/daemon/desktop-daemon";
@@ -39,72 +40,42 @@ function useDaemonManagementToggle(args: {
return;
}
if (!settings.manageBuiltInDaemon) {
setIsUpdatingDaemonManagement(true);
void updateSettings({ manageBuiltInDaemon: true })
.then(() => startDesktopDaemon())
.then((newStatus) => {
setStatus(newStatus);
refetch();
return;
})
.catch((error) => {
console.error("[Settings] Failed to update built-in daemon management", error);
Alert.alert("Error", "Unable to update built-in daemon management.");
})
.finally(() => {
setIsUpdatingDaemonManagement(false);
});
return;
}
void confirmDialog({
title: "Pause built-in daemon",
message:
"This will stop the built-in daemon immediately. Running agents and terminals connected to the built-in daemon will be stopped.",
confirmLabel: "Pause and stop",
cancelLabel: "Cancel",
destructive: true,
setIsUpdatingDaemonManagement(true);
void executeDaemonManagementToggle(settings.manageBuiltInDaemon, daemonStatus, {
confirm: () =>
confirmDialog({
title: "Pause built-in daemon",
message:
"This will stop the built-in daemon immediately. Running agents and terminals connected to the built-in daemon will be stopped.",
confirmLabel: "Pause and stop",
cancelLabel: "Cancel",
destructive: true,
}),
persistSettings: (next) => updateSettings(next) as Promise<void>,
startDaemon: startDesktopDaemon,
stopDaemon: stopDesktopDaemon,
})
.then((confirmed) => {
if (!confirmed) {
.then((result) => {
if (result.kind === "cancelled") {
return;
}
setIsUpdatingDaemonManagement(true);
void updateSettings({ manageBuiltInDaemon: false })
.then(() => {
if (daemonStatus?.status === "running" && daemonStatus.desktopManaged) {
return stopDesktopDaemon();
}
return daemonStatus ?? null;
})
.then((newStatus) => {
if (newStatus) {
setStatus(newStatus);
}
return;
})
.then(() => {
refetch();
return;
})
.catch((error) => {
console.error("[Settings] Failed to stop built-in daemon", error);
Alert.alert(
"Error",
"Built-in daemon management was paused, but Paseo could not stop the daemon.",
);
})
.finally(() => {
setIsUpdatingDaemonManagement(false);
});
if (result.newStatus) {
setStatus(result.newStatus);
}
refetch();
return;
})
.catch((error) => {
console.error("[Settings] Failed to open built-in daemon pause confirmation", error);
Alert.alert("Error", "Unable to open the daemon confirmation dialog.");
console.error("[Settings] Failed to update built-in daemon management", error);
Alert.alert(
"Error",
settings.manageBuiltInDaemon
? "Built-in daemon management was paused, but Paseo could not stop the daemon."
: "Unable to update built-in daemon management.",
);
})
.finally(() => {
setIsUpdatingDaemonManagement(false);
});
}, [
daemonStatus,
@@ -0,0 +1,159 @@
import { describe, expect, it } from "vitest";
import { executeDaemonManagementToggle } from "./daemon-management-toggle";
import type { DesktopDaemonStatus } from "./desktop-daemon";
const runningManagedStatus: DesktopDaemonStatus = {
serverId: "desktop",
status: "running",
listen: null,
hostname: null,
pid: 123,
home: "/tmp/paseo",
version: "1.0.0",
desktopManaged: true,
error: null,
};
const stoppedStatus: DesktopDaemonStatus = { ...runningManagedStatus, status: "stopped" };
function makeDeps(overrides?: {
confirm?: () => Promise<boolean>;
persistSettings?: (next: { manageBuiltInDaemon: boolean }) => Promise<void>;
startDaemon?: () => Promise<DesktopDaemonStatus>;
stopDaemon?: () => Promise<DesktopDaemonStatus>;
}) {
const calls: string[] = [];
return {
deps: {
confirm: overrides?.confirm ?? (() => Promise.resolve(true)),
persistSettings:
overrides?.persistSettings ??
(async () => {
calls.push("persist");
}),
startDaemon:
overrides?.startDaemon ??
(async () => {
calls.push("start");
return { ...runningManagedStatus, status: "running" as const };
}),
stopDaemon:
overrides?.stopDaemon ??
(async () => {
calls.push("stop");
return stoppedStatus;
}),
},
calls,
};
}
describe("executeDaemonManagementToggle", () => {
describe("enable path (currentlyManaging: false)", () => {
it("persists the new setting then starts the daemon", async () => {
const { deps, calls } = makeDeps();
const result = await executeDaemonManagementToggle(false, null, deps);
expect(result).toEqual({ kind: "enabled", newStatus: runningManagedStatus });
expect(calls).toEqual(["persist", "start"]);
});
it("persists manageBuiltInDaemon: true", async () => {
let persisted: { manageBuiltInDaemon: boolean } | null = null;
const { deps } = makeDeps({
persistSettings: async (next) => {
persisted = next;
},
});
await executeDaemonManagementToggle(false, null, deps);
expect(persisted).toEqual({ manageBuiltInDaemon: true });
});
});
describe("disable path (currentlyManaging: true)", () => {
it("returns cancelled without changing settings when confirmation is rejected", async () => {
const persistedSettings: unknown[] = [];
const { deps } = makeDeps({
confirm: () => Promise.resolve(false),
persistSettings: async (next) => {
persistedSettings.push(next);
},
});
const result = await executeDaemonManagementToggle(true, runningManagedStatus, deps);
expect(result).toEqual({ kind: "cancelled" });
expect(persistedSettings).toHaveLength(0);
});
it("persists settings BEFORE stopping the daemon", async () => {
const callOrder: string[] = [];
const { deps } = makeDeps({
persistSettings: async () => {
callOrder.push("persist");
},
stopDaemon: async () => {
callOrder.push("stop");
return stoppedStatus;
},
});
await executeDaemonManagementToggle(true, runningManagedStatus, deps);
expect(callOrder).toEqual(["persist", "stop"]);
});
it("persists manageBuiltInDaemon: false when disabling", async () => {
let persisted: { manageBuiltInDaemon: boolean } | null = null;
const { deps } = makeDeps({
persistSettings: async (next) => {
persisted = next;
},
});
await executeDaemonManagementToggle(true, runningManagedStatus, deps);
expect(persisted).toEqual({ manageBuiltInDaemon: false });
});
it("stops the daemon when it is running and desktop-managed", async () => {
const { deps, calls } = makeDeps();
const result = await executeDaemonManagementToggle(true, runningManagedStatus, deps);
expect(calls).toContain("stop");
expect(result).toEqual({ kind: "disabled", newStatus: stoppedStatus });
});
it("skips stop when daemon is running but not desktop-managed", async () => {
const { deps, calls } = makeDeps();
const manuallyManagedStatus = { ...runningManagedStatus, desktopManaged: false };
const result = await executeDaemonManagementToggle(true, manuallyManagedStatus, deps);
expect(calls).not.toContain("stop");
expect(result).toEqual({ kind: "disabled", newStatus: null });
});
it("skips stop when daemon is stopped (regardless of desktopManaged)", async () => {
const { deps, calls } = makeDeps();
const result = await executeDaemonManagementToggle(true, stoppedStatus, deps);
expect(calls).not.toContain("stop");
expect(result).toEqual({ kind: "disabled", newStatus: null });
});
it("skips stop when daemonStatus is null", async () => {
const { deps, calls } = makeDeps();
const result = await executeDaemonManagementToggle(true, null, deps);
expect(calls).not.toContain("stop");
expect(result).toEqual({ kind: "disabled", newStatus: null });
});
});
});
@@ -0,0 +1,41 @@
import type { DesktopDaemonStatus } from "./desktop-daemon";
export interface DaemonManagementToggleDeps {
confirm: () => Promise<boolean>;
persistSettings: (next: { manageBuiltInDaemon: boolean }) => Promise<void>;
startDaemon: () => Promise<DesktopDaemonStatus>;
stopDaemon: () => Promise<DesktopDaemonStatus>;
}
export type DaemonManagementToggleResult =
| { kind: "cancelled" }
| { kind: "enabled"; newStatus: DesktopDaemonStatus }
| { kind: "disabled"; newStatus: DesktopDaemonStatus | null };
export async function executeDaemonManagementToggle(
currentlyManaging: boolean,
daemonStatus: Pick<DesktopDaemonStatus, "status" | "desktopManaged"> | null,
deps: DaemonManagementToggleDeps,
): Promise<DaemonManagementToggleResult> {
if (!currentlyManaging) {
await deps.persistSettings({ manageBuiltInDaemon: true });
const newStatus = await deps.startDaemon();
return { kind: "enabled", newStatus };
}
const confirmed = await deps.confirm();
if (!confirmed) {
return { kind: "cancelled" };
}
// Settings must persist before the daemon is stopped so the persisted
// state reflects what was actually applied if the stop fails.
await deps.persistSettings({ manageBuiltInDaemon: false });
if (daemonStatus?.status === "running" && daemonStatus.desktopManaged) {
const newStatus = await deps.stopDaemon();
return { kind: "disabled", newStatus };
}
return { kind: "disabled", newStatus: null };
}
@@ -0,0 +1,174 @@
import type { UserComposerAttachment } from "@/attachments/types";
import type { DraftAgentStatusBarProps } from "@/components/agent-status-bar";
import type { DraftCommandConfig } from "@/hooks/use-agent-commands-query";
import type { UseAgentFormStateResult } from "@/hooks/use-agent-form-state";
import type { AgentModelDefinition, AgentProvider } from "@server/server/agent/agent-sdk-types";
export interface DraftStorage {
getItem(key: string): Promise<string | null>;
setItem(key: string, value: string): Promise<void>;
removeItem(key: string): Promise<void>;
}
export interface StoredDraft {
text: string;
attachments: UserComposerAttachment[];
cwd: string;
}
export interface AgentInputDraftCore {
load(initialCwd?: string): Promise<StoredDraft | null>;
save(draft: StoredDraft): Promise<void>;
clear(): Promise<void>;
}
export function createAgentInputDraftCore(input: {
storage: DraftStorage;
storageKey: string;
}): AgentInputDraftCore {
return {
async load(initialCwd?: string) {
const json = await input.storage.getItem(input.storageKey);
if (!json) return null;
try {
const parsed = JSON.parse(json) as Record<string, unknown>;
return {
text: typeof parsed.text === "string" ? parsed.text : "",
attachments: Array.isArray(parsed.attachments)
? (parsed.attachments as UserComposerAttachment[])
: [],
cwd: typeof parsed.cwd === "string" ? parsed.cwd : (initialCwd ?? ""),
};
} catch {
return null;
}
},
async save(draft) {
await input.storage.setItem(input.storageKey, JSON.stringify(draft));
},
async clear() {
await input.storage.removeItem(input.storageKey);
},
};
}
export interface DraftKeyContext {
selectedServerId: string | null;
}
export type DraftKeyInput = string | ((context: DraftKeyContext) => string);
export function resolveDraftKey(input: {
draftKey: DraftKeyInput;
selectedServerId: string | null;
}): string {
if (typeof input.draftKey === "function") {
return input.draftKey({ selectedServerId: input.selectedServerId });
}
return input.draftKey;
}
export function resolveEffectiveComposerModelId(input: {
selectedModel: string;
availableModels: AgentModelDefinition[];
}): string {
return input.selectedModel.trim();
}
export function resolveEffectiveComposerThinkingOptionId(input: {
selectedThinkingOptionId: string;
availableModels: AgentModelDefinition[];
effectiveModelId: string;
}): string {
const selectedThinkingOptionId = input.selectedThinkingOptionId.trim();
if (selectedThinkingOptionId) {
return selectedThinkingOptionId;
}
const selectedModelDefinition =
input.availableModels.find((model) => model.id === input.effectiveModelId) ?? null;
return selectedModelDefinition?.defaultThinkingOptionId ?? "";
}
export function buildDraftComposerCommandConfig(input: {
provider: AgentProvider | null;
cwd: string;
modeOptions: DraftAgentStatusBarProps["modeOptions"];
selectedMode: string;
effectiveModelId: string;
effectiveThinkingOptionId: string;
featureValues?: Record<string, unknown>;
}): DraftCommandConfig | undefined {
const cwd = input.cwd.trim();
if (!input.provider || !cwd) {
return undefined;
}
return {
provider: input.provider,
cwd,
...(input.modeOptions.length > 0 && input.selectedMode !== ""
? { modeId: input.selectedMode }
: {}),
...(input.effectiveModelId ? { model: input.effectiveModelId } : {}),
...(input.effectiveThinkingOptionId
? { thinkingOptionId: input.effectiveThinkingOptionId }
: {}),
...(input.featureValues ? { featureValues: input.featureValues } : {}),
};
}
export function buildDraftStatusControls(input: {
formState: UseAgentFormStateResult;
features?: DraftAgentStatusBarProps["features"];
onSetFeature?: DraftAgentStatusBarProps["onSetFeature"];
onDropdownClose?: DraftAgentStatusBarProps["onDropdownClose"];
}): DraftAgentStatusBarProps {
const { formState, features, onSetFeature, onDropdownClose } = input;
return {
providerDefinitions: formState.providerDefinitions,
selectedProvider: formState.selectedProvider,
onSelectProvider: formState.setProviderFromUser,
modeOptions: formState.modeOptions,
selectedMode: formState.selectedMode,
onSelectMode: formState.setModeFromUser,
models: formState.availableModels,
selectedModel: formState.selectedModel,
onSelectModel: formState.setModelFromUser,
isModelLoading: formState.isModelLoading,
allProviderModels: formState.allProviderModels,
isAllModelsLoading: formState.isAllModelsLoading,
onSelectProviderAndModel: formState.setProviderAndModelFromUser,
thinkingOptions: formState.availableThinkingOptions,
selectedThinkingOptionId: formState.selectedThinkingOptionId,
onSelectThinkingOption: formState.setThinkingOptionFromUser,
features,
onSetFeature,
onDropdownClose,
onModelSelectorOpen: formState.refetchProviderModelsIfStale,
};
}
export function hasDraftContent(input: {
text: string;
attachments: UserComposerAttachment[];
cwd: string;
}): boolean {
return (
input.text.trim().length > 0 || input.attachments.length > 0 || input.cwd.trim().length > 0
);
}
export function areAttachmentsEqual(input: {
left: UserComposerAttachment[];
right: UserComposerAttachment[];
}): boolean {
if (input.left.length !== input.right.length) {
return false;
}
return input.left.every((attachment, index) => {
const other = input.right[index];
return JSON.stringify(attachment) === JSON.stringify(other);
});
}
@@ -1,194 +1,188 @@
import { beforeAll, describe, expect, it, vi } from "vitest";
import { describe, expect, it } from "vitest";
import {
buildDraftComposerCommandConfig,
createAgentInputDraftCore,
resolveDraftKey,
resolveEffectiveComposerModelId,
resolveEffectiveComposerThinkingOptionId,
} from "./use-agent-input-draft-core";
vi.mock("@react-native-async-storage/async-storage", () => ({
default: {
getItem: async () => null,
setItem: async () => undefined,
removeItem: async () => undefined,
},
}));
vi.mock("@/attachments/service", () => ({
garbageCollectAttachments: async () => undefined,
}));
vi.mock("./use-agent-form-state", () => ({
useAgentFormState: () => ({
selectedServerId: "host-1",
setSelectedServerId: () => undefined,
setSelectedServerIdFromUser: () => undefined,
selectedProvider: "codex",
setProviderFromUser: () => undefined,
selectedMode: "auto",
setModeFromUser: () => undefined,
selectedModel: "",
setModelFromUser: () => undefined,
selectedThinkingOptionId: "",
setThinkingOptionFromUser: () => undefined,
workingDir: "/repo",
setWorkingDir: () => undefined,
setWorkingDirFromUser: () => undefined,
providerDefinitions: [{ id: "codex", label: "Codex", modes: [{ id: "auto", label: "Auto" }] }],
providerDefinitionMap: new Map(),
agentDefinition: undefined,
modeOptions: [{ id: "auto", label: "Auto" }],
availableModels: [],
allProviderModels: new Map(),
isAllModelsLoading: false,
availableThinkingOptions: [],
isModelLoading: false,
modelError: null,
refreshProviderModels: () => undefined,
setProviderAndModelFromUser: () => undefined,
workingDirIsEmpty: false,
persistFormPreferences: async () => undefined,
}),
}));
let __private__: typeof import("./use-agent-input-draft").__private__;
beforeAll(async () => {
const storage = new Map<string, string>();
Object.defineProperty(globalThis, "window", {
value: {
localStorage: {
getItem: (key: string) => storage.get(key) ?? null,
setItem: (key: string, value: string) => {
storage.set(key, value);
},
removeItem: (key: string) => {
storage.delete(key);
},
},
function makeStorage() {
const map = new Map<string, string>();
return {
getItem: async (key: string) => map.get(key) ?? null,
setItem: async (key: string, value: string) => {
map.set(key, value);
},
configurable: true,
removeItem: async (key: string) => {
map.delete(key);
},
};
}
describe("resolveDraftKey", () => {
it("returns a string draft key unchanged", () => {
expect(
resolveDraftKey({
draftKey: "draft:key",
selectedServerId: "host-1",
}),
).toBe("draft:key");
});
({ __private__ } = await import("./use-agent-input-draft"));
it("resolves a computed draft key from the selected server", () => {
expect(
resolveDraftKey({
draftKey: ({ selectedServerId }) => `draft:${selectedServerId ?? "none"}`,
selectedServerId: "host-1",
}),
).toBe("draft:host-1");
});
});
describe("useAgentInputDraft", () => {
describe("__private__.resolveDraftKey", () => {
it("returns an object draft key string unchanged", () => {
expect(
__private__.resolveDraftKey({
draftKey: "draft:key",
selectedServerId: "host-1",
}),
).toBe("draft:key");
});
it("resolves a computed draft key from the selected server", () => {
expect(
__private__.resolveDraftKey({
draftKey: ({ selectedServerId }) => `draft:${selectedServerId ?? "none"}`,
selectedServerId: "host-1",
}),
).toBe("draft:host-1");
});
describe("resolveEffectiveComposerModelId", () => {
it("returns the selected model trimmed", () => {
expect(
resolveEffectiveComposerModelId({
selectedModel: " gpt-5.4-mini ",
availableModels: [],
}),
).toBe("gpt-5.4-mini");
});
describe("__private__.resolveEffectiveComposerModelId", () => {
const models = [
{
provider: "codex",
id: "gpt-5.4",
label: "gpt-5.4",
isDefault: true,
},
{
provider: "codex",
id: "gpt-5.4-mini",
label: "gpt-5.4-mini",
},
];
it("returns empty string when no model selected", () => {
expect(
resolveEffectiveComposerModelId({
selectedModel: "",
availableModels: [],
}),
).toBe("");
});
});
it("prefers the selected model when present", () => {
expect(
__private__.resolveEffectiveComposerModelId({
selectedModel: "gpt-5.4-mini",
availableModels: models,
}),
).toBe("gpt-5.4-mini");
});
describe("resolveEffectiveComposerThinkingOptionId", () => {
const models = [
{
provider: "codex",
id: "gpt-5.4",
label: "gpt-5.4",
isDefault: true,
defaultThinkingOptionId: "high",
thinkingOptions: [
{ id: "medium", label: "Medium" },
{ id: "high", label: "High", isDefault: true },
],
},
];
it("returns empty string when no model selected", () => {
expect(
__private__.resolveEffectiveComposerModelId({
selectedModel: "",
availableModels: models,
}),
).toBe("");
});
it("prefers the selected thinking option when present", () => {
expect(
resolveEffectiveComposerThinkingOptionId({
selectedThinkingOptionId: "medium",
availableModels: models,
effectiveModelId: "gpt-5.4",
}),
).toBe("medium");
});
describe("__private__.resolveEffectiveComposerThinkingOptionId", () => {
const models = [
{
it("falls back to the model default thinking option", () => {
expect(
resolveEffectiveComposerThinkingOptionId({
selectedThinkingOptionId: "",
availableModels: models,
effectiveModelId: "gpt-5.4",
}),
).toBe("high");
});
});
describe("buildDraftComposerCommandConfig", () => {
it("returns undefined when cwd is empty", () => {
expect(
buildDraftComposerCommandConfig({
provider: "codex",
id: "gpt-5.4",
label: "gpt-5.4",
isDefault: true,
defaultThinkingOptionId: "high",
thinkingOptions: [
{ id: "medium", label: "Medium" },
{ id: "high", label: "High", isDefault: true },
],
},
];
it("prefers the selected thinking option when present", () => {
expect(
__private__.resolveEffectiveComposerThinkingOptionId({
selectedThinkingOptionId: "medium",
availableModels: models,
effectiveModelId: "gpt-5.4",
}),
).toBe("medium");
});
it("falls back to the model default thinking option", () => {
expect(
__private__.resolveEffectiveComposerThinkingOptionId({
selectedThinkingOptionId: "",
availableModels: models,
effectiveModelId: "gpt-5.4",
}),
).toBe("high");
});
cwd: " ",
modeOptions: [],
selectedMode: "",
effectiveModelId: "gpt-5.4",
effectiveThinkingOptionId: "high",
}),
).toBeUndefined();
});
describe("__private__.buildDraftComposerCommandConfig", () => {
it("returns undefined when cwd is empty", () => {
expect(
__private__.buildDraftComposerCommandConfig({
provider: "codex",
cwd: " ",
modeOptions: [],
selectedMode: "",
effectiveModelId: "gpt-5.4",
effectiveThinkingOptionId: "high",
}),
).toBeUndefined();
});
it("builds the draft command config from derived composer state", () => {
expect(
__private__.buildDraftComposerCommandConfig({
provider: "codex",
cwd: "/repo",
modeOptions: [{ id: "auto", label: "Auto" }],
selectedMode: "auto",
effectiveModelId: "gpt-5.4",
effectiveThinkingOptionId: "high",
}),
).toEqual({
it("builds the draft command config from derived composer state", () => {
expect(
buildDraftComposerCommandConfig({
provider: "codex",
cwd: "/repo",
modeId: "auto",
model: "gpt-5.4",
thinkingOptionId: "high",
});
modeOptions: [{ id: "auto", label: "Auto" }],
selectedMode: "auto",
effectiveModelId: "gpt-5.4",
effectiveThinkingOptionId: "high",
}),
).toEqual({
provider: "codex",
cwd: "/repo",
modeId: "auto",
model: "gpt-5.4",
thinkingOptionId: "high",
});
});
});
describe("createAgentInputDraftCore", () => {
it("load returns null when nothing has been saved", async () => {
const core = createAgentInputDraftCore({ storage: makeStorage(), storageKey: "test" });
expect(await core.load()).toBeNull();
});
it("load returns the draft that was saved", async () => {
const core = createAgentInputDraftCore({ storage: makeStorage(), storageKey: "test" });
await core.save({ text: "hello world", attachments: [], cwd: "/repo" });
expect(await core.load()).toEqual({ text: "hello world", attachments: [], cwd: "/repo" });
});
it("clear removes the persisted draft", async () => {
const core = createAgentInputDraftCore({ storage: makeStorage(), storageKey: "test" });
await core.save({ text: "hello", attachments: [], cwd: "/repo" });
await core.clear();
expect(await core.load()).toBeNull();
});
it("load seeds cwd from initialCwd when cwd is absent from stored data", async () => {
const storage = makeStorage();
await storage.setItem("test", JSON.stringify({ text: "hello", attachments: [] }));
const core = createAgentInputDraftCore({ storage, storageKey: "test" });
const draft = await core.load("/initial");
expect(draft?.cwd).toBe("/initial");
});
it("round-trips attachments unchanged", async () => {
const attachment = {
kind: "github_issue" as const,
item: {
kind: "issue" as const,
number: 42,
title: "Unify attachments",
url: "https://github.com/example/repo/issues/42",
state: "open" as const,
body: "body",
labels: ["composer"],
},
};
const core = createAgentInputDraftCore({ storage: makeStorage(), storageKey: "test" });
await core.save({ text: "", attachments: [attachment], cwd: "/repo" });
const draft = await core.load();
expect(draft?.attachments).toEqual([attachment]);
});
it("isolated keys do not share state", async () => {
const storage = makeStorage();
const a = createAgentInputDraftCore({ storage, storageKey: "key-a" });
const b = createAgentInputDraftCore({ storage, storageKey: "key-b" });
await a.save({ text: "from a", attachments: [], cwd: "" });
expect(await b.load()).toBeNull();
expect(await a.load()).toMatchObject({ text: "from a" });
});
});
+10 -123
View File
@@ -8,9 +8,17 @@ import {
type UseAgentFormStateResult,
} from "@/hooks/use-agent-form-state";
import { useDraftAgentFeatures } from "@/hooks/use-draft-agent-features";
import {
areAttachmentsEqual,
buildDraftComposerCommandConfig,
buildDraftStatusControls,
hasDraftContent,
resolveDraftKey,
resolveEffectiveComposerModelId,
resolveEffectiveComposerThinkingOptionId,
type DraftKeyInput,
} from "@/hooks/use-agent-input-draft-core";
import { useDraftStore } from "@/stores/draft-store";
import type { AgentModelDefinition } from "@server/server/agent/agent-sdk-types";
import type { AgentProvider } from "@server/server/agent/agent-sdk-types";
type AttachmentUpdater =
| UserComposerAttachment[]
@@ -24,12 +32,6 @@ interface AgentInputDraftComposerOptions {
lockedWorkingDir?: string;
}
interface DraftKeyContext {
selectedServerId: string | null;
}
type DraftKeyInput = string | ((context: DraftKeyContext) => string);
interface UseAgentInputDraftInput {
draftKey: DraftKeyInput;
initialCwd?: string;
@@ -57,121 +59,6 @@ interface AgentInputDraft {
composerState: DraftComposerState | null;
}
function hasDraftContent(input: {
text: string;
attachments: UserComposerAttachment[];
cwd: string;
}): boolean {
return (
input.text.trim().length > 0 || input.attachments.length > 0 || input.cwd.trim().length > 0
);
}
function areAttachmentsEqual(input: {
left: UserComposerAttachment[];
right: UserComposerAttachment[];
}): boolean {
if (input.left.length !== input.right.length) {
return false;
}
return input.left.every((attachment, index) => {
const other = input.right[index];
return JSON.stringify(attachment) === JSON.stringify(other);
});
}
function resolveDraftKey(input: {
draftKey: DraftKeyInput;
selectedServerId: string | null;
}): string {
if (typeof input.draftKey === "function") {
return input.draftKey({ selectedServerId: input.selectedServerId });
}
return input.draftKey;
}
function resolveEffectiveComposerModelId(input: {
selectedModel: string;
availableModels: AgentModelDefinition[];
}): string {
return input.selectedModel.trim();
}
function resolveEffectiveComposerThinkingOptionId(input: {
selectedThinkingOptionId: string;
availableModels: AgentModelDefinition[];
effectiveModelId: string;
}): string {
const selectedThinkingOptionId = input.selectedThinkingOptionId.trim();
if (selectedThinkingOptionId) {
return selectedThinkingOptionId;
}
const selectedModelDefinition =
input.availableModels.find((model) => model.id === input.effectiveModelId) ?? null;
return selectedModelDefinition?.defaultThinkingOptionId ?? "";
}
function buildDraftComposerCommandConfig(input: {
provider: AgentProvider | null;
cwd: string;
modeOptions: DraftAgentStatusBarProps["modeOptions"];
selectedMode: string;
effectiveModelId: string;
effectiveThinkingOptionId: string;
featureValues?: Record<string, unknown>;
}): DraftCommandConfig | undefined {
const cwd = input.cwd.trim();
if (!input.provider || !cwd) {
return undefined;
}
return {
provider: input.provider,
cwd,
...(input.modeOptions.length > 0 && input.selectedMode !== ""
? { modeId: input.selectedMode }
: {}),
...(input.effectiveModelId ? { model: input.effectiveModelId } : {}),
...(input.effectiveThinkingOptionId
? { thinkingOptionId: input.effectiveThinkingOptionId }
: {}),
...(input.featureValues ? { featureValues: input.featureValues } : {}),
};
}
function buildDraftStatusControls(input: {
formState: UseAgentFormStateResult;
features?: DraftAgentStatusBarProps["features"];
onSetFeature?: DraftAgentStatusBarProps["onSetFeature"];
onDropdownClose?: DraftAgentStatusBarProps["onDropdownClose"];
}): DraftAgentStatusBarProps {
const { formState, features, onSetFeature, onDropdownClose } = input;
return {
providerDefinitions: formState.providerDefinitions,
selectedProvider: formState.selectedProvider,
onSelectProvider: formState.setProviderFromUser,
modeOptions: formState.modeOptions,
selectedMode: formState.selectedMode,
onSelectMode: formState.setModeFromUser,
models: formState.availableModels,
selectedModel: formState.selectedModel,
onSelectModel: formState.setModelFromUser,
isModelLoading: formState.isModelLoading,
allProviderModels: formState.allProviderModels,
isAllModelsLoading: formState.isAllModelsLoading,
onSelectProviderAndModel: formState.setProviderAndModelFromUser,
thinkingOptions: formState.availableThinkingOptions,
selectedThinkingOptionId: formState.selectedThinkingOptionId,
onSelectThinkingOption: formState.setThinkingOptionFromUser,
features,
onSetFeature,
onDropdownClose,
onModelSelectorOpen: formState.refetchProviderModelsIfStale,
};
}
export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDraft {
const composerOptions = input.composer ?? null;
const formState = useAgentFormState({
+42 -44
View File
@@ -285,18 +285,12 @@ describe("highlightDiffFile", () => {
// First content line: "const foo = 1;"
const constLine = hunk.lines[1];
expect(constLine.tokens).toBeDefined();
expect(constLine.tokens!.length).toBeGreaterThan(0);
// Should have a "keyword" token for "const"
const constToken = constLine.tokens!.find((t) => t.text === "const");
expect(constToken).toBeDefined();
expect(constToken!.style).toBe("keyword");
// Should have a "number" token for "1"
const numberToken = constLine.tokens!.find((t) => t.text === "1");
expect(numberToken).toBeDefined();
expect(numberToken!.style).toBe("number");
expect(constLine.tokens).toContainEqual(
expect.objectContaining({ text: "const", style: "keyword" }),
);
expect(constLine.tokens).toContainEqual(
expect.objectContaining({ text: "1", style: "number" }),
);
});
it("highlights both added and removed lines correctly", () => {
@@ -306,15 +300,15 @@ describe("highlightDiffFile", () => {
// Removed line: "const bar = 2;"
const removedLine = hunk.lines.find((l) => l.type === "remove" && l.content.includes("bar"));
expect(removedLine?.tokens).toBeDefined();
const removedNumber = removedLine!.tokens!.find((t) => t.text === "2");
expect(removedNumber?.style).toBe("number");
expect(removedLine?.tokens).toContainEqual(
expect.objectContaining({ text: "2", style: "number" }),
);
// Added line: "const bar = 3;"
const addedLine = hunk.lines.find((l) => l.type === "add" && l.content.includes("bar"));
expect(addedLine?.tokens).toBeDefined();
const addedNumber = addedLine!.tokens!.find((t) => t.text === "3");
expect(addedNumber?.style).toBe("number");
expect(addedLine?.tokens).toContainEqual(
expect.objectContaining({ text: "3", style: "number" }),
);
});
it("does not modify unsupported file types", () => {
@@ -351,15 +345,16 @@ describe("highlightDiffFile", () => {
const highlighted = highlightDiffFile(files[0]);
const hunk = highlighted.hunks[0];
const fnLine = hunk.lines[1];
expect(fnLine.tokens).toBeDefined();
expect(fnLine.tokens!.some((t) => t.text === "fn" && t.style === "keyword")).toBe(true);
expect(hunk.lines[1].tokens).toContainEqual(
expect.objectContaining({ text: "fn", style: "keyword" }),
);
const addedLine = hunk.lines.find(
(line) => line.type === "add" && line.content.includes("version"),
);
expect(addedLine?.tokens).toBeDefined();
expect(addedLine!.tokens!.some((t) => t.text === "2" && t.style === "number")).toBe(true);
expect(addedLine?.tokens).toContainEqual(
expect.objectContaining({ text: "2", style: "number" }),
);
});
it("adds syntax highlighting tokens to C code", () => {
@@ -367,15 +362,14 @@ describe("highlightDiffFile", () => {
const highlighted = highlightDiffFile(files[0]);
const hunk = highlighted.hunks[0];
const mainLine = hunk.lines[1];
expect(mainLine.tokens).toBeDefined();
expect(mainLine.tokens!.length).toBeGreaterThan(0);
expect(hunk.lines[1].tokens?.length).toBeGreaterThan(0);
const addedLine = hunk.lines.find(
(line) => line.type === "add" && line.content.includes("version"),
);
expect(addedLine?.tokens).toBeDefined();
expect(addedLine!.tokens!.some((t) => t.text === "2" && t.style === "number")).toBe(true);
expect(addedLine?.tokens).toContainEqual(
expect.objectContaining({ text: "2", style: "number" }),
);
});
it("adds syntax highlighting tokens to Java code", () => {
@@ -383,15 +377,16 @@ describe("highlightDiffFile", () => {
const highlighted = highlightDiffFile(files[0]);
const hunk = highlighted.hunks[0];
const classLine = hunk.lines[1];
expect(classLine.tokens).toBeDefined();
expect(classLine.tokens!.some((t) => t.text === "public" && t.style === "keyword")).toBe(true);
expect(hunk.lines[1].tokens).toContainEqual(
expect.objectContaining({ text: "public", style: "keyword" }),
);
const addedLine = hunk.lines.find(
(line) => line.type === "add" && line.content.includes("version"),
);
expect(addedLine?.tokens).toBeDefined();
expect(addedLine!.tokens!.some((t) => t.text === "2" && t.style === "number")).toBe(true);
expect(addedLine?.tokens).toContainEqual(
expect.objectContaining({ text: "2", style: "number" }),
);
});
it("adds syntax highlighting tokens to Objective-C file extensions", () => {
@@ -402,8 +397,9 @@ describe("highlightDiffFile", () => {
const addedLine = hunk.lines.find(
(line) => line.type === "add" && line.content.includes("version"),
);
expect(addedLine?.tokens).toBeDefined();
expect(addedLine!.tokens!.some((t) => t.text === "2" && t.style === "number")).toBe(true);
expect(addedLine?.tokens).toContainEqual(
expect.objectContaining({ text: "2", style: "number" }),
);
});
it("adds syntax highlighting tokens to Go code", () => {
@@ -413,8 +409,9 @@ describe("highlightDiffFile", () => {
(line) => line.type === "add" && line.content.includes("version"),
);
expect(addedLine?.tokens).toBeDefined();
expect(addedLine!.tokens!.some((t) => t.text === "2" && t.style === "number")).toBe(true);
expect(addedLine?.tokens).toContainEqual(
expect.objectContaining({ text: "2", style: "number" }),
);
});
it("adds syntax highlighting tokens to PHP code", () => {
@@ -424,8 +421,9 @@ describe("highlightDiffFile", () => {
(line) => line.type === "add" && line.content.includes("$version"),
);
expect(addedLine?.tokens).toBeDefined();
expect(addedLine!.tokens!.some((t) => t.text === "2" && t.style === "number")).toBe(true);
expect(addedLine?.tokens).toContainEqual(
expect.objectContaining({ text: "2", style: "number" }),
);
});
it("adds syntax highlighting tokens to YAML code", () => {
@@ -435,8 +433,7 @@ describe("highlightDiffFile", () => {
(line) => line.type === "add" && line.content.includes("count"),
);
expect(addedLine?.tokens).toBeDefined();
expect(addedLine!.tokens!.length).toBeGreaterThan(0);
expect(addedLine?.tokens?.length).toBeGreaterThan(0);
});
it("adds syntax highlighting tokens to XML code", () => {
@@ -446,8 +443,7 @@ describe("highlightDiffFile", () => {
(line) => line.type === "add" && line.content.includes("<count>"),
);
expect(addedLine?.tokens).toBeDefined();
expect(addedLine!.tokens!.some((t) => t.style === "tag")).toBe(true);
expect(addedLine?.tokens).toContainEqual(expect.objectContaining({ style: "tag" }));
});
});
@@ -456,7 +452,9 @@ describe("parseAndHighlightDiff", () => {
const files = parseAndHighlightDiff(SIMPLE_DIFF);
expect(files).toHaveLength(1);
expect(files[0].hunks[0].lines[1].tokens).toBeDefined();
expect(files[0].hunks[0].lines[1].tokens).toContainEqual(
expect.objectContaining({ text: "const", style: "keyword" }),
);
});
it("handles multiple files", () => {
+42 -1
View File
@@ -3,7 +3,13 @@ import type {
CheckoutPrStatusResponse,
PullRequestTimelineResponse,
} from "@server/shared/messages";
import { deriveAvatarColor, formatAge, mapPrPaneData } from "./pr-pane-data";
import {
deriveAvatarColor,
formatAge,
getActivityVerb,
getStateLabel,
mapPrPaneData,
} from "./pr-pane-data";
type CheckoutPrStatus = NonNullable<CheckoutPrStatusResponse["payload"]["status"]>;
type PullRequestTimeline = PullRequestTimelineResponse["payload"];
@@ -335,3 +341,38 @@ describe("formatAge", () => {
expect(formatAge(now - 365 * 24 * 60 * 60_000, now)).toBe("1y ago");
});
});
describe("getStateLabel", () => {
it.each([
["open", "Open"],
["draft", "Draft"],
["merged", "Merged"],
["closed", "Closed"],
] as const)("maps %s → %s", (state, expected) => {
expect(getStateLabel(state)).toBe(expected);
});
});
describe("getActivityVerb", () => {
it("returns Commented for comment kind", () => {
expect(getActivityVerb({ kind: "comment" })).toBe("Commented");
});
it("returns Approved for approved review", () => {
expect(getActivityVerb({ kind: "review", reviewState: "approved" })).toBe("Approved");
});
it("returns Requested changes for changes_requested review", () => {
expect(getActivityVerb({ kind: "review", reviewState: "changes_requested" })).toBe(
"Requested changes",
);
});
it("returns Reviewed for a commented review with body (generic case)", () => {
expect(getActivityVerb({ kind: "review", reviewState: "commented" })).toBe("Reviewed");
});
it("returns Reviewed when reviewState is undefined", () => {
expect(getActivityVerb({ kind: "review" })).toBe("Reviewed");
});
});
+14
View File
@@ -225,3 +225,17 @@ function hashLogin(login: string): number {
}
return hash;
}
export function getStateLabel(state: PrState): string {
if (state === "draft") return "Draft";
if (state === "merged") return "Merged";
if (state === "closed") return "Closed";
return "Open";
}
export function getActivityVerb(item: Pick<PrPaneActivity, "kind" | "reviewState">): string {
if (item.kind === "comment") return "Commented";
if (item.reviewState === "approved") return "Approved";
if (item.reviewState === "changes_requested") return "Requested changes";
return "Reviewed";
}
@@ -49,7 +49,7 @@ describe("configToDraft", () => {
expect(devRow.commandOriginalKind).toBe("string");
expect(devRow.type).toBe("long-running");
expect(devRow.portText).toBe("3000");
expect(devRow.id).toBeTruthy();
expect(devRow.id).toMatch(/^script-draft-\d+$/);
expect(buildRow.name).toBe("build");
expect(buildRow.commandText).toBe("npm\nrun\nbuild");
expect(buildRow.commandOriginalKind).toBe("array");