opencode/packages/app/e2e/regression/settings.spec.ts

1773 lines
75 KiB
TypeScript

import { expect, test, type Page } from "@playwright/test"
import type { ConfigEntry, OpenCodeEvent, SessionMessageInfo, WorktreeDirectory } from "@opencode/client/promise"
import { NO_PROVIDER, REMOTE_SERVER, SERVER, holdRoute, project, seed, session } from "../utils/app"
import { mockMissingLocation, mockOpenCodeServer } from "../utils/mock-server"
import { mockRemoteServer, mockWorkspace, openSession, openSettings, type WorkspaceInput } from "../utils/workspace"
const directory = "C:/Projects/settings-demo"
const projectID = "proj_settings_demo"
const sandboxes = Array.from({ length: 12 }, (_, index) => `${directory}/workspace-${index + 1}`)
const override =
"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16'%3E%3Crect width='16' height='16' fill='red'/%3E%3C/svg%3E"
const contributors = "https://api.github.com/repos/anomalyco/opencode/contributors?anon=1&per_page=1"
test.use({ serviceWorkers: "block" })
// One project with 12 worktrees, each with one session, and a configured zsh shell.
function open(page: Page, input: Partial<WorkspaceInput> = {}) {
return openSettings(page, {
name: "Settings demo",
directory,
project: { icon: { color: "orange", override }, commands: { start: "echo setup" }, sandboxes },
provider: NO_PROVIDER,
configEntries: [
{ type: "document", path: "/home/test/.config/opencode/opencode.jsonc", info: { shell: "/bin/zsh" } },
{ type: "directory", path: "/home/test/.config/opencode" },
],
shells: [
{ path: "/bin/zsh", name: "zsh", acceptable: true },
{ path: "/bin/bash", name: "bash", acceptable: true },
],
sessions: sandboxes.map((item, index) => ({
id: `ses_settings_${index + 1}`,
title: `Workspace ${index + 1} session`,
directory: item,
})),
...input,
seed: { tabs: [], ...input.seed },
})
}
async function openProject(page: Page, name = "Settings demo") {
const settings = page.getByTestId("settings-screen")
await settings.getByRole("tab", { name: "Projects", exact: true }).click()
await settings.getByRole("button", { name, exact: true }).click()
await expect(settings.getByRole("button", { name: "Back to projects", exact: true })).toBeVisible()
}
const patched = (page: Page) =>
page.waitForRequest(
(request) => request.method() === "PATCH" && new URL(request.url()).pathname === `/api/project/${projectID}`,
)
test("settings has its own route and returns through app history", async ({ page }) => {
const { settings } = await open(page)
const home = page.getByRole("button", { name: "Home", exact: true })
await expect(page).toHaveURL("/settings")
await expect(home).toHaveAttribute("aria-pressed", "false")
await settings.getByRole("button", { name: "Back to app", exact: true }).click()
await expect(page).toHaveURL("/")
await expect(home).toHaveAttribute("aria-pressed", "true")
await page.keyboard.press("Control+]")
await expect(page).toHaveURL("/settings")
await expect(home).toHaveAttribute("aria-pressed", "false")
await home.click()
await expect(page).toHaveURL("/")
await expect(settings).toBeHidden()
})
test("Ctrl+, opens settings as soon as the app loads", async ({ page }) => {
await mockWorkspace(page, {
name: "Settings demo",
directory,
provider: NO_PROVIDER,
sessions: [],
seed: { tabs: [] },
})
await page.goto("/")
await page.keyboard.press("Control+,")
await expect(page.getByTestId("settings-screen")).toBeVisible()
await expect(page).toHaveURL("/settings")
})
test("a settings page survives refresh", async ({ page }) => {
const { settings } = await open(page)
const appearance = settings.getByRole("tab", { name: "Appearance", exact: true })
await appearance.click()
await expect(page).toHaveURL("/settings?tab=appearance")
await page.reload()
await expect(appearance).toHaveAttribute("aria-selected", "true")
await expect(page).toHaveURL("/settings?tab=appearance")
})
for (const locale of ["en", "ar"]) {
test(`background activity alignment stays physical and persists (${locale})`, async ({ page }) => {
const id = "ses_activity_settings"
const childID = "ses_activity_settings_child"
const stopped: string[] = []
page.on("request", (request) => {
if (request.method() === "POST" && new URL(request.url()).pathname.endsWith("/interrupt"))
stopped.push(request.url())
if (request.method() === "DELETE" && new URL(request.url()).pathname.startsWith("/api/shell/"))
stopped.push(request.url())
})
await openSession(page, {
name: "Activity settings",
sessions: [
{ id, title: "Activity settings" },
{ id: childID, parentID: id, title: "Inspect capsule" },
],
sessionStatus: { [id]: { type: "busy" }, [childID]: { type: "busy" } },
seed: { locale },
pageMessages: () => ({
items: [
{ id: "msg_activity_user", type: "user", text: "Inspect the activity capsule", time: { created: 1 } },
{
id: "msg_activity_assistant",
type: "assistant",
agent: "build",
model: { id: "model", providerID: "provider" },
content: [
{
type: "tool",
id: "call_activity_child",
name: "subagent",
state: {
status: "running",
input: { agent: "explore", description: "Inspect capsule" },
metadata: { sessionID: childID },
},
time: { created: 2 },
},
{
type: "tool",
id: "call_activity_shell",
name: "shell",
state: {
status: "completed",
input: { command: "sleep 120" },
content: [{ type: "text", text: "working" }],
metadata: { shellID: "shell_activity_settings", status: "running" },
},
time: { created: 2, completed: 3 },
},
],
time: { created: 2 },
},
],
}),
shellCommands: [
{
id: "shell_activity_settings",
status: "running",
command: "sleep 120",
cwd: "C:/OpenCode/Activity settings",
shell: "bash",
file: "/tmp/activity.out",
metadata: { sessionID: id },
time: { started: 2 },
},
],
})
const capsule = page.locator('[data-slot="session-activity-chip"]')
const panel = page.locator('[data-slot="session-activity-panel"]')
await expect(capsule).toBeVisible()
await expect(page.locator("html")).toHaveAttribute("dir", locale === "ar" ? "rtl" : "ltr")
for (const value of ["Center", "Right", "Hidden", "Left", "Right"] as const) {
await page.keyboard.press("Control+,")
const settings = page.getByTestId("settings-screen")
const control = settings.getByLabel("Background activity", { exact: true })
await expect(control).toBeVisible()
await control.click()
const options = page.getByRole("listbox")
await expect(options.getByRole("option")).toHaveText(["Hidden", "Left", "Center", "Right"])
await options.getByRole("option", { name: value, exact: true }).click()
await expect(control).toHaveText(value)
await page.goBack()
if (value === "Hidden") {
await expect(capsule).toHaveCount(0)
await expect(panel).toHaveCount(0)
continue
}
await expect(capsule).toBeVisible()
await expect
.poll(async () => {
const anchor = await capsule.boundingBox()
const container = await page.locator('[data-component="session-composer-lane"]').boundingBox()
if (!anchor || !container) return Infinity
const offset = {
Left: anchor.x - container.x,
Center: anchor.x + anchor.width / 2 - container.x - container.width / 2,
Right: anchor.x + anchor.width - container.x - container.width,
}
return Math.abs(offset[value])
})
.toBeLessThan(1)
await capsule.click()
await expect(panel.getByRole("menuitem")).toHaveCount(2)
await expect
.poll(async () => {
const anchor = await capsule.boundingBox()
const bounds = await panel.boundingBox()
if (!anchor || !bounds) return Infinity
const offset = {
Left: anchor.x - bounds.x,
Center: anchor.x + anchor.width / 2 - bounds.x - bounds.width / 2,
Right: anchor.x + anchor.width - bounds.x - bounds.width,
}
return Math.abs(offset[value])
})
.toBeLessThan(1)
await page.keyboard.press("Escape")
}
expect(stopped).toEqual([])
await expect
.poll(() =>
page.evaluate(() => JSON.parse(localStorage.getItem("settings.v3") ?? "{}").general?.backgroundActivity),
)
.toBe("right")
await page.keyboard.press("Control+,")
await page.reload()
await expect(page.getByTestId("settings-screen").getByLabel("Background activity", { exact: true })).toHaveText(
"Right",
)
})
}
test("another server's settings page survives refresh", async ({ page }) => {
await mockRemoteServer(page, { directory: "/remote/settings-demo" })
const { settings } = await open(page)
const url = (value: URL) =>
value.pathname === "/settings" &&
value.searchParams.get("server") === REMOTE_SERVER &&
value.searchParams.get("tab") === "providers"
await page.goto(`/settings?server=${encodeURIComponent(REMOTE_SERVER)}&tab=providers`)
await expect(settings.getByRole("heading", { name: "Providers", exact: true })).toBeVisible()
await expect(page).toHaveURL(url)
await page.reload()
await expect(settings.getByRole("heading", { name: "Providers", exact: true })).toBeVisible()
await expect(page).toHaveURL(url)
})
test("single-server settings expose scoped pages without a server picker", async ({ page }) => {
const { settings } = await open(page, { hostname: "hailmary" })
await expect(settings.getByRole("tab", { name: "Server", exact: true })).toBeVisible()
await expect(settings.getByRole("tab", { name: "Servers", exact: true })).toHaveCount(0)
for (const name of ["Projects", "Worktrees", "Providers", "Models", "Extensions"]) {
await settings.getByRole("tab", { name, exact: true }).click()
await expect(settings.getByRole("tab", { name, exact: true })).toHaveAttribute("aria-selected", "true")
await expect(settings.locator('[data-action="settings-server-select"]')).toHaveCount(0)
await expect(settings.getByText(/hailmary|This computer|Local server/i)).toHaveCount(0)
}
await settings.getByRole("tab", { name: "Server", exact: true }).click()
await expect(settings.getByText("Terminal shell", { exact: true })).toBeVisible()
await settings.getByText("zsh", { exact: true }).click()
const updated = page.waitForRequest(
(request) => request.method() === "PATCH" && new URL(request.url()).pathname === "/api/experimental/config",
)
await page.getByRole("option", { name: "bash", exact: true }).click()
expect((await updated).postDataJSON()).toEqual({ shell: "bash" })
})
test("several servers share one selected server across per-server pages", async ({ page }) => {
const offline = "http://127.0.0.1:4099"
await mockRemoteServer(page, {
name: "Build server",
directory: "/remote/settings-demo",
provider: {
all: [{ id: "openrouter", name: "OpenRouter", models: { kimi: { id: "kimi", name: "Kimi K2.5" } } }],
connected: ["openrouter"],
default: { providerID: "openrouter", modelID: "kimi" },
},
integrations: [{ id: "openrouter", name: "OpenRouter", methods: [{ type: "key" }], connections: [] }],
})
// Nothing answers on the offline server.
await seed(page, {
servers: [
{ url: REMOTE_SERVER, name: "Build server" },
{ url: offline, name: "Offline box" },
],
})
const { settings } = await open(page, { hostname: "hailmary" })
const switcher = settings.locator('[data-action="settings-server-select"]:visible')
const connected = settings.locator('[data-component="connected-providers-section"]')
await settings.getByRole("tab", { name: "Providers", exact: true }).click()
// The server the app runs beside is named by its hostname; only the menu that chooses a server adds "This computer".
await expect(switcher).toHaveText("Serverhailmary")
await expect(connected.getByText("No connected providers")).toBeVisible()
await switcher.click()
await expect(page.getByRole("menuitemradio")).toHaveText(["hailmary· This computer", "Build server", /^Offline box/])
await page.getByRole("menuitemradio", { name: "Build server", exact: true }).click()
await expect(connected.getByText("OpenRouter", { exact: true })).toBeVisible()
await expect(page).toHaveURL(
(url) => url.searchParams.get("server") === REMOTE_SERVER && url.searchParams.get("tab") === "providers",
)
await settings.getByRole("tab", { name: "Models", exact: true }).click()
await expect(switcher).toHaveText("ServerBuild server")
await expect(settings.getByRole("switch", { name: "Kimi K2.5", exact: true })).toBeVisible()
await switcher.click()
await page.getByRole("menuitemradio", { name: /^Offline box/ }).click()
await expect(settings.getByRole("status").filter({ hasText: "Can't reach Offline box" })).toBeVisible()
await expect(settings.getByRole("button", { name: "Retry", exact: true })).toBeVisible()
await expect(settings.getByRole("button", { name: "Edit server", exact: true })).toBeVisible()
})
test("project list menus rename, edit, add, and stay inside the scrollport", async ({ page }) => {
const projects = ["rebase", "dinocms", "opencode", "Playground"].map((name, index) =>
project({ id: `project-${index}`, directory: `/projects/${name}`, name }),
)
const added = project({ id: "project-added", directory: "/projects/added", name: "added" })
const { settings } = await open(page, {
name: "rebase",
directory: "/projects/rebase",
project: { id: "project-0" },
projects,
// The server registers a project when it first resolves its directory.
onLocationGet: (directory) => {
if (directory === added.worktree && !projects.includes(added)) projects.push(added)
},
sessions: [],
fileList: () => [],
})
await settings.getByRole("tab", { name: "Projects", exact: true }).click()
const panel = settings.getByRole("tabpanel")
const list = panel.getByRole("list")
await expect(list.getByRole("listitem")).toHaveCount(4)
const card = list.getByRole("listitem").filter({ hasText: "rebase" })
const more = card.getByRole("button", { name: "More options", exact: true })
await more.click()
const menu = page.getByRole("menu")
await expect(menu.getByRole("menuitem")).toHaveText(["Edit", "Rename", "Clear notifications"])
await menu.getByRole("menuitem", { name: "Edit", exact: true }).click()
await expect(panel.getByRole("heading", { name: "rebase", exact: true })).toBeVisible()
await settings.getByRole("button", { name: "Back to projects", exact: true }).click()
await page.setViewportSize({ width: 600, height: 720 })
// Each project card stays fully inside every horizontal clip ancestor.
await expect
.poll(() =>
card.evaluate((row) => {
const bounds = row.getBoundingClientRect()
const clips = []
for (let parent = row.parentElement; parent; parent = parent.parentElement) {
if (getComputedStyle(parent).overflowX === "visible") continue
const clip = parent.getBoundingClientRect()
clips.push(bounds.left - clip.left, clip.right - bounds.right)
}
return Math.min(...clips)
}),
)
.toBeGreaterThanOrEqual(4)
await expect(panel).toHaveJSProperty("scrollWidth", await panel.evaluate((element) => element.clientWidth))
await page.setViewportSize({ width: 1280, height: 720 })
await more.click()
await menu.getByRole("menuitem", { name: "Rename", exact: true }).click()
const rename = panel.getByRole("textbox", { name: "Rename", exact: true })
await expect(rename).toBeFocused()
await rename.fill("Renamed project")
const renamed = page.waitForRequest(
(request) => request.method() === "PATCH" && new URL(request.url()).pathname === "/api/project/project-0",
)
await rename.press("Enter")
expect((await renamed).postDataJSON()).toEqual({ name: "Renamed project" })
await expect(panel.getByRole("button", { name: "Renamed project", exact: true })).toBeVisible()
await panel.getByRole("button", { name: "Add project", exact: true }).click()
const picker = page.getByRole("dialog", { name: "Open project", exact: true })
await picker.getByRole("combobox").fill("/projects/added")
await picker.getByRole("combobox").press("Enter")
const select = picker.getByRole("button", { name: "Select folder", exact: true })
await expect(select).toBeEnabled()
await select.click()
await expect(picker).toBeHidden()
await expect(panel.getByRole("heading", { name: "added", exact: true })).toBeVisible()
})
test("project settings open as a nested view that keeps its route", async ({ page }) => {
const { settings } = await open(page)
await openProject(page)
await expect(settings.getByRole("tab", { name: "General", exact: true })).toBeVisible()
await expect(settings.getByRole("tab", { name: "Extensions", exact: true })).toBeVisible()
await expect(settings.getByRole("tab", { name: "Scripts", exact: true })).toHaveCount(0)
const menu = page.getByRole("menu")
await settings.locator(".settings-tab-header").getByRole("button", { name: "More options", exact: true }).click()
await expect(menu.getByRole("menuitem")).toHaveText(["Clear notifications"])
// Escape must reach the menu, not the settings screen behind it.
await expect.poll(() => menu.evaluate((element) => element.contains(document.activeElement))).toBe(true)
await page.keyboard.press("Escape")
await expect(menu).toBeHidden()
await expect(settings.getByRole("button", { name: "Back to projects", exact: true })).toBeVisible()
await settings.getByRole("tab", { name: "Worktrees", exact: true }).click()
await expect(settings.getByRole("heading", { name: "Worktrees", exact: true })).toBeVisible()
const route = (url: URL) =>
url.pathname === "/settings" &&
url.searchParams.get("server") === SERVER &&
url.searchParams.get("project") === directory &&
url.searchParams.get("tab") === "workspaces"
await expect(page).toHaveURL(route)
await page.reload()
await expect(settings.getByRole("heading", { name: "Worktrees", exact: true })).toBeVisible()
await expect(page).toHaveURL(route)
await page.keyboard.press("Escape")
await expect(settings.getByRole("heading", { name: "Projects", exact: true })).toBeVisible()
})
// The desktop app reopens its last settings URL on launch, so a crash on this page would repeat on every restart.
test("a project whose folder is gone opens its settings with a notice", async ({ page }) => {
await mockWorkspace(page, {
name: "Settings demo",
directory,
provider: NO_PROVIDER,
sessions: [],
seed: { tabs: [] },
})
await mockMissingLocation(page, directory)
const plugins = page.waitForResponse((response) => {
const url = new URL(response.url())
return url.pathname === "/api/plugin" && url.searchParams.get("location[directory]") === directory
})
await page.goto(
`/settings?server=${encodeURIComponent(SERVER)}&project=${encodeURIComponent(directory)}&tab=extensions`,
)
expect((await plugins).status()).toBe(404)
const settings = page.getByTestId("settings-screen")
const notice = settings.getByRole("status").filter({ hasText: "Project folder not found" })
await expect(notice).toContainText(directory)
await settings.getByRole("tab", { name: "Plugins", exact: true }).click()
await expect(
settings.getByRole("tabpanel", { name: "Plugins", exact: true }).getByText("No plugins yet", { exact: true }),
).toBeVisible()
await settings.getByRole("tab", { name: "General", exact: true }).click()
await expect(settings.getByRole("textbox", { name: "Project name", exact: true })).toBeVisible()
await expect(notice).toContainText(directory)
})
for (const field of [
{
name: "color",
label: "",
initial: "orange",
next: "blue",
patches: [{ icon: { color: "blue", override: "" } }, { icon: { color: "orange", override: "" } }],
},
{
name: "name",
label: "Project name",
initial: "Settings demo",
next: "Renamed project",
patches: [{ name: "Renamed project" }, { name: "Settings demo" }],
},
{
name: "startup script",
label: "Worktree startup script",
initial: "echo setup",
next: "bun install",
patches: [{ commands: { start: "bun install" } }, { commands: { start: "echo setup" } }],
},
]) {
test(`project autosave keeps the final ${field.name} when reverting during a save`, async ({ page }) => {
const { settings } = await open(page, {
project: { icon: { color: "orange" }, commands: { start: "echo setup" }, sandboxes },
})
await openProject(page)
const hold = await holdRoute(page, (url) => url.pathname === `/api/project/${projectID}`, { method: "PATCH" })
const edit = async (value: string) => {
if (field.name === "color") {
await settings.getByRole("button", { name: `Select ${value} color`, exact: true }).click()
return
}
const input = settings.getByRole("textbox", { name: field.label, exact: true })
await input.fill(value)
await input.blur()
}
await edit(field.next)
await hold.arrived
await edit(field.initial)
expect(hold.requests.map((request) => request.postDataJSON())).toEqual([field.patches[0]])
hold.release()
await expect.poll(() => hold.requests.map((request) => request.postDataJSON())).toEqual(field.patches)
await expect(settings.locator('[aria-busy="true"]')).toHaveCount(0)
await settings.getByRole("tab", { name: "Worktrees", exact: true }).click()
await settings.getByRole("tab", { name: "General", exact: true }).click()
if (field.name === "color") {
await expect(settings.getByRole("button", { name: "Select orange color", exact: true })).toHaveAttribute(
"aria-pressed",
"true",
)
return
}
await expect(settings.getByRole("textbox", { name: field.label, exact: true })).toHaveValue(field.initial)
})
}
test("clearing project fields sends explicit removal values", async ({ page }) => {
const { settings } = await open(page)
await openProject(page)
const startup = settings.getByRole("textbox", { name: "Worktree startup script", exact: true })
await expect(startup).toHaveValue("echo setup")
const icon = settings.getByRole("button", { name: "Project icon", exact: true })
await expect(icon.locator("img")).toHaveCount(1)
const color = settings.getByRole("button", { name: "Select orange color", exact: true })
for (const step of [
{
act: async () => {
await startup.clear()
await startup.blur()
},
patch: { commands: { start: "" } },
},
{ act: () => icon.click(), patch: { icon: { color: "orange", override: "" } } },
{
act: async () => {
await expect(color).toHaveAttribute("aria-pressed", "true")
await color.click()
},
patch: { icon: { color: "", override: "" } },
},
]) {
const saved = patched(page)
await step.act()
expect((await saved).postDataJSON()).toEqual(step.patch)
await expect(settings.locator('[aria-busy="true"]')).toHaveCount(0)
}
})
test("shortcuts list Search sessions once and unbind a shortcut while recording it", async ({ page }) => {
// Opening Settings from Home registers Home's Find, which must not add a second Search sessions.
const { settings } = await open(page)
await settings.getByRole("tab", { name: "Shortcuts", exact: true }).click()
await expect(settings.locator('[data-keybind-id="sessions.search"]')).toBeVisible()
await expect(settings.getByText("Search sessions", { exact: true })).toHaveCount(1)
const binding = settings.locator('[data-keybind-id="settings.open"]')
const unbind = settings.getByRole("button", { name: "Unbind", exact: true })
await expect(binding).toHaveText("Ctrl+,")
await expect(unbind).toHaveCount(0)
await binding.click()
await expect(binding).toHaveText("Press keys")
await unbind.click()
await expect(binding).toHaveText("Unassigned")
await expect(unbind).toHaveCount(0)
// An unassigned shortcut has nothing to unbind.
await binding.click()
await expect(binding).toHaveText("Press keys")
await expect(unbind).toHaveCount(0)
})
for (const own of [false, true]) {
test(`shortcuts list a command that shares Close tab only with its own shortcut: ${own}`, async ({ page }) => {
const { settings } = await open(page, {
seed: { settings: { keybinds: own ? { "terminal.close": "ctrl+alt+e" } : {} } },
})
await settings.getByRole("tab", { name: "Shortcuts", exact: true }).click()
await expect(settings.locator('[data-keybind-id="terminal.new"]')).toBeVisible()
await expect(settings.locator('[data-keybind-id="terminal.close"]')).toHaveText(own ? ["Ctrl+Alt+E"] : [])
})
}
test("the new session shortcut waits for a shortcut recording, then leaves settings", async ({ page }) => {
const { settings } = await open(page)
await settings.getByRole("tab", { name: "Shortcuts", exact: true }).click()
const binding = settings.locator('[data-keybind-id="tab.new"]')
await binding.click()
await expect(binding).toHaveText("Press keys")
await page.keyboard.press("Control+t")
await expect(binding).toHaveText("Ctrl+T")
await expect(page).toHaveURL("/settings?tab=shortcuts")
await expect(page.locator("[data-titlebar-tab]")).toHaveCount(0)
await page.keyboard.press("Control+t")
await expect(page).toHaveURL(/\/new-session\?draftId=.+$/)
await expect(settings).toBeHidden()
await expect(page.locator('[data-component="composer-editor"]')).toBeEditable()
await expect(page.locator('[data-titlebar-tab][data-active="true"]')).toHaveCount(1)
})
test("single extension rows stay aligned when switching tabs", async ({ page }) => {
const { settings } = await open(page, {
mcp: [{ name: "demo-mcp", status: { status: "connected" } }],
plugins: [{ id: "demo-plugin", source: { type: "package", target: "demo-plugin" } }],
skills: [{ name: "demo-skill", description: "Demo skill", path: "/skills/demo/SKILL.md" }],
})
await settings.getByRole("tab", { name: "Extensions", exact: true }).click()
await expect(settings.getByRole("switch", { name: "demo-mcp", exact: true })).toBeChecked()
const mcp = settings.getByRole("tabpanel", { name: "MCPs", exact: true }).locator(".settings-extension-row")
await expect(mcp).toHaveCount(1)
const bounds = await mcp.boundingBox()
expect(bounds).not.toBeNull()
for (const item of [
{ tab: "Plugins", name: "demo-plugin" },
{ tab: "Skills", name: "demo-skill" },
]) {
await settings.getByRole("tab", { name: item.tab, exact: true }).click()
const panel = settings.getByRole("tabpanel", { name: item.tab, exact: true })
await expect(panel.getByText(item.name, { exact: true })).toBeVisible()
const row = panel.locator(".settings-extension-row")
await expect(row).toHaveCount(1)
await expect.poll(() => row.boundingBox()).toEqual(bounds)
}
})
test.describe("pages open before slow data", () => {
test("worktrees", async ({ page }) => {
const { settings } = await open(page)
const inventory = await holdRoute(page, (url) => url.pathname === "/api/worktree", { method: "GET" })
const sessions = await holdRoute(
page,
(url) => url.pathname === "/api/session" && url.searchParams.has("directory"),
)
await settings.getByRole("tab", { name: "Worktrees", exact: true }).click()
await inventory.arrived
await expect(settings.getByRole("heading", { name: "Worktrees", exact: true })).toBeVisible()
await expect(settings.getByRole("button", { name: "Back to app" })).toBeVisible()
await expect(settings.getByText("No worktrees", { exact: true })).toHaveCount(0)
inventory.release()
await expect(settings.getByText(sandboxes[0]!, { exact: true })).toBeVisible()
await expect(settings.getByText("12 worktrees", { exact: true })).toBeVisible()
// Home already listed this session; it renders while the directory reads are still held.
await sessions.arrived
await expect(settings.getByText("Workspace 1 session", { exact: true })).toBeVisible()
sessions.release()
const refresh = await holdRoute(page, (url) => url.pathname === "/api/worktree", { method: "GET" })
await settings.getByRole("tab", { name: "Preferences", exact: true }).click()
await settings.getByRole("tab", { name: "Worktrees", exact: true }).click()
await expect(settings.getByText("Workspace 1 session", { exact: true })).toBeVisible()
refresh.release()
})
test("extensions", async ({ page }) => {
const { settings } = await open(page, { mcp: [{ name: "demo-mcp", status: { status: "connected" } }] })
const mcp = await holdRoute(page, (url) => url.pathname === "/api/mcp")
await settings.getByRole("tab", { name: "Extensions", exact: true }).click()
await mcp.arrived
await expect(settings.getByRole("heading", { name: "Extensions", exact: true })).toBeVisible()
await expect(settings.getByRole("button", { name: "Back to app" })).toBeVisible()
mcp.release()
await settings.getByRole("tab", { name: "MCPs", exact: true }).click()
await expect(settings.getByRole("switch", { name: "demo-mcp" })).toBeChecked()
})
test("extensions show MCP status dots with sign-in, error, and switch controls", async ({ page, context }) => {
const error = "Connection closed: MCP server process exited with code 1"
const signIns: string[] = []
await context.route("https://auth.example.test/**", (route) => route.fulfill({ body: "Sign in" }))
const { settings } = await open(page, {
mcp: [
{ name: "blender", status: { status: "failed", error } },
{ name: "demo-mcp", status: { status: "connected" } },
{ name: "disabled-mcp", status: { status: "disabled" } },
{ name: "stripe", integrationID: "stripe-oauth", status: { status: "needs_auth", error: "Sign in required" } },
],
integrations: [
{ id: "stripe-oauth", name: "Stripe", methods: [{ id: "oauth", type: "oauth" }], connections: [] },
],
onIntegrationOAuth: (input) => {
signIns.push(input.integrationID)
return { url: "https://auth.example.test/authorize" }
},
})
await settings.getByRole("tab", { name: "Extensions", exact: true }).click()
await settings.getByRole("tab", { name: "MCPs", exact: true }).click()
// As in the MCPs dialog, a dot shows each status and the words stay for assistive technology.
await expect(settings.getByRole("switch", { name: "demo-mcp" })).toBeChecked()
await expect(settings.getByRole("switch", { name: "demo-mcp" })).toHaveAccessibleDescription("Connected")
await expect(settings.getByRole("switch", { name: "disabled-mcp" })).toHaveAccessibleDescription("Disabled")
await expect(settings.getByRole("switch", { name: "blender" })).toHaveAccessibleDescription("Failed")
await expect(settings.getByRole("switch")).toHaveCount(3)
const popup = page.waitForEvent("popup")
const signIn = settings.getByRole("button", { name: "Sign in to stripe", exact: true })
await expect(signIn).toHaveAttribute("data-variant", "ghost-muted")
await expect(signIn.locator("svg")).toHaveCount(0)
await signIn.click()
await expect(await popup).toHaveURL("https://auth.example.test/authorize")
expect(signIns).toEqual(["stripe-oauth"])
const action = settings.getByRole("button", { name: "View error for blender", exact: true })
await expect(action).toHaveText("View error")
await expect(action).toHaveAttribute("data-variant", "ghost-muted")
await action.click()
const details = page.getByRole("dialog", { name: "blender", exact: true })
await expect(details).toHaveAccessibleDescription("Connection failed")
await expect(details.getByText(error, { exact: true })).toBeVisible()
})
for (const fails of [false, true]) {
test(`about ${fails ? "keeps its fallback when contributors fail" : "updates contributors later"}`, async ({
page,
}) => {
const { settings } = await open(page)
const gate = Promise.withResolvers<void>()
await page.route(contributors, async (route) => {
await gate.promise
if (fails) return route.abort("failed")
await route.fulfill({
json: [],
headers: {
"access-control-allow-origin": "*",
"access-control-expose-headers": "Link",
Link: `<${contributors}&page=1004>; rel="last"`,
},
})
})
const requested = page.waitForRequest(contributors)
await settings.getByRole("tab", { name: "About", exact: true }).click()
await requested
await expect(settings.getByText("Released under the MIT License", { exact: true })).toBeVisible()
await expect(settings.getByRole("link", { name: "935 others", exact: true })).toBeVisible()
await expect(settings.getByRole("button", { name: "Back to app" })).toBeVisible()
const website = settings.getByRole("link", { name: "www.opencode.ai", exact: true })
await website.focus()
const settled = fails
? page.waitForEvent("requestfailed", (request) => request.url() === contributors)
: page.waitForResponse(contributors)
gate.resolve()
await settled
await expect(settings.getByRole("link", { name: fails ? "935 others" : "988 others", exact: true })).toBeVisible()
await expect(website).toBeFocused()
})
}
})
test("worktrees follow inventory events, wait for session counts, and delete by project", async ({ page }) => {
const empty = `${directory}/empty-workspace`
const discovered = `${directory}/discovered-workspace`
const inventory: WorktreeDirectory[] = [
{ directory },
...[...sandboxes, empty].map((item) => ({ directory: item, strategy: "git" })),
]
const view = await open(page, {
project: { sandboxes: [...sandboxes, empty] },
worktrees: () => inventory,
onWorktreeRemove: (body) => {
inventory.splice(
inventory.findIndex((item) => item.directory === body.directory),
1,
)
},
})
const settings = view.settings
// Holding every directory would fill the request budget; hold only the worktree without sessions.
const sessions = await holdRoute(
page,
(url) => url.pathname === "/api/session" && url.searchParams.get("directory") === empty,
)
await settings.getByRole("tab", { name: "Worktrees", exact: true }).click()
const row = settings.locator(".settings-workspaces-row").filter({ has: page.getByLabel(empty, { exact: true }) })
await expect(row).toContainText("Loading messages")
await settings.getByRole("button", { name: "More options", exact: true }).click()
await expect(page.getByRole("menuitem", { name: "Delete worktrees without sessions", exact: true })).toHaveCount(0)
await page.keyboard.press("Escape")
sessions.release()
await expect(row).toContainText("0 sessions")
const listed = page.waitForResponse(
(response) => new URL(response.url()).pathname === "/api/worktree" && response.request().method() === "GET",
)
const read = page.waitForResponse((response) => {
const url = new URL(response.url())
return url.pathname === "/api/session" && url.searchParams.get("directory") === discovered
})
// Home never listed this session, so only the new worktree's directory read can show it.
view.sessions.push(session({ id: "ses_discovered", directory: discovered, title: "Discovered session", projectID }))
inventory.push({ directory: discovered, strategy: "git" })
// SAFETY: a worktree.updated event carries only the project ID, which is all the app reads from it.
await view.push([
{ id: "evt_settings_worktree_updated", created: Date.now(), type: "worktree.updated", data: { projectID } },
] as OpenCodeEvent[])
expect((await listed).ok()).toBe(true)
await expect(settings.getByText(discovered, { exact: true })).toBeVisible()
expect((await read).ok()).toBe(true)
await expect(settings.getByText("Discovered session", { exact: true })).toBeVisible()
await openProject(page)
await settings.getByRole("tab", { name: "Worktrees", exact: true }).click()
await settings.getByRole("button", { name: "Delete “workspace-1”?", exact: true }).click()
const deleting = page.waitForRequest(
(request) => new URL(request.url()).pathname === "/api/worktree" && request.method() === "DELETE",
)
await page
.getByRole("dialog", { name: "Delete “workspace-1”?", exact: true })
.getByRole("button", { name: "Delete worktree", exact: true })
.click()
const request = await deleting
expect(new URL(request.url()).searchParams.has("location[directory]")).toBe(false)
expect(request.postDataJSON()).toEqual({ projectID, directory: sandboxes[0], force: true })
await expect(settings.getByText("13 worktrees", { exact: true })).toBeVisible()
await settings.getByRole("button", { name: "Back to projects", exact: true }).click()
await settings.getByRole("tab", { name: "Worktrees", exact: true }).click()
await expect(settings.getByText("13 worktrees", { exact: true })).toBeVisible()
await expect(settings.getByLabel(sandboxes[0]!, { exact: true })).toHaveCount(0)
})
test.describe("worktrees prefetch", () => {
const other = project({ id: "proj_other", directory: "/repo/other", name: "Other project" })
for (const interaction of ["hover", "focus"] as const) {
test(`project Worktrees ${interaction} prefetches only its inventory and reuses the request`, async ({ page }) => {
const { settings } = await open(page)
await page.route(
(url) => url.pathname === "/api/project",
(route) => route.fulfill({ json: [project({ id: projectID, directory, sandboxes }), other] }),
)
const refreshes: string[] = []
const sessions: string[] = []
page.on("request", (request) => {
const url = new URL(request.url())
if (url.pathname === "/api/worktree/refresh") refreshes.push(request.postDataJSON().projectID)
if (url.pathname === "/api/session" && url.searchParams.has("directory"))
sessions.push(url.searchParams.get("directory")!)
})
await openProject(page)
const inventory = await holdRoute(page, (url) => url.pathname === "/api/worktree", { method: "GET" })
const calls = () => inventory.requests.map((request) => new URL(request.url()).searchParams.get("projectID"))
const worktrees = settings.getByRole("tab", { name: "Worktrees", exact: true })
await expect(worktrees).toBeEnabled()
await worktrees[interaction]()
await inventory.arrived
await expect(worktrees).toHaveAttribute("aria-selected", "false")
expect(calls()).toEqual([projectID])
expect(sessions).toEqual([])
if (interaction === "hover") {
const finished = page.waitForEvent(
"requestfinished",
(request) => new URL(request.url()).pathname === "/api/worktree",
)
inventory.release()
await finished
}
await worktrees.click()
await expect(worktrees).toHaveAttribute("aria-selected", "true")
inventory.release()
await expect(settings.getByText("12 worktrees", { exact: true })).toBeVisible()
expect(calls()).toEqual([projectID])
expect(refreshes).toEqual([projectID])
await expect.poll(() => sessions.toSorted()).toEqual(sandboxes.toSorted())
})
}
test("server Worktrees hover only prefetches metadata", async ({ page }) => {
const { settings } = await open(page)
const calls = { projects: 0, worktrees: new Array<string>(), refreshes: new Array<string>() }
page.on("request", (request) => {
if (new URL(request.url()).pathname === "/api/worktree/refresh")
calls.refreshes.push(request.postDataJSON().projectID)
})
await page.route(
(url) => url.pathname === "/api/project",
async (route) => {
calls.projects += 1
await route.fulfill({ json: [project({ id: projectID, directory, sandboxes }), other] })
},
)
await page.route(
(url) => url.pathname === "/api/worktree",
async (route) => {
const requested = new URL(route.request().url()).searchParams.get("projectID") ?? ""
calls.worktrees.push(requested)
if (requested === other.id) return route.fulfill({ json: [{ directory: other.worktree }] })
await route.fallback()
},
)
const worktrees = settings.getByRole("tab", { name: "Worktrees", exact: true })
const fetched = page.waitForEvent(
"requestfinished",
(request) => new URL(request.url()).pathname === "/api/project",
)
await worktrees.hover()
await fetched
await worktrees.focus()
await expect(worktrees).toHaveAttribute("aria-selected", "false")
expect(calls).toEqual({ projects: 1, worktrees: [], refreshes: [] })
await worktrees.click()
await expect(settings.getByText("12 worktrees", { exact: true })).toBeVisible()
expect(calls.projects).toBe(1)
expect(calls.worktrees.toSorted()).toEqual([projectID, other.id].toSorted())
expect(calls.refreshes).toEqual([])
})
})
const lsp: ConfigEntry[] = [
{
type: "document",
path: "/config/opencode.json",
info: { lsp: { typescript: { command: ["typescript-language-server", "--stdio"], extensions: [".ts", ".tsx"] } } },
},
{
type: "document",
path: `${directory}/opencode.jsonc`,
info: { lsp: { typescript: { disabled: true }, rust: { command: ["rust-analyzer"], extensions: [".rs"] } } },
},
]
for (const row of ["configured", "disabled", "failure"] as const) {
test(`project LSPs: ${row}`, async ({ page }) => {
const { settings } = await open(page)
await openProject(page)
await settings.getByRole("tab", { name: "Extensions", exact: true }).click()
const state = { fail: row === "failure" }
const gate = Promise.withResolvers<void>()
await page.route(
(url) => url.pathname === "/api/config",
async (route) => {
await gate.promise
if (state.fail) return route.fulfill({ status: 404, json: {} })
await route.fulfill({ json: row === "disabled" ? [{ type: "document", info: { lsp: false } }] : lsp })
},
)
const requested = page.waitForRequest((request) => new URL(request.url()).pathname === "/api/config")
await settings.getByRole("tab", { name: "LSPs", exact: true }).click()
expect(new URL((await requested).url()).searchParams.get("location[directory]")).toBe(directory)
const panel = settings.getByRole("tabpanel", { name: "LSPs", exact: true })
await expect(panel.getByText("Loading", { exact: true })).toBeVisible()
gate.resolve()
if (row === "disabled") {
await expect(panel.getByText("Language servers disabled", { exact: true })).toBeVisible()
await expect(panel.locator(".project-settings-extension-row")).toHaveCount(0)
return
}
if (row === "failure") {
await expect(panel.getByText("Could not load language server configuration", { exact: true })).toBeVisible()
state.fail = false
await panel.getByRole("button", { name: "Retry", exact: true }).click()
}
const rows = panel.locator(".project-settings-extension-row")
await expect(rows.filter({ hasText: "typescript" })).toContainText("Disabled in config")
await expect(rows.filter({ hasText: "typescript" })).toContainText(".ts, .tsx")
await expect(rows.filter({ hasText: "rust" })).toContainText("Enabled in config")
await expect(panel.getByRole("switch")).toHaveCount(0)
})
}
// Zen and the Console account share the id `opencode`: the provider comes from models.dev, the
// integration carries the account sign-in.
for (const row of [
{ name: "a fresh install offers the Console sign-in", paid: false, connections: [], console: true },
{
name: "a stored Zen API key keeps the Console sign-in",
paid: true,
connections: [{ type: "credential", id: "cred_v1", label: "API key", method: "key" }],
console: true,
},
{
name: "a Console account hides the sign-in row",
paid: true,
connections: [{ type: "credential", id: "cred_account", label: "Clara Team", method: "oauth" }],
console: false,
},
]) {
test(`providers: ${row.name}`, async ({ page }) => {
const { settings } = await open(page, {
provider: {
all: [
{
id: "opencode",
name: "OpenCode Zen",
models: {
"claude-sonnet-4-6": {
id: "claude-sonnet-4-6",
name: "Claude Sonnet 4.6",
cost: { input: row.paid ? 3 : 0, output: 0 },
},
},
},
],
connected: ["opencode"],
default: {},
},
integrations: [
{
id: "opencode",
name: "OpenCode Console",
methods: [
{ id: "device", type: "oauth", label: "OpenCode Console account" },
{ type: "key", label: "API key (service account)" },
],
connections: row.connections,
},
{ id: "opencode-go", name: "OpenCode Go", methods: [{ type: "key" }], connections: [] },
{ id: "anthropic", name: "Anthropic", methods: [{ type: "key" }], connections: [] },
],
})
await settings.getByRole("tab", { name: "Providers", exact: true }).click()
await expect(settings.getByRole("heading", { name: "Popular providers" })).toBeVisible()
const connected = settings.locator('[data-component="connected-providers-section"]')
if (row.paid) await expect(connected.getByText("OpenCode Zen", { exact: true })).toBeVisible()
if (!row.paid) await expect(settings.getByText("No connected providers")).toBeVisible()
// Anthropic only exists in the integration fixture, so its row proves the integration list has loaded.
await expect(settings.getByText("Anthropic", { exact: true })).toBeVisible()
await expect(settings.getByText("OpenCode Console", { exact: true })).toHaveCount(row.console ? 1 : 0)
})
}
const consoleIntegrations = [
{
id: "opencode",
name: "OpenCode Console",
methods: [
{ id: "device", type: "oauth", label: "OpenCode Console account" },
{ type: "key", label: "API key (service account)" },
],
connections: [],
},
{ id: "opencode-go", name: "OpenCode Go", methods: [{ type: "key" }], connections: [] },
]
test("providers: OpenCode Console signs in from its method list", async ({ page, context }) => {
const url = "https://auth.example.test/device?user_code=ABCD-EFGH"
await context.route("https://auth.example.test/**", (route) => route.fulfill({ body: "Sign in" }))
const { settings } = await open(page, { integrations: consoleIntegrations, onIntegrationOAuth: () => ({ url }) })
await settings.getByRole("tab", { name: "Providers", exact: true }).click()
await settings
.locator(".settings-provider-row", { hasText: "OpenCode Console" })
.getByRole("button", { name: "Connect", exact: true })
.click()
const methods = page.getByRole("dialog", { name: "Connect OpenCode Console", exact: true })
// The methods come from the integration in the TUI's order: sign-ins first, API keys last.
await expect(methods.locator('[data-action="provider-connect-method"]')).toHaveText([
"OpenCode Console account",
"API key (service account)",
])
const popup = page.waitForEvent("popup")
await methods.getByRole("button", { name: "OpenCode Console account", exact: true }).click()
await expect(await popup).toHaveURL(url)
const signIn = page.getByRole("dialog", { name: "Connecting to OpenCode Console", exact: true })
await expect(signIn.getByRole("group", { name: "Device code: ABCD-EFGH", exact: true })).toBeVisible()
await expect(signIn.getByRole("button", { name: "Copy sign-in link", exact: true })).toBeVisible()
})
test("providers: OpenCode Go connects with its own methods, not the Console sign-in", async ({ page }) => {
const attempts: string[] = []
const { settings } = await open(page, {
integrations: consoleIntegrations,
onIntegrationOAuth: (input) => {
attempts.push(input.integrationID)
return { url: "https://auth.example.test/device?user_code=ABCD-EFGH" }
},
})
await settings.getByRole("tab", { name: "Providers", exact: true }).click()
await settings
.locator(".settings-provider-row", { hasText: "OpenCode Go" })
.getByRole("button", { name: "Connect", exact: true })
.click()
const dialog = page.getByRole("dialog", { name: "Connect OpenCode Go", exact: true })
await expect(dialog.getByPlaceholder("API key")).toBeVisible()
expect(attempts).toEqual([])
})
test("providers: the free tier upsell opens Go on its own, sized to its content", async ({ page }) => {
const view = await openSession(page, { name: "FreeTier", integrations: consoleIntegrations })
await view.push([
{
id: "evt_free_tier_limit",
created: 1700000000000,
type: "session.step.failed",
location: { directory: view.directory },
durable: { aggregateID: view.session.id, seq: 1, version: 1 },
data: {
sessionID: view.session.id,
assistantMessageID: "msg_free_tier_assistant",
error: { type: "provider.free-limit", message: "Free usage limit reached.", status: 429 },
},
},
])
await page
.getByRole("dialog", { name: "Free limit reached" })
.getByRole("button", { name: "Subscribe", exact: true })
.click()
const dialog = page.getByRole("dialog", { name: "Connect OpenCode Go", exact: true })
const container = page.locator('[data-slot="dialog-container"]')
await expect(dialog.getByPlaceholder("API key")).toBeVisible()
// Nothing to go back to: the upsell opened the dialog straight on Go.
await expect(dialog.getByRole("button", { name: "Navigate back", exact: true })).toHaveCount(0)
await expect.poll(async () => (await container.boundingBox())?.height).toBeLessThan(512)
})
test("providers: the connect dialog lists connected providers and manages their accounts", async ({ page }) => {
const accounts = [
{ type: "credential", id: "cred_work", label: "Work", method: "key" },
{ type: "credential", id: "cred_personal", label: "Personal", method: "key" },
]
const state = { active: "cred_work" }
const activated: string[] = []
const { settings } = await open(page, {
integrations: () => [
{
id: "openai",
name: "OpenAI",
methods: [{ type: "key", label: "API key" }],
connections: accounts.toSorted((a, b) => Number(b.id === state.active) - Number(a.id === state.active)),
},
{ id: "anthropic", name: "Anthropic", methods: [{ type: "key", label: "API key" }], connections: [] },
],
onCredentialActivate: (credentialID) => {
activated.push(credentialID)
state.active = credentialID
},
onCredentialUpdate: (credentialID, body) => {
const account = accounts.find((item) => item.id === credentialID)
if (account && body.label) account.label = body.label
},
})
await settings.getByRole("tab", { name: "Providers", exact: true }).click()
await settings.getByRole("button", { name: "Show more providers", exact: true }).click()
const dialog = page.getByRole("dialog")
const openai = dialog.locator('[data-provider-id="openai"]')
await expect(openai.locator('[data-slot="provider-connected"]')).toHaveText("Work")
await expect(
dialog.locator('[data-provider-id="anthropic"]').locator('[data-slot="provider-connected"]'),
).toHaveCount(0)
const container = page.locator('[data-slot="dialog-container"]')
await expect.poll(async () => (await container.boundingBox())?.height).toBe(512)
const picker = await container.boundingBox()
await openai.click()
await expect(page.getByRole("dialog", { name: "OpenAI", exact: true })).toBeVisible()
// The provider step fits its content below the list's top edge.
await expect.poll(async () => (await container.boundingBox())?.height).toBeLessThan(picker!.height)
expect((await container.boundingBox())?.y).toBe(picker!.y)
const list = dialog.getByRole("radiogroup", { name: "Connected accounts", exact: true })
await expect(list.getByRole("radio", { name: "Work", exact: true })).toHaveAttribute("aria-checked", "true")
// Rows keep their order when the active account changes.
await expect(list.getByRole("radio")).toHaveText(["Personal", "Work"])
await list.getByRole("radio", { name: "Personal", exact: true }).click()
await expect(list.getByRole("radio", { name: "Personal", exact: true })).toHaveAttribute("aria-checked", "true")
await expect(list.getByRole("radio")).toHaveText(["Personal", "Work"])
expect(activated).toEqual(["cred_personal"])
await list.getByRole("button", { name: "Personal options", exact: true }).click()
await page.getByRole("menuitem", { name: "Rename", exact: true }).click()
const name = list.getByRole("textbox", { name: "Account name", exact: true })
await expect(name).toBeFocused()
await expect(name).toHaveValue("Personal")
await name.fill("Home")
await name.press("Enter")
await expect(list.getByRole("radio")).toHaveText(["Home", "Work"])
await expect(list.getByRole("radio", { name: "Home", exact: true })).toHaveAttribute("aria-checked", "true")
await list.getByRole("button", { name: "Home options", exact: true }).click()
await page.getByRole("menuitem", { name: "Rename", exact: true }).click()
await name.fill("Ignored")
await name.press("Escape")
await expect(list.getByRole("radio")).toHaveText(["Home", "Work"])
await expect(page.getByRole("dialog", { name: "OpenAI", exact: true })).toBeVisible()
await list.getByRole("button", { name: "Work options", exact: true }).click()
await page.getByRole("menuitem", { name: "Remove", exact: true }).click()
await expect(dialog.getByText("Remove Work?", { exact: true })).toBeVisible()
const removed = page.waitForRequest(
(request) => request.method() === "DELETE" && new URL(request.url()).pathname === "/api/credential/cred_work",
)
await dialog.getByRole("button", { name: "Remove", exact: true }).click()
await removed
await dialog.getByRole("button", { name: "Add account", exact: true }).click()
await expect(dialog.getByPlaceholder("API key")).toBeVisible()
await dialog.getByRole("button", { name: "Navigate back", exact: true }).click()
await expect(list).toBeVisible()
})
test("providers: adding an account starts a lone method once", async ({ page, context }) => {
await context.route("https://auth.example.test/**", (route) => route.fulfill({ body: "Sign in" }))
const attempts: string[] = []
const { settings } = await open(page, {
integrations: [
...consoleIntegrations.filter((integration) => integration.id !== "opencode-go"),
{
id: "opencode-go",
name: "OpenCode Go",
methods: [{ type: "key" }],
connections: [{ type: "credential", id: "cred_go", label: "Go key", method: "key" }],
},
{
id: "github-copilot",
name: "GitHub Copilot",
methods: [{ id: "device", type: "oauth", label: "GitHub" }],
connections: [{ type: "credential", id: "cred_gh", label: "Octocat", method: "oauth" }],
},
],
onIntegrationOAuth: (input) => {
attempts.push(input.integrationID)
return { url: "https://auth.example.test/device?user_code=GH12-3456" }
},
})
await settings.getByRole("tab", { name: "Providers", exact: true }).click()
await settings.getByRole("button", { name: "Show more providers", exact: true }).click()
const dialog = page.getByRole("dialog")
await dialog.locator('[data-provider-id="opencode-go"]').click()
await dialog.getByRole("button", { name: "Add account", exact: true }).click()
await expect(dialog.getByPlaceholder("API key")).toBeVisible()
expect(attempts).toEqual([])
await dialog.getByRole("button", { name: "Navigate back", exact: true }).click()
await expect(dialog.getByRole("radio", { name: "Go key", exact: true })).toBeVisible()
await dialog.getByRole("button", { name: "Integrations", exact: true }).click()
await dialog.locator('[data-provider-id="github-copilot"]').click()
const popup = page.waitForEvent("popup")
await dialog.getByRole("button", { name: "Add account", exact: true }).click()
await popup
await expect.poll(() => attempts).toEqual(["github-copilot"])
expect(attempts).toEqual(["github-copilot"])
})
test("providers: the account options rename and remove the active account", async ({ page }) => {
const account = { type: "credential", id: "cred_work", label: "Work", method: "key" }
const other = { type: "credential", id: "cred_personal", label: "Personal", method: "key" }
const removed: string[] = []
const { settings } = await open(page, {
provider: { all: [{ id: "openai", name: "OpenAI", models: {} }], connected: ["openai"], default: {} },
integrations: () => [
{
id: "openai",
name: "OpenAI",
methods: [{ type: "key", label: "API key" }],
connections: [account, other].filter((item) => !removed.includes(item.id)),
},
],
onCredentialUpdate: (credentialID, body) => {
const target = [account, other].find((item) => item.id === credentialID)
if (target && body.label) target.label = body.label
},
})
page.on("request", (request) => {
const path = new URL(request.url()).pathname
if (request.method() === "DELETE" && path.startsWith("/api/credential/")) removed.push(path.split("/").at(-1)!)
})
await settings.getByRole("tab", { name: "Providers", exact: true }).click()
const trigger = settings.getByRole("button", { name: "Manage OpenAI accounts", exact: true })
await expect(trigger).toHaveText("Work")
await trigger.click()
await expect(page.getByRole("menuitemradio", { name: "Work", exact: true })).toHaveAttribute("aria-checked", "true")
await expect(page.getByRole("menuitem", { name: "Add account", exact: true })).toBeVisible()
await page.keyboard.press("Escape")
const options = settings.getByRole("button", { name: "Work options", exact: true })
await expect(options).toHaveCSS("height", "28px")
await options.click()
await page.getByRole("menuitem", { name: "Rename", exact: true }).click()
const name = settings.getByRole("textbox", { name: "Account name", exact: true })
await expect(name).toBeFocused()
await expect(name).toHaveValue("Work")
await name.fill("Team")
await name.press("Enter")
await expect(trigger).toHaveText("Team")
expect(other.label).toBe("Personal")
await settings.getByRole("button", { name: "Team options", exact: true }).click()
await page.getByRole("menuitem", { name: "Rename", exact: true }).click()
await name.fill("Ignored")
await name.press("Escape")
await expect(trigger).toHaveText("Team")
await settings.getByRole("button", { name: "Team options", exact: true }).click()
await page.getByRole("menuitem", { name: "Rename", exact: true }).click()
await name.fill("Shared")
await settings.getByRole("tab", { name: "Providers", exact: true }).click()
await expect(trigger).toHaveText("Shared")
await settings.getByRole("button", { name: "Shared options", exact: true }).click()
await page.getByRole("menuitem", { name: "Remove", exact: true }).click()
await expect.poll(() => removed).toEqual(["cred_work"])
})
test("providers: switching to a Zen API key does not wait for a Console workspace", async ({ page }) => {
const accounts = [
{ type: "credential", id: "cred_console", label: "Anomaly", method: "oauth" },
{ type: "credential", id: "cred_zen", label: "Zen key", method: "key" },
]
const state = { active: "cred_console" }
const { settings } = await open(page, {
provider: () =>
state.active === "cred_console"
? {
all: [
{ id: "opencode", integrationID: "opencode", name: "Anomaly / OpenCode", models: {} },
{ id: "console-google", integrationID: "opencode", name: "Anomaly / Google", models: {} },
],
connected: ["opencode", "console-google"],
default: {},
}
: {
all: [
{
id: "opencode",
name: "OpenCode Zen",
models: { paid: { id: "paid", name: "Paid", cost: { input: 3 } } },
},
],
connected: ["opencode"],
default: {},
},
integrations: () => [
{
id: "opencode",
name: "OpenCode Console",
methods: [{ id: "device", type: "oauth", label: "OpenCode Console account" }],
connections: accounts.toSorted((a, b) => Number(b.id === state.active) - Number(a.id === state.active)),
},
],
onCredentialActivate: (credentialID) => {
state.active = credentialID
},
})
await settings.getByRole("tab", { name: "Providers", exact: true }).click()
const trigger = settings.getByRole("button", { name: "Manage OpenCode Console accounts", exact: true })
await expect(trigger).toHaveText("Anomaly")
await trigger.click()
const catalogReads: string[] = []
page.on("request", (request) => {
if (request.method() === "GET" && new URL(request.url()).pathname === "/api/provider")
catalogReads.push(request.url())
})
await page.getByRole("menuitemradio", { name: "Zen key", exact: true }).click()
await expect(page.getByText("OpenCode Console account switched")).toBeVisible()
// One refresh after the switch; a Console workspace poll would keep reading the catalog.
expect(catalogReads).toHaveLength(1)
})
test("providers: adding a Console account keeps the Console row in place", async ({ page, context }) => {
await context.route("https://auth.example.test/**", (route) => route.fulfill({ body: "Sign in" }))
// After the sign-in the server reloads the workspace, briefly serving only the free catalog.
const state = { authorized: false, pendingReads: 0 }
const workspace = {
all: [
{ id: "opencode", integrationID: "opencode", name: "Anomaly / OpenCode", models: {} },
{ id: "console-google", integrationID: "opencode", name: "Anomaly / Google", models: {} },
],
connected: ["opencode", "console-google"],
default: {},
}
const catalog = () => {
if (state.pendingReads > 0) {
state.pendingReads--
return { all: [{ id: "opencode", name: "OpenCode", models: {} }], connected: ["opencode"], default: {} }
}
return workspace
}
const { settings } = await open(page, {
provider: catalog,
integrations: () => [
{
id: "opencode",
name: "OpenCode Console",
methods: [{ id: "device", type: "oauth", label: "OpenCode Console account" }],
connections: [
{ type: "credential", id: "cred_console", label: "Anomaly", method: "oauth" },
...(state.authorized ? [{ type: "credential", id: "cred_clara", label: "Clara", method: "oauth" }] : []),
],
},
{ id: "opencode-go", name: "OpenCode Go", methods: [{ type: "key" }], connections: [] },
],
onIntegrationOAuth: () => ({ url: "https://auth.example.test/device?user_code=GOGO-1234" }),
onIntegrationOAuthStatus: () => {
if (!state.authorized) {
state.authorized = true
state.pendingReads = 3
}
return "complete"
},
})
await settings.getByRole("tab", { name: "Providers", exact: true }).click()
const connected = settings.locator('[data-component="connected-providers-section"]')
await expect(connected.getByText("OpenCode Console", { exact: true })).toBeVisible()
await connected.evaluate((element) => {
new MutationObserver(() => {
if (!element.textContent?.includes("OpenCode Console")) element.dataset.flashed = ""
}).observe(element, { childList: true, subtree: true, characterData: true })
})
await settings.getByRole("button", { name: "Show more providers", exact: true }).click()
const dialog = page.getByRole("dialog")
await dialog.locator('[data-provider-id="opencode"]').click()
const popup = page.waitForEvent("popup")
await dialog.getByRole("button", { name: "Add account", exact: true }).click()
await popup
await expect(page.getByText("OpenCode Console connected", { exact: true })).toBeVisible()
await expect(connected.getByText("OpenCode Console", { exact: true })).toBeVisible()
await expect(connected).not.toHaveAttribute("data-flashed")
})
test("providers: switching Console accounts keeps the list until the new workspace loads", async ({ page }) => {
const accounts = [
{ type: "credential", id: "cred_clara", label: "Clara", method: "oauth" },
{ type: "credential", id: "cred_anomaly", label: "Anomaly", method: "oauth" },
]
// The server loads the new workspace's providers a few catalog reads after the switch.
const state = { active: "cred_clara", pendingReads: 0 }
const workspace = () => accounts.find((account) => account.id === state.active)!.label
const catalog = () => {
if (state.pendingReads > 0) {
state.pendingReads--
return {
all: [{ id: "opencode", name: "OpenCode", models: { free: { id: "free", name: "Free", cost: { input: 0 } } } }],
connected: ["opencode"],
default: {},
}
}
return {
all: [
{ id: "opencode", integrationID: "opencode", name: `${workspace()} / OpenCode`, models: {} },
{ id: "console-google", integrationID: "opencode", name: `${workspace()} / Google`, models: {} },
],
connected: ["opencode", "console-google"],
default: {},
}
}
const { settings } = await open(page, {
provider: catalog,
integrations: () => [
{
id: "opencode",
name: "OpenCode Console",
methods: [{ id: "device", type: "oauth", label: "OpenCode Console account" }],
connections: accounts.toSorted((a, b) => Number(b.id === state.active) - Number(a.id === state.active)),
},
],
onCredentialActivate: (credentialID) => {
state.active = credentialID
state.pendingReads = 2
},
})
await settings.getByRole("tab", { name: "Providers", exact: true }).click()
const connected = settings.locator('[data-component="connected-providers-section"]')
const trigger = connected.getByRole("button", { name: "Manage OpenCode Console accounts", exact: true })
await expect(trigger).toHaveText("Clara")
await connected.evaluate((element) => {
new MutationObserver(() => {
if (element.textContent?.includes("No connected providers")) element.dataset.flashed = ""
}).observe(element, { childList: true, subtree: true, characterData: true })
})
await trigger.click()
await page.getByRole("menuitemradio", { name: "Anomaly", exact: true }).click()
await expect(page.getByText("OpenCode Console account switched")).toBeVisible()
await expect(trigger).toHaveText("Anomaly")
await expect(connected).not.toHaveAttribute("data-flashed")
})
test("the add server dialog keeps focus above fullscreen settings", async ({ page }) => {
await mockRemoteServer(page, { directory: "/remote/settings-demo" })
const { settings } = await open(page)
await expect(page.getByRole("dialog")).toHaveCount(0)
await settings.getByRole("tab", { name: "Servers", exact: true }).click()
await settings.getByRole("button", { name: "Add server" }).click()
const editor = page.getByRole("dialog", { name: "Add server" })
await expect(editor.getByLabel("Pairing link", { exact: true })).toBeFocused()
await expect(editor.getByPlaceholder("password")).toHaveCount(0)
await editor.getByRole("button", { name: "Use password", exact: true }).click()
await expect(editor.getByPlaceholder("username")).toHaveCount(0)
const name = editor.getByPlaceholder("Localhost", { exact: true })
await name.click()
await name.fill("Remote")
await page.keyboard.press("Tab")
await expect(editor.getByPlaceholder("password")).toBeFocused()
await page.keyboard.press("Escape")
await expect(editor).toBeHidden()
await expect(settings).toBeVisible()
})
test("the add server dialog pairs from a one-time link and explains a spent one", async ({ page }) => {
const paired = "http://127.0.0.1:4098"
await mockRemoteServer(page, { directory: "/remote/settings-demo" })
await mockOpenCodeServer(page, {
server: paired,
directory: "/remote/paired",
project: project({ id: "proj_paired", directory: "/remote/paired" }),
provider: NO_PROVIDER,
sessions: [],
pageMessages: () => ({ items: [] }),
password: "session-token",
pairing: { code: "one-time-code", token: "session-token" },
})
const { settings } = await open(page)
const link = `${paired}/auth/connect/one-time-code`
const addServer = async () => {
await settings.getByRole("tab", { name: "Servers", exact: true }).click()
await settings.getByRole("button", { name: "Add server" }).click()
const editor = page.getByRole("dialog", { name: "Add server" })
await editor.getByLabel("Pairing link", { exact: true }).fill(link)
await editor.getByRole("button", { name: "Add server", exact: true }).click()
return editor
}
const added = await addServer()
await expect(added).toBeHidden()
await expect(settings.getByText(paired, { exact: true })).toBeVisible()
const spent = await addServer()
await expect(spent.getByRole("alert")).toHaveText(
"This pairing link expired or was already used. Run opencode pair to get a new one.",
)
})
test("a pairing code with several addresses keeps the first one that works with its token", async ({ page }) => {
// Both addresses reach one server. The second spends the code first, so the first answers 401, and the token works on
// it as on every address of that server.
const first = "http://127.0.0.1:4098"
const second = "http://127.0.0.1:4099"
await mockRemoteServer(page, { directory: "/remote/settings-demo" })
for (const [server, pairing] of [
[first, { code: "spent-by-the-other-address", token: "session-token" }],
[second, { code: "one-time-code", token: "session-token" }],
] as const) {
await mockOpenCodeServer(page, {
server,
directory: "/remote/paired",
project: project({ id: "proj_paired", directory: "/remote/paired" }),
provider: NO_PROVIDER,
sessions: [],
pageMessages: () => ({ items: [] }),
password: "session-token",
pairing,
})
}
const { settings } = await open(page)
await settings.getByRole("tab", { name: "Servers", exact: true }).click()
await settings.getByRole("button", { name: "Add server" }).click()
const editor = page.getByRole("dialog", { name: "Add server" })
await editor
.getByLabel("Pairing link", { exact: true })
.fill(JSON.stringify({ code: "one-time-code", urls: [first, second] }))
await editor.getByRole("button", { name: "Add server", exact: true }).click()
await expect(editor).toBeHidden()
await expect(settings.getByText(first, { exact: true })).toBeVisible()
await expect(settings.getByText(second, { exact: true })).toHaveCount(0)
})
test("the Side tabs interface mode switches to vertical tabs and survives reload", async ({ page }) => {
const { settings } = await open(page)
const layout = settings.getByRole("group", { name: "Interface" })
await expect(layout.getByRole("radio", { name: "Top tabs", exact: true })).toBeChecked()
await layout.getByText("Side tabs", { exact: true }).click()
await expect(layout.getByRole("radio", { name: "Side tabs", exact: true })).toBeChecked()
await expect(page.locator('[data-slot="vertical-tabs-sidebar"]')).toBeVisible()
await expect(page.locator('[data-slot="titlebar-tabs"]')).toHaveCount(0)
await page.reload()
await expect(layout.getByRole("radio", { name: "Side tabs", exact: true })).toBeChecked()
await expect(page.locator('[data-slot="vertical-tabs-sidebar"]')).toBeVisible()
await expect(page.locator('[data-slot="titlebar-tabs"]')).toHaveCount(0)
})
for (const viewport of [
{ name: "desktop", width: 1280, height: 720, bottom: false },
{ name: "mobile", width: 390, height: 844, bottom: true },
]) {
test(`settings layout (${viewport.name}): every page scrolls inside its panel with room below`, async ({ page }) => {
await page.route("https://api.github.com/repos/anomalyco/opencode/contributors?*", (route) =>
route.fulfill({ json: [] }),
)
const { settings } = await open(page)
await page.setViewportSize(viewport)
const panel = settings.locator(".settings-content > .settings-panel:visible")
const main = page.getByRole("main")
if (viewport.bottom) {
const toggle = settings.locator('[data-action="settings-mobile-titlebar-bottom"]')
await toggle.locator('[data-slot="switch-control"]').click()
await expect(toggle.getByRole("switch")).toBeChecked()
}
// Wheel over the outer gutter must not move the entire settings screen.
await main.hover({ position: { x: 1, y: 200 } })
await page.mouse.wheel(0, 10000)
await expect(main).toHaveJSProperty("scrollTop", 0)
if (viewport.name === "desktop") {
// Wheel over the settings gutter scrolls the page beside it.
await settings.hover({ position: { x: 16, y: 200 } })
await page.mouse.wheel(0, 200)
await expect.poll(() => panel.evaluate((element) => element.scrollTop)).toBeGreaterThan(0)
}
const pages = [
"Preferences",
"Appearance",
"Notifications",
"Shortcuts",
"Projects",
"Worktrees",
"Providers",
"Models",
"Extensions",
"Server",
"About",
]
for (const [index, name] of pages.entries()) {
if (viewport.width >= 816) await settings.getByRole("tab", { name, exact: true }).click()
if (viewport.width < 816) {
await settings.getByRole("button", { name: pages[Math.max(0, index - 1)], exact: true }).click()
await page.getByRole("menuitemradio", { name, exact: true }).click()
}
if (name === "About") await expect(panel.getByText("Released under the MIT License")).toBeVisible()
if (name !== "About")
await expect(
panel.getByRole("heading", { name: name === "Shortcuts" ? "Keyboard shortcuts" : name, exact: true }),
).toBeVisible()
if (name === "Worktrees") {
const last = settings.getByText("Workspace 12 session", { exact: true })
await last.scrollIntoViewIfNeeded()
await expect(last).toBeInViewport()
if (!viewport.bottom) await expect(settings.getByRole("button", { name: "Back to app" })).toBeInViewport()
}
await panel.hover()
await page.mouse.wheel(0, 10000)
await expect
.poll(() => panel.evaluate((element) => element.scrollHeight - element.clientHeight - element.scrollTop))
.toBeLessThanOrEqual(1)
await expect
.poll(
() =>
panel.evaluate((element) => {
const body = element.querySelector(".settings-tab-body, .settings-about-content")!
return element.getBoundingClientRect().bottom - body.lastElementChild!.getBoundingClientRect().bottom
}),
{ message: `${name} bottom clearance` },
)
.toBeGreaterThanOrEqual(viewport.bottom ? 119.5 : 79.5)
await expect(main).toHaveJSProperty("scrollTop", 0)
await expect
.poll(() => main.evaluate((element) => element.scrollWidth - element.clientWidth))
.toBeLessThanOrEqual(1)
}
})
}