Compare commits

..

31 Commits

Author SHA1 Message Date
Kit Langton fdd8ad4d3f refactor(core): centralize full-prefix KV scans 2026-08-27 11:40:44 -04:00
Kit Langton 5fb3040505 test(core): scope skill discovery fixtures (#45464) 2026-08-27 11:25:17 -04:00
Kit Langton df7dae3706 refactor(plugin): reuse tool executor conversion (#45572)
Reuse the private executor/progress conversion for Promise tool list, get, and update while preserving captured executors, identifiers, and explicit optional-field clearing. Add focused adapter regression coverage.
2026-08-27 11:25:12 -04:00
Kit Langton 83ff4253f5 test: share session message expectations (#45454) 2026-08-27 10:58:12 -04:00
Kit Langton 89cb5146d4 test(cli): scope temporary directories to test lifetimes (#45467) 2026-08-27 10:57:06 -04:00
James Long b0b5bf6749 feat(tui): jump to background tool starts (#45554) 2026-08-27 10:56:51 -04:00
Kit Langton ef9b9fb6bf test(client): scope service subprocess fixtures per test (#45471) 2026-08-27 10:55:20 -04:00
James Long c05d481ec6 fix(pty): use server shell and session cwd for terminals (#45552) 2026-08-27 10:39:27 -04:00
Shoubhit Dash 8e726dc7d8 fix(core): preserve imported session parents (#45566) 2026-08-27 19:57:59 +05:30
Shoubhit Dash 23f0ee53cf feat(plugin): intercept user prompts before admission (#45550) 2026-08-27 18:58:00 +05:30
Shoubhit Dash 46aa25f236 feat(plugin): expose model generation options to session hooks (#45268) 2026-08-27 17:30:37 +05:30
Brendan Allan 803ead32e7 feat(app): use channel-specific favicon and PWA icons (#45543) 2026-08-27 11:17:11 +00:00
Luke Parker 42422a1e03 fix(app): show sessions while worktrees are created (#45529) 2026-08-27 19:44:23 +10:00
Brendan Allan b1374978c9 fix(app): prevent Safari shell content from collapsing 2026-08-27 16:59:43 +08:00
Luke Parker ed95fdaa27 fix(app): show MCP connection failures as toasts (#45522) 2026-08-27 08:46:54 +00:00
Luke Parker 53a4829672 fix(app): restore fullscreen settings version footer (#45419) 2026-08-27 17:57:04 +10:00
Luke Parker 7036294543 fix(app): align thinking states and reasoning settings (#45515) 2026-08-27 17:50:39 +10:00
opencode-agent[bot] 23506b5fb4 fix(app): scope MCP picker toggles to workspace (#45509)
Co-authored-by: Hona <10430890+Hona@users.noreply.github.com>
2026-08-27 17:20:38 +10:00
Luke Parker 2af02d0ad7 fix(app): use worktree inventory for session accents (#45506) 2026-08-27 07:03:16 +00:00
opencode-agent[bot] 26ee104829 fix(app): prevent renderer OOM on multiline paste (#45497)
Co-authored-by: Brendonovich <14191578+Brendonovich@users.noreply.github.com>
2026-08-27 14:31:28 +08:00
opencode-agent[bot] 8252897a33 fix(app): precache complete builds before serving cached HTML (#45495)
Co-authored-by: Brendonovich <14191578+Brendonovich@users.noreply.github.com>
2026-08-27 14:23:31 +08:00
Luke Parker 7000607fd0 fix(app): stop shimmer when background shells finish (#45494) 2026-08-27 16:15:34 +10:00
opencode-agent[bot] fa1ab5f8e1 fix(app): restore worktree message accent for further trial (#45486)
Co-authored-by: Brendonovich <14191578+Brendonovich@users.noreply.github.com>
2026-08-27 05:18:54 +00:00
Aiden Cline e288e0fc4d feat(plugin): allow tool call repair before lookup (#45453) 2026-08-27 00:10:43 -05:00
Luke Parker ff5b5d00f9 fix(app): preserve tool disclosures when groups update (#45474) 2026-08-27 15:02:39 +10:00
Luke Parker 990f7ee000 fix(app): keep timeline notices on one line (#45479) 2026-08-27 04:47:50 +00:00
Luke Parker e2d6c4bd4a fix(app): merge adjacent patches inside used groups (#45477) 2026-08-27 04:36:27 +00:00
Aiden Cline fcc6568fcb feat(core): adjust bg shell completion msg (include output file) (#45461) 2026-08-26 23:04:11 -05:00
opencode-agent[bot] 1c66cd7832 fix(tui): clarify tool grouping setting (#45470)
Co-authored-by: rekram1-node <rekram1-node@users.noreply.github.com>
2026-08-26 23:02:27 -05:00
Luke Parker 5cc81a497c fix(app): keep active tools in existing groups (#45462) 2026-08-27 03:54:38 +00:00
Kit Langton 10786cb60c refactor(core): consolidate runner capability reads (#45448) 2026-08-26 23:45:01 -04:00
151 changed files with 6342 additions and 2288 deletions
-5
View File
@@ -1,5 +0,0 @@
---
"@opencode-ai/core": minor
---
Rename the Core namespace exports `McpTool` and `McpInstructions` to `MCPTool` and `MCPInstructions`. Update imports to use the new names; module paths and runtime service keys are unchanged.
+6
View File
@@ -244,6 +244,12 @@ jobs:
CI: true
timeout-minutes: 30
- name: Verify service worker precaching and upgrades
if: env.E2E_ENABLED == 'true'
working-directory: packages/app
run: bunx playwright test --config e2e/service-worker/playwright.config.ts
timeout-minutes: 5
- name: Upload Playwright artifacts
if: always() && env.E2E_ENABLED == 'true'
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
@@ -0,0 +1,120 @@
import { expect, test } from "@playwright/test"
import { mockOpenCodeServer } from "../utils/mock-server"
import { expectAppVisible } from "../utils/waits"
const draftID = "draft_large_paste"
const directory = "/repo/large-paste"
const server = `http://${process.env.PLAYWRIGHT_SERVER_HOST ?? "127.0.0.1"}:${process.env.PLAYWRIGHT_SERVER_PORT ?? "4096"}`
test.use({ permissions: ["clipboard-read", "clipboard-write"] })
test.beforeEach(async ({ page }) => {
await mockOpenCodeServer(page, {
directory,
project: {
id: "proj_large_paste",
worktree: directory,
vcs: "git",
name: "large-paste",
time: { created: 1700000000000, updated: 1700000000000 },
sandboxes: [],
},
provider: { all: [], connected: [], default: {} },
sessions: [],
pageMessages: () => ({ items: [] }),
})
await page.addInitScript(
({ directory, draftID, server }) => {
localStorage.setItem("opencode-theme-id", "oc-2")
localStorage.setItem("opencode-color-scheme", "dark")
localStorage.setItem(
"opencode.global.dat:server",
JSON.stringify({
projects: { local: [{ worktree: directory, expanded: true }] },
lastProject: { local: directory },
}),
)
localStorage.setItem(
"opencode.window.browser.dat:tabs",
JSON.stringify([{ type: "draft", draftID, server, directory }]),
)
},
{ directory, draftID, server },
)
await page.goto(`/new-session?draftId=${draftID}`)
const input = page.locator('[data-component="composer-editor"]')
await expectAppVisible(input)
await expect(input).toBeEditable()
await expect
.poll(() => input.evaluate((element) => getComputedStyle(element, "::before").content))
.toBe(`"${String.fromCodePoint(0x200b)}"`)
await input.click()
})
for (const lines of [6000, 25000]) {
test(`keeps a ${lines}-line crash report editable in a new session`, async ({ page }) => {
const input = page.getByRole("textbox", { name: "Prompt", exact: true })
const text = "Thread 0 Crashed:\n" + "0 Example 0x0000000100000000 frame + 32\n".repeat(lines) + "End of report"
await page.evaluate((text) => navigator.clipboard.writeText(text), text)
const events = await input.evaluateHandle((element) => {
const events = { count: 0 }
element.addEventListener("input", () => events.count++)
return events
})
await page.keyboard.press("ControlOrMeta+V")
await expect.poll(async () => (await input.innerText()) === text).toBe(true)
expect(await events.evaluate((events) => events.count)).toBe(1)
await expect(input).toBeFocused()
await page.keyboard.type("!")
await expect.poll(async () => (await input.innerText()) === text + "!").toBe(true)
})
}
for (const text of [
"single line <b> &amp;",
"first\nsecond",
"\n\n indented\ttext \n\nlast\n\n",
'literal <b>bold</b> &amp; & < > "quotes"\n<script>not code</script>\n<img src="example">',
"first\r\nsecond\rthird",
]) {
test(`preserves text and native undo: ${JSON.stringify(text)}`, async ({ page }) => {
const input = page.getByRole("textbox", { name: "Prompt", exact: true })
await page.evaluate((text) => navigator.clipboard.writeText(text), text)
await page.keyboard.press("ControlOrMeta+V")
const expected = text.replace(/\r\n?/g, "\n")
await expect.poll(() => input.innerText()).toBe(expected)
await expect(input.locator("b, script, img")).toHaveCount(0)
await page.keyboard.press("ControlOrMeta+Z")
await expect(input).toBeEmpty()
await page.keyboard.press("ControlOrMeta+Shift+Z")
await expect.poll(() => input.innerText()).toBe(expected)
})
}
test("replaces only the selected text and leaves the caret after the paste", async ({ page }) => {
const input = page.getByRole("textbox", { name: "Prompt", exact: true })
await page.evaluate(() => navigator.clipboard.writeText("one\ntwo"))
await page.keyboard.type("before replace after")
await expect(input).toHaveText("before replace after")
await page.evaluate(() => document.fonts.ready)
const word = await input.evaluate((element) => {
const range = document.createRange()
range.setStart(element.firstChild!, 7)
range.setEnd(element.firstChild!, 14)
const rect = range.getBoundingClientRect()
return { x: rect.x, y: rect.y + rect.height / 2, width: rect.width }
})
await page.mouse.move(word.x, word.y)
await page.mouse.down()
await page.mouse.move(word.x + word.width, word.y, { steps: 5 })
await page.mouse.up()
await expect.poll(() => page.evaluate(() => window.getSelection()?.toString())).toBe("replace")
await page.keyboard.press("ControlOrMeta+V")
await expect.poll(() => input.innerText()).toBe("before one\ntwo after")
await page.keyboard.press("ControlOrMeta+Z")
await expect(input).toHaveText("before replace after")
await page.keyboard.press("ControlOrMeta+Shift+Z")
await expect.poll(() => input.innerText()).toBe("before one\ntwo after")
await page.keyboard.type("!")
await expect.poll(() => input.innerText()).toBe("before one\ntwo! after")
})
@@ -0,0 +1,178 @@
import { base64Encode } from "@opencode-ai/util/encode"
import { expect, test } from "@playwright/test"
import { mockOpenCodeServer } from "../utils/mock-server"
import { expectSessionTitle } from "../utils/waits"
const directory = "C:\\OpenCode\\main"
const workspace = "C:\\OpenCode\\worktree"
const projectID = "proj_mcp_workspace"
const sessionID = "ses_mcp_workspace"
const title = "Workspace MCP routing"
const server = `http://${process.env.PLAYWRIGHT_SERVER_HOST ?? "127.0.0.1"}:${process.env.PLAYWRIGHT_SERVER_PORT ?? "4096"}`
for (const shared of [true, false]) {
test(`toggles the workspace MCP when the default location ${shared ? "has" : "does not have"} the server`, async ({
page,
}, testInfo) => {
const connected = new Set<string>()
const requests: { path: string; directory: string }[] = []
await mockOpenCodeServer(page, {
directory,
project: {
id: projectID,
worktree: directory,
vcs: "git",
name: "mcp-workspace",
time: { created: 1700000000000, updated: 1700000000000 },
sandboxes: [workspace],
},
provider: { all: [], connected: [], default: {} },
sessions: [{ id: sessionID, projectID, directory: workspace, title }],
pageMessages: () => ({ items: [] }),
})
await page.route("**/api/mcp**", async (route) => {
if (route.request().method() === "OPTIONS") return route.fallback()
const url = new URL(route.request().url())
const target = url.searchParams.get("location[directory]") ?? directory
requests.push({ path: url.pathname, directory: target })
if (url.pathname === "/api/mcp/figma-desktop/connect") {
connected.add(target)
return route.fulfill({ status: 204 })
}
if (url.pathname === "/api/mcp/figma-desktop/disconnect") {
connected.delete(target)
return route.fulfill({ status: 204 })
}
return route.fulfill({
json: {
location: { directory: target },
data:
url.pathname === "/api/mcp/resource"
? { resources: [], templates: [] }
: !shared && target !== workspace
? []
: [{ name: "figma-desktop", status: { status: connected.has(target) ? "connected" : "disabled" } }],
},
})
})
await page.goto(`/server/${base64Encode(server)}/session/${sessionID}`)
await expectSessionTitle(page, title)
await expect(page.getByRole("textbox", { name: "Prompt", exact: true })).toBeEditable()
await page.keyboard.press("ControlOrMeta+;")
const dialog = page.getByRole("dialog", { name: "MCPs", exact: true })
await expect(dialog.getByText("figma-desktop", { exact: true })).toBeVisible()
const toggle = dialog.getByRole("switch")
await expect(toggle).not.toBeChecked()
await expect(toggle).toBeEnabled()
requests.length = 0
await dialog.locator('[data-slot="switch-control"]').click()
await expect(toggle).toBeChecked()
await expect(toggle).toBeEnabled()
expect(connected).toEqual(new Set([workspace]))
expect(requests).toContainEqual({ path: "/api/mcp/figma-desktop/connect", directory: workspace })
expect(requests).toContainEqual({ path: "/api/mcp/resource", directory: workspace })
expect(requests.every((request) => request.directory === workspace)).toBe(true)
await testInfo.attach("workspace-connected", { body: await page.screenshot(), contentType: "image/png" })
requests.length = 0
await dialog.getByText("figma-desktop", { exact: true }).click()
await expect(toggle).not.toBeChecked()
await expect(toggle).toBeEnabled()
expect(connected.size).toBe(0)
expect(requests).toContainEqual({ path: "/api/mcp/figma-desktop/disconnect", directory: workspace })
expect(requests.every((request) => request.directory === workspace)).toBe(true)
})
}
for (const surface of ["popover", "dialog"] as const) {
test(`shows connection failures from the MCP ${surface} and allows reconnecting`, async ({ page }, testInfo) => {
const error = "Streamable HTTP error: Error POSTing to endpoint: 404 Not Found"
const state = { fail: true, status: surface === "popover" ? "failed" : "disabled" }
const requests: { path: string; directory: string }[] = []
await page.addInitScript(() => {
localStorage.setItem("settings.v3", JSON.stringify({ general: { showStatus: true } }))
})
await mockOpenCodeServer(page, {
directory,
project: {
id: projectID,
worktree: directory,
vcs: "git",
name: "mcp-workspace",
time: { created: 1700000000000, updated: 1700000000000 },
sandboxes: [workspace],
},
provider: { all: [], connected: [], default: {} },
sessions: [{ id: sessionID, projectID, directory: workspace, title }],
pageMessages: () => ({ items: [] }),
})
await page.route("**/api/mcp**", async (route) => {
if (route.request().method() === "OPTIONS") return route.fallback()
const url = new URL(route.request().url())
const target = url.searchParams.get("location[directory]") ?? directory
requests.push({ path: url.pathname, directory: target })
if (url.pathname === "/api/mcp/figma-desktop/connect") {
state.status = state.fail ? "failed" : "connected"
// Connection failures are reported by the refreshed status, not the HTTP response.
return route.fulfill({ status: 204 })
}
return route.fulfill({
json: {
location: { directory: target },
data:
url.pathname === "/api/mcp/resource"
? { resources: [], templates: [] }
: [
{
name: "figma-desktop",
status: { status: target === workspace ? state.status : "connected", error },
},
],
},
})
})
await page.goto(`/server/${base64Encode(server)}/session/${sessionID}`)
await expectSessionTitle(page, title)
await expect(page.getByRole("textbox", { name: "Prompt", exact: true })).toBeEditable()
if (surface === "popover") await page.getByRole("button", { name: "Status", exact: true }).click()
if (surface === "dialog") await page.keyboard.press("ControlOrMeta+;")
const panel =
surface === "popover" ? page.getByRole("tabpanel") : page.getByRole("dialog", { name: "MCPs", exact: true })
const toggle = panel.getByRole("switch")
await expect(panel.getByText("figma-desktop", { exact: true })).toBeVisible()
await expect(toggle).not.toBeChecked()
await expect(toggle).toBeEnabled()
requests.length = 0
await panel.locator('[data-slot="switch-control"]').click()
const toast = page
.getByRole("listitem", { includeHidden: true })
.filter({ has: page.getByText("Request failed", { exact: true }) })
await expect(toast.getByText(`figma-desktop: ${error}`, { exact: true })).toBeVisible()
await expect(toggle).not.toBeChecked()
await expect(toggle).toBeEnabled()
expect(requests.filter((request) => request.path.endsWith("/connect"))).toEqual([
{ path: "/api/mcp/figma-desktop/connect", directory: workspace },
])
expect(requests.every((request) => request.directory === workspace)).toBe(true)
await expect(toast).toHaveCSS("opacity", "1")
await testInfo.attach("mcp-connection-error", { body: await page.screenshot(), contentType: "image/png" })
if (surface === "popover") await page.keyboard.press("Escape")
if (surface === "dialog") await panel.getByRole("button", { name: "Close", exact: true }).click()
await expect(panel).toBeHidden()
await toast.getByRole("button", { name: "Dismiss", exact: true }).click()
await expect(toast).toBeHidden()
state.fail = false
if (surface === "popover") await page.getByRole("button", { name: "Status", exact: true }).click()
if (surface === "dialog") await page.keyboard.press("ControlOrMeta+;")
await expect(toggle).toBeEnabled()
await panel.locator('[data-slot="switch-control"]').click()
await expect(toggle).toBeChecked()
await expect(toggle).toBeEnabled()
await expect(toast).toBeHidden()
})
}
@@ -0,0 +1,303 @@
import { expect, test, type Page } from "@playwright/test"
import { base64Encode } from "@opencode-ai/util/encode"
import { currentSession, mockOpenCodeServer } from "../utils/mock-server"
import { expectAppVisible } from "../utils/waits"
const directory = "C:/OpenCode/WorkspacePending"
const workspace = "C:/OpenCode/pending-workspace"
const projectID = "proj_workspace_pending"
const draftID = "draft_workspace_pending"
const otherID = "ses_workspace_pending_other"
const text = "Create the workspace, then explain the pending session."
const server = `http://${process.env.PLAYWRIGHT_SERVER_HOST ?? "127.0.0.1"}:${process.env.PLAYWRIGHT_SERVER_PORT ?? "4096"}`
const sessionPath = `/server/${base64Encode(server)}/session/`
const draftPath = `/new-session?draftId=${draftID}`
const headers = { "access-control-allow-origin": "*" }
test.use({ serviceWorkers: "block", viewport: { width: 1280, height: 900 } })
for (const viewport of [
{ name: "desktop", width: 1280, height: 900 },
{ name: "mobile", width: 390, height: 844 },
]) {
test(`shows a pending workspace session immediately on ${viewport.name}`, async ({ page }, testInfo) => {
await page.setViewportSize(viewport)
const mock = await openDraft(page)
const pending = await submitPending(page, mock)
await expect(pending.message).toBeInViewport()
await expect(pending.shimmer).toBeInViewport()
await testInfo.attach("creating-worktree", {
body: await page.screenshot({ path: testInfo.outputPath(`pending-${viewport.name}.png`) }),
contentType: "image/png",
})
if (viewport.name === "mobile") {
await page.locator("html").evaluate((element) => {
element.dir = "rtl"
})
await expect(page.locator("html")).toHaveAttribute("dir", "rtl")
await expect(pending.message).toBeInViewport()
await expect(pending.shimmer).toBeInViewport()
await expect(page.locator('[data-component="session-preparing"]')).toHaveCSS("direction", "rtl")
expect(
await page
.locator('[data-component="session-preparing"]')
.evaluate((element) => element.scrollWidth <= element.clientWidth),
).toBe(true)
}
if (viewport.name === "desktop") {
await page.locator(`[data-titlebar-tab-link][href="${sessionPath}${otherID}"]`).click()
await expect(page).toHaveURL(`${sessionPath}${otherID}`)
await expect(page.locator('[data-component="composer-editor"]')).toBeEditable()
await expect(pending.shimmer).toBeHidden()
await page.locator(`[data-titlebar-tab-link][href="${sessionPath}${pending.sessionID}"]`).click()
await expect(page).toHaveURL(pending.url)
await expect(pending.message).toHaveAttribute("data-timeline-part-id", `${pending.messageID}:text:0`)
await expect(pending.shimmer).toHaveAttribute("data-active", "true")
expect(mock.calls).toEqual(["worktree"])
await page.locator(`[data-titlebar-tab-link][href="${sessionPath}${otherID}"]`).click()
await expect(page).toHaveURL(`${sessionPath}${otherID}`)
await page.locator('[data-component="composer-editor"]').fill("Keep focus in this other session")
await expect(page.locator('[data-component="composer-editor"]')).toBeFocused()
}
expect(mock.calls).toEqual(["worktree"])
mock.worktree.resolve({ status: 200, json: { directory: workspace } })
await expect
.poll(() => mock.prompts)
.toEqual([{ sessionID: pending.sessionID, body: expect.objectContaining({ id: pending.messageID, text }) }])
expect(mock.creates).toEqual([
expect.objectContaining({ id: pending.sessionID, location: { directory: workspace } }),
])
expect(mock.calls).toEqual(["worktree", "session", "prompt"])
if (viewport.name === "desktop") {
await expect(page.locator(`[data-titlebar-tab-link][href="${sessionPath}${pending.sessionID}"]`)).toContainText(
"Created workspace session",
)
await expect(page).toHaveURL(`${sessionPath}${otherID}`)
await expect(page.locator('[data-component="composer-editor"]')).toHaveText("Keep focus in this other session")
await expect(page.locator('[data-component="composer-editor"]')).toBeFocused()
await page.locator(`[data-titlebar-tab-link][href="${sessionPath}${pending.sessionID}"]`).click()
}
await expect(page).toHaveURL(pending.url)
await expect(pending.shimmer).toHaveCount(0)
await expect(pending.message).toHaveCount(1)
await expect(pending.message.locator('[data-slot="user-message-text"]')).toHaveText(text)
await expect(pending.message).toHaveAttribute("data-timeline-part-id", `${pending.messageID}:text:0`)
})
}
test("restores the original draft when worktree creation fails", async ({ page }) => {
const mock = await openDraft(page)
const pending = await submitPending(page, mock)
mock.worktree.resolve({ status: 500, json: { message: "Worktree creation failed in the fixture" } })
await expect(page).toHaveURL(draftPath)
await expect(page.getByText("Failed to create worktree", { exact: true })).toBeVisible()
await expect(page.locator('[data-component="composer-editor"]')).toHaveText(text)
await expect(page.locator('[data-action="composer-submit"]')).toBeEnabled()
await expect(page.getByRole("button", { name: "New workspace", exact: true })).toBeVisible()
await expect(pending.shimmer).toHaveCount(0)
await expect(pending.message).toHaveCount(0)
await expect(page.locator(`[data-titlebar-tab-link][href="${sessionPath}${pending.sessionID}"]`)).toHaveCount(0)
expect(mock.calls).toEqual(["worktree"])
expect(mock.creates).toEqual([])
expect(mock.prompts).toEqual([])
})
test("retains the draft and reuses the created workspace after session creation fails", async ({ page }) => {
const mock = await openDraft(page, { failSessionCreate: true })
const pending = await submitPending(page, mock)
mock.worktree.resolve({ status: 200, json: { directory: workspace } })
await expect(page).toHaveURL(draftPath)
await expect(page.getByText("Failed to create session", { exact: true })).toBeVisible()
await expect(page.locator('[data-component="composer-editor"]')).toHaveText(text)
await expect(page.locator('[data-action="composer-submit"]')).toBeEnabled()
await expect(page.getByRole("button", { name: "pending-workspace", exact: true })).toBeVisible()
await expect(pending.shimmer).toHaveCount(0)
await expect(pending.message).toHaveCount(0)
expect(mock.creates).toEqual([expect.objectContaining({ id: pending.sessionID, location: { directory: workspace } })])
expect(mock.calls).toEqual(["worktree", "session"])
expect(mock.prompts).toEqual([])
await page.locator('[data-action="composer-submit"]').click()
await expect.poll(() => mock.prompts.length).toBe(1)
expect(mock.creates).toHaveLength(2)
expect(mock.creates[1]).toMatchObject({ location: { directory: workspace } })
expect(mock.prompts[0]).toMatchObject({ sessionID: mock.creates[1].id, body: { text } })
expect(mock.calls).toEqual(["worktree", "session", "session", "prompt"])
await expect(page).toHaveURL(`${sessionPath}${mock.creates[1].id}`)
await expect(page.locator('[data-component="user-message"] [data-slot="user-message-text"]')).toHaveText(text)
})
test("restores the draft after closing and revisiting a pending session that fails", async ({ page }) => {
const mock = await openDraft(page)
const pending = await submitPending(page, mock)
const tab = page.locator(`[data-titlebar-tab-link][href="${sessionPath}${pending.sessionID}"]`)
await page.locator("[data-titlebar-tab-slot]").filter({ has: tab }).locator('[data-slot="tab-close"] button').click()
await expect(page).toHaveURL(`${sessionPath}${otherID}`)
await expect(page.locator('[data-component="composer-editor"]')).toBeEditable()
await expect(tab).toHaveCount(0)
await expect(pending.shimmer).toHaveCount(0)
await page.goBack()
await expect(page).toHaveURL(pending.url)
await expect(tab).toHaveCount(1)
await expect(tab).toBeVisible()
await expect(pending.message).toHaveCount(1)
await expect(pending.message.locator('[data-slot="user-message-text"]')).toHaveText(text)
await expect(pending.message).toHaveAttribute("data-timeline-part-id", `${pending.messageID}:text:0`)
await expect(pending.shimmer).toBeVisible()
await expect(pending.shimmer).toContainText("Creating worktree")
await expect(pending.shimmer).toHaveAttribute("data-active", "true")
expect(mock.calls).toEqual(["worktree"])
mock.worktree.resolve({ status: 500, json: { message: "Worktree creation failed after revisiting the session" } })
await expect(page).toHaveURL(draftPath)
await expect(page.getByText("Failed to create worktree", { exact: true })).toBeVisible()
await expect(page.locator('[data-component="composer-editor"]')).toHaveText(text)
await expect(page.locator('[data-action="composer-submit"]')).toBeEnabled()
await expect(page.getByRole("button", { name: "New workspace", exact: true })).toBeVisible()
await expect(page.locator(`[data-titlebar-tab-link][href="${draftPath}"]`)).toHaveCount(1)
await expect(tab).toHaveCount(0)
await expect(pending.shimmer).toHaveCount(0)
await expect(pending.message).toHaveCount(0)
expect(mock.calls).toEqual(["worktree"])
expect(mock.creates).toEqual([])
expect(mock.prompts).toEqual([])
})
async function openDraft(page: Page, options?: { failSessionCreate?: boolean }) {
const worktree = Promise.withResolvers<{ status: number; json: { directory?: string; message?: string } }>()
const calls: string[] = []
const creates: Record<string, unknown>[] = []
const prompts: { sessionID: string; body: Record<string, unknown> }[] = []
const project = {
id: projectID,
worktree: directory,
vcs: "git",
name: "workspace-pending",
time: { created: 1700000000000, updated: 1700000000000 },
sandboxes: [] as string[],
}
const sessions = [currentSession({ id: otherID, projectID, title: "Other session" }, directory)]
await mockOpenCodeServer(page, {
directory,
project,
provider: {
all: [
{
id: "opencode",
name: "OpenCode",
models: { "pending-model": { id: "pending-model", name: "Pending Model", limit: { context: 200_000 } } },
},
],
connected: ["opencode"],
default: { providerID: "opencode", modelID: "pending-model" },
},
sessions,
pageMessages: () => ({ items: [] }),
onPrompt: (input) => prompts.push(input),
})
page.on("request", (request) => {
if (request.method() !== "POST") return
const path = new URL(request.url()).pathname
if (path === `/api/worktree/${projectID}`) calls.push("worktree")
if (path === "/api/session") calls.push("session")
if (/^\/api\/session\/[^/]+\/prompt$/.test(path)) calls.push("prompt")
})
await page.route(`**/api/worktree/${projectID}`, async (route) => {
if (route.request().method() !== "POST") return route.fallback()
// Keep the real HTTP response pending until the test has checked the preview.
const response = await worktree.promise
if (response.status === 200) project.sandboxes.push(workspace)
await route.fulfill({ ...response, headers })
})
await page.route("**/api/session", async (route) => {
if (route.request().method() !== "POST") return route.fallback()
const body: Record<string, unknown> = route.request().postDataJSON()
creates.push(body)
if (options?.failSessionCreate && creates.length === 1) {
return route.fulfill({ status: 500, json: { message: "Session creation failed in the fixture" }, headers })
}
if (typeof body.id !== "string") throw new Error("Session creation must use the client-reserved ID")
const session = currentSession({ ...body, id: body.id, projectID, title: "Created workspace session" }, workspace)
sessions.push(session)
return route.fulfill({ json: { data: session }, headers })
})
await page.route("**/api/location?**", (route) => {
if (route.request().method() !== "GET") return route.fallback()
return route.fulfill({
json: {
directory: new URL(route.request().url()).searchParams.get("location[directory]") ?? directory,
project: { id: projectID, directory, canonical: directory },
},
headers,
})
})
await page.addInitScript(
({ directory, draftID, otherID, server }) => {
localStorage.setItem(
"opencode.global.dat:server",
JSON.stringify({
projects: { local: [{ worktree: directory, expanded: true }] },
lastProject: { local: directory },
}),
)
localStorage.setItem(
"opencode.window.browser.dat:tabs",
JSON.stringify([
{ type: "draft", draftID, server, directory },
{ type: "session", sessionId: otherID, server },
]),
)
},
{ directory, draftID, otherID, server },
)
await page.goto(draftPath)
await expectAppVisible(page.locator('[data-component="composer-editor"]'))
await page.getByRole("button", { name: "Local", exact: true }).click()
await page.getByRole("menuitem", { name: "New workspace", exact: true }).click()
await expect(page.getByRole("button", { name: "New workspace", exact: true })).toBeVisible()
await expect(page.locator('[data-component="composer-editor"]')).toBeEditable()
return { worktree, calls, creates, prompts }
}
async function submitPending(page: Page, mock: Awaited<ReturnType<typeof openDraft>>) {
await page.locator('[data-component="composer-editor"]').fill(text)
await expect(page.locator('[data-action="composer-submit"]')).toBeEnabled()
await page.locator('[data-action="composer-submit"]').click()
await expect(page).toHaveURL((url) => url.pathname.startsWith(sessionPath) && /\/ses_[^/]+$/.test(url.pathname))
const url = page.url()
const sessionID = new URL(url).pathname.slice(sessionPath.length)
const preparing = page.locator('[data-component="session-preparing"]')
const message = page.locator('[data-component="user-message"]')
const shimmer = preparing.getByRole("status").locator('[data-component="text-shimmer"]')
await expect(preparing).toBeVisible()
await expect(preparing.locator('[data-component="user-message"]')).toHaveCount(1)
await expect(message).toHaveCount(1)
await expect(message.locator('[data-slot="user-message-text"]')).toHaveText(text)
await expect(message).toHaveAttribute("data-timeline-part-id", /^.+:text:0$/)
const messageID = (await message.getAttribute("data-timeline-part-id"))!.replace(/:text:0$/, "")
await expect(shimmer).toBeVisible()
await expect(shimmer).toContainText("Creating worktree")
await expect(shimmer).toHaveAttribute("data-active", "true")
await expect.poll(() => mock.calls).toEqual(["worktree"])
expect(mock.creates).toEqual([])
expect(mock.prompts).toEqual([])
return { url, sessionID, messageID, message, shimmer }
}
@@ -0,0 +1,89 @@
import { expect, test } from "@playwright/test"
import { setupTimeline } from "../performance/timeline-stability/fixture"
for (const width of [1400, 390]) {
for (const profile of [
{ locale: "en", direction: "ltr" },
{ locale: "en", direction: "rtl" },
{ locale: "ar", direction: "rtl" },
]) {
test(`keeps notices on one line: ${profile.locale} ${profile.direction} ${width}`, async ({ page }, info) => {
const command =
"bun run inspect --target src/renderer/session-timeline.ts --output artifacts/inspection-report.json ".repeat(5)
const descriptions = [
`${command}--finished`,
`Instructions changed\n${command}--updated`,
`\u0645\u0631\u0627\u062c\u0639\u0629 ${command}--reviewed`,
]
await setupTimeline(page, {
locale: profile.locale,
viewport: { width, height: 900 },
sessionMessages: [
{
id: "msg_notice_user",
type: "user",
text: "Inspect the project and report completion.",
time: { created: 1 },
},
{
id: "msg_notice_shell",
type: "synthetic",
text: "Complete",
description: descriptions[0],
metadata: { source: "shell", state: "completed" },
time: { created: 2 },
},
{ id: "msg_notice_system", type: "system", text: descriptions[1], time: { created: 3 } },
{
id: "msg_notice_agent",
type: "synthetic",
text: "Complete",
description: descriptions[2],
metadata: { source: "subagent", state: "completed", agent: "general" },
time: { created: 4 },
},
],
})
await page
.locator("html")
.evaluate((element, direction) => element.setAttribute("dir", direction), profile.direction)
const notices = page.locator('[data-slot="session-timeline-notice"]')
await expect(notices).toHaveCount(3)
await expect(notices).toContainText(descriptions)
await page.locator("[data-timeline-virtual-content]").screenshot({ path: info.outputPath("notices.png") })
await expect
.poll(() =>
notices.evaluateAll((nodes) =>
nodes.map((node) => {
const style = getComputedStyle(node)
const element = node as HTMLElement
return {
direction: style.direction,
whiteSpace: style.whiteSpace,
textOverflow: style.textOverflow,
overflow: style.overflowX,
singleLine:
Math.abs(
element.clientHeight -
parseFloat(style.paddingTop) -
parseFloat(style.paddingBottom) -
parseFloat(style.lineHeight),
) <= 1,
clipped: element.scrollWidth > element.clientWidth,
}
}),
),
)
.toEqual(
Array.from({ length: 3 }, () => ({
direction: profile.direction,
whiteSpace: "nowrap",
textOverflow: "ellipsis",
overflow: "hidden",
singleLine: true,
clipped: true,
})),
)
})
}
}
@@ -261,7 +261,7 @@ for (const delivery of ["steer", "queue"] as const) {
const transcript = page.locator("[data-timeline-virtual-content]")
const thinking = transcript.locator('[data-timeline-row="Thinking"]')
await expect(transcript.getByText("A1: I will inspect the current implementation.", { exact: true })).toBeVisible()
await expect(thinking).toBeVisible()
await expect(thinking).toHaveCount(0)
await expect(view.input).toBeEditable()
await view.input.fill(followUp)
await view.input.press("Enter")
@@ -274,12 +274,14 @@ for (const delivery of ["steer", "queue"] as const) {
const queued = view.rows.filter({ hasText: followUp })
await expect(queued).toBeVisible()
await expect(pending).toHaveCount(0)
await expect(thinking).toHaveCount(0)
await queued.hover()
await queued.getByRole("button", { name: "Steer", exact: true }).click()
await expect.poll(() => mock.changes).toEqual([{ inboxID, action: "steer" }])
}
await expect(view.rows).toHaveCount(0)
await expect(pending).toContainText(followUp)
await expect(thinking).toHaveCount(0)
// The next assistant step still belongs to U1: U2 has been admitted, not delivered.
mock.emit("session.step.started", { sessionID, assistantMessageID: assistantID, agent: "build", model })
@@ -308,7 +310,7 @@ for (const delivery of ["steer", "queue"] as const) {
await expect(tools).toBeVisible()
await expect(tools).toContainText(/Used\s*Read, Grep/)
await expect(tools.locator('[data-component="tag"]')).toHaveText("2")
await expect(thinking).toBeVisible()
await expect(thinking).toHaveCount(0)
await expect(pending).toBeVisible()
expect(mock.rows.map((row) => ({ id: row.id, delivery: row.delivery }))).toEqual([
{ id: inboxID, delivery: "steer" },
@@ -316,27 +318,21 @@ for (const delivery of ["steer", "queue"] as const) {
await transcript.screenshot({ path: testInfo.outputPath("pending-steer.png") })
// Soft assertions let delivery run too, even when the pending ordering regresses.
await expect
.soft(tools.or(thinking).or(pending))
.toHaveText([/Used\s*Read, Grep/, /Thinking/, /U2: Also check the retry path\./])
await expect.soft(tools.or(pending)).toHaveText([/Used\s*Read, Grep/, /U2: Also check the retry path\./])
await expect
.soft(transcript.locator('[data-timeline-row="AssistantPart"]').filter({ has: tools }))
.toHaveAttribute("data-message-id", userID)
await expect
.configure({ soft: true })
.poll(async () => {
const boxes = await Promise.all([tools.boundingBox(), thinking.boundingBox(), pending.boundingBox()])
return (
boxes.every((box) => box !== null) &&
boxes[0]!.y + boxes[0]!.height <= boxes[1]!.y &&
boxes[1]!.y + boxes[1]!.height <= boxes[2]!.y
)
const boxes = await Promise.all([tools.boundingBox(), pending.boundingBox()])
return boxes.every((box) => box !== null) && boxes[0]!.y + boxes[0]!.height <= boxes[1]!.y
})
.toBe(true)
mock.rows.splice(0, 1)
mock.emit("session.inbox.delivered", { sessionID, inboxID })
await expect(thinking).toHaveAttribute("data-message-id", inboxID)
await expect(thinking).toHaveCount(0)
await expect(pending).toHaveCount(1)
await expect(transcript.locator('[data-timeline-row="UserMessage"]')).toHaveCount(2)
await expect(transcript.locator('[data-timeline-row="AssistantPart"]').filter({ has: tools })).toHaveAttribute(
@@ -352,11 +348,11 @@ for (const delivery of ["steer", "queue"] as const) {
.locator('[data-timeline-row="AssistantPart"]')
.filter({ hasText: "A3: Now checking the retry path for U2." })
await expect(response).toHaveAttribute("data-message-id", inboxID)
await expect(tools.or(pending).or(response).or(thinking)).toHaveText([
await expect(thinking).toHaveCount(0)
await expect(tools.or(pending).or(response)).toHaveText([
/Used\s*Read, Grep/,
/U2: Also check the retry path\./,
/A3: Now checking the retry path for U2\./,
/Thinking/,
])
})
}
@@ -0,0 +1,191 @@
import { expect, test } from "@playwright/test"
import type { SessionMessageAssistant, ShellInfo } from "@opencode-ai/client/promise"
import { directory, sessionID, setupTimeline } from "../performance/timeline-stability/fixture"
const shell = {
id: "sh_background",
status: "running",
command: "bun run check",
cwd: directory,
shell: "bash",
file: "/tmp/check.out",
metadata: { sessionID },
time: { started: 2 },
} satisfies ShellInfo
for (const grouped of [false, true]) {
for (const status of ["exited", "killed", "timeout"] as const) {
test(`stops ${grouped ? "grouped" : "standalone"} background shell shimmer when ${status}`, async ({
page,
}, info) => {
const message: SessionMessageAssistant = {
id: "msg_background",
type: "assistant",
agent: "build",
model: { id: "model", providerID: "provider" },
content: [shell.id, "sh_other"].map((id) => ({
type: "tool",
id: `call_${id}`,
name: "shell",
state: {
status: "completed",
input: { command: shell.command },
content: [{ type: "text", text: "Command moved to the background." }],
metadata: { shellID: id, status: "running" },
},
time: { created: 2, completed: 3 },
})),
time: { created: 2, completed: 3 },
}
if (grouped)
message.content.unshift({
type: "tool",
id: "call_read",
name: "read",
state: {
status: "completed",
input: { path: "package.json" },
content: [{ type: "text", text: "{}" }],
metadata: {},
},
time: { created: 1, completed: 2 },
})
const timeline = await setupTimeline(page, {
viewport: { width: grouped ? 390 : 1400, height: 900 },
settings: { shellToolPartsExpanded: !grouped },
sessionStatus: { [sessionID]: { type: "busy" } },
sessionMessages: [
{ id: "msg_user", type: "user", text: "Run two independent checks.", time: { created: 1 } },
message,
],
})
const state = { finished: false, requests: 0 }
await page.route("**/api/shell?*", (route) =>
route.fulfill({
json: { location: { directory }, data: [...(state.finished ? [] : [shell]), { ...shell, id: "sh_other" }] },
}),
)
await page.route("**/api/shell/*/output?*", (route) => {
const url = new URL(route.request().url())
const target = url.pathname.includes(`/${shell.id}/`)
if (target) state.requests++
const output = target && state.finished ? "Checking project\nCheck finished\n" : "Checking project\n"
const cursor = Number(url.searchParams.get("cursor") ?? 0)
const end = Math.min(output.length, cursor + 17)
return route.fulfill({
json: {
location: { directory },
data: {
output: output.slice(cursor, end),
cursor: end,
size: output.length,
truncated: false,
},
},
})
})
await page.clock.install()
await page.reload()
await timeline.transport.waitForConnection()
const group = page.locator('[data-component="collapsed-tool-group"]')
const groupTrigger = group.locator(':scope > [data-component="collapsible"] > [data-slot="collapsible-trigger"]')
if (grouped) {
await expect(group).toHaveAttribute("data-timeline-part-ids", "call_read,call_sh_background,call_sh_other")
await expect(groupTrigger).toHaveAttribute("aria-expanded", "false")
await groupTrigger.click()
}
const card = page.locator(`[data-timeline-part-id="call_${shell.id}"]`)
const shimmer = card.locator('[data-component="text-shimmer"]')
const other = page.locator('[data-timeline-part-id="call_sh_other"] [data-component="text-shimmer"]')
await expect(shimmer).toHaveAttribute("data-active", "true")
await expect(other).toHaveAttribute("data-active", "true")
if (grouped) await card.locator('[data-slot="collapsible-trigger"]').click()
await expect(card.locator('[data-slot="bash-result"]')).toHaveText("Checking project")
state.finished = true
await timeline.transport.send({
id: "evt_shell_exited",
created: 4,
type: "shell.exited",
location: { directory },
data: { id: shell.id, status, exit: status === "exited" ? 0 : 1 },
})
await expect(shimmer).toHaveAttribute("data-active", "false")
await expect(other).toHaveAttribute("data-active", "true")
await expect(card.locator('[data-slot="bash-result"]')).toHaveText("Checking project\nCheck finished")
await expect(card.locator('[data-slot="collapsible-trigger"]')).toHaveAttribute("aria-expanded", "true")
await page.locator("[data-timeline-virtual-content]").screenshot({ path: info.outputPath("shell-finished.png") })
const requests = state.requests
await page.clock.fastForward(5_000)
expect(state.requests).toBe(requests)
await page.reload()
if (grouped) await groupTrigger.click()
await expect(shimmer).toHaveAttribute("data-active", "false")
await expect(other).toHaveAttribute("data-active", "true")
})
}
}
test("shows the authoritative foreground result after streaming shell output", async ({ page }) => {
const timeline = await setupTimeline(page, {
settings: { shellToolPartsExpanded: true },
sessionMessages: [
{ id: "msg_user", type: "user", text: "Run the check.", time: { created: 1 } },
{
id: "msg_foreground",
type: "assistant",
agent: "build",
model: { id: "model", providerID: "provider" },
content: [
{
type: "tool",
id: "call_foreground",
name: "shell",
state: { status: "running", input: { command: shell.command }, metadata: { shellID: shell.id } },
time: { created: 2 },
},
],
time: { created: 2 },
},
],
})
await page.route("**/api/shell/*/output?*", (route) =>
route.fulfill({
json: {
location: { directory },
data: {
output: Number(new URL(route.request().url()).searchParams.get("cursor")) === 0 ? "Checking project\n" : "",
cursor: 17,
size: 17,
truncated: false,
},
},
}),
)
await page.reload()
await timeline.transport.waitForConnection()
const card = page.locator('[data-timeline-part-id="call_foreground"]')
const shimmer = card.locator('[data-component="text-shimmer"]')
await expect(shimmer).toHaveAttribute("data-active", "true")
await expect(card.locator('[data-slot="bash-result"]')).toHaveText("Checking project")
await timeline.transport.send({
id: "evt_foreground_complete",
created: 3,
type: "session.tool.success",
durable: { aggregateID: sessionID, seq: 0, version: 2 },
data: {
sessionID,
assistantMessageID: "msg_foreground",
id: "call_foreground",
executed: true,
content: [{ type: "text", text: "Checking project\nCheck finished\nCommand exited with code 0." }],
metadata: { status: "completed", exit: 0 },
},
})
await expect(shimmer).toHaveAttribute("data-active", "false")
await expect(card.locator('[data-slot="bash-result"]')).toHaveText(
"Checking project\nCheck finished\nCommand exited with code 0.",
)
})
@@ -84,6 +84,39 @@ const assistantMessage = {
} satisfies SessionMessageInfo
test.describe("regression: session timeline local row state", () => {
test("preserves a patch file choice as new calls join its Used group", async ({ page }) => {
const events: EventPayload[] = []
const part = { ...editPart, tool: "patch" }
await mockServer(page, events, [userMessage, { ...assistantMessage, content: [toolContent(part)] }])
await configurePage(page, false)
await page.goto(sessionHref())
await expectSessionTitle(page, title)
const group = page.locator('[data-component="collapsed-tool-group"]')
const summary = group.getByRole("button", { name: "Used Patch", exact: true })
await summary.click()
await group.locator(`[data-timeline-part-id="${editPartID}"]`).evaluate((element) => {
element.setAttribute("data-disclosure-probe", "existing")
})
const wrapper = group.locator('[data-disclosure-probe="existing"]')
const trigger = wrapper.locator('[data-scope="apply-patch"] button')
await expect(trigger).toHaveAttribute("aria-expanded", "false")
await trigger.click()
await expect(trigger).toHaveAttribute("aria-expanded", "true")
const original = await wrapper.elementHandle()
for (const count of [2, 3]) {
if (count === 3) await trigger.click()
const id = `prt_patch_${count}`
events.push(...toolEvents({ ...part, id, callID: id }))
await expect(group.locator('[data-component="tag"]')).toHaveText(String(count))
await expect(group).toHaveAttribute("data-timeline-part-ids", new RegExp(`${id}$`))
await expect(trigger).toHaveAttribute("aria-expanded", String(count === 2))
await expect(summary).toHaveAttribute("aria-expanded", "true")
expect(await original!.evaluate((node) => node.isConnected)).toBe(true)
}
})
test("keeps a manually collapsed tool collapsed when later assistant content streams", async ({ page }) => {
const events: EventPayload[] = []
await mockServer(page, events)
@@ -208,19 +241,19 @@ test.describe("regression: session timeline local row state", () => {
})
})
async function configurePage(page: Page) {
await page.addInitScript(() => {
async function configurePage(page: Page, expanded = true) {
await page.addInitScript((expanded) => {
localStorage.setItem(
"settings.v3",
JSON.stringify({
general: {
editToolPartsExpanded: true,
shellToolPartsExpanded: true,
editToolPartsExpanded: expanded,
shellToolPartsExpanded: expanded,
showReasoningSummaries: true,
},
}),
)
})
}, expanded)
}
async function expectExpanded(locator: Locator, expected: boolean) {
@@ -109,31 +109,85 @@ test("shimmers and expands a running shell command", async ({ page }) => {
await expect(tool.locator('[data-slot="bash-pre"]')).toContainText("still running")
})
test("transitions thinking and hidden reasoning through busy to idle", async ({ page }) => {
const reasoningID = "prt_reasoning_hidden"
const assistant = assistantMessage([reasoningPart(reasoningID, "## Inspecting stability")], { completed: false })
const timeline = await setupTimeline(page, {
messages: [userMessage(), assistant],
settings: { showReasoningSummaries: false },
cpuRate: 4,
for (const open of [false, true]) {
test(`keeps ${open ? "expanded" : "collapsed"} reasoning intent from Thinking through standalone shell into Used`, async ({
page,
}) => {
const reasoningID = `prt_reasoning_hidden_${open}`
const shellID = `prt_reasoning_shell_${open}`
const assistant = assistantMessage([reasoningPart(reasoningID, "## Inspecting stability")], { completed: false })
const timeline = await setupTimeline(page, {
messages: [userMessage(), assistant],
settings: { showReasoningSummaries: false },
cpuRate: 4,
})
const reasoning = page.locator(`[data-timeline-part-id="${renderedPartID(reasoningID)}"]`)
await expect(page.locator('[data-timeline-row="Thinking"]')).toBeVisible()
await expect(page.getByText("Inspecting stability", { exact: true })).toBeVisible()
const thought = reasoning.locator('[data-slot="collapsible-trigger"]')
await expect(thought).toHaveAttribute("aria-expanded", "false")
await thought.click()
await expect(thought).toHaveAttribute("aria-expanded", "true")
if (!open) await thought.click()
await expect(thought).toHaveAttribute("aria-expanded", String(open))
await timeline.send(partUpdated(shell(shellID, "running")))
const group = page.locator('[data-component="collapsed-tool-group"]')
await expect(page.locator(`[data-timeline-part-id="${shellID}"]`)).toBeVisible()
await expect(group).toHaveCount(0)
await expect(page.locator('[data-timeline-row="Thinking"]')).toHaveCount(0)
await expect(thought).toContainText("Thought")
await expect(thought).not.toContainText("Inspecting stability")
await expect(thought).toHaveAttribute("aria-expanded", String(open))
await timeline.send(partUpdated(shell(shellID, "completed", "done")))
await timeline.send(messageUpdated(completedAssistantInfo(assistant)))
await timeline.send(status("idle"))
const used = group.getByRole("button", { name: "Used Shell", exact: true })
await expect(used).toHaveAttribute("aria-expanded", "false")
await used.click()
await expect(used).toHaveAttribute("aria-expanded", "true")
await expect(group.locator(`[data-timeline-part-id="${shellID}"]`)).toBeVisible()
await expect(group.getByRole("button", { name: "Thought", exact: true })).toHaveAttribute(
"aria-expanded",
String(open),
)
await expect(group.locator('[data-component="tag"]')).toHaveText("1")
await expect(page.locator('[data-timeline-row="Thinking"]')).toHaveCount(0)
await expect(used).toHaveAttribute("aria-expanded", "true")
if (!open) await thought.click()
await expect(reasoning.getByRole("heading", { name: "Inspecting stability", exact: true })).toBeVisible()
await used.click()
await expect(used).toHaveAttribute("aria-expanded", "false")
await used.click()
await expect(reasoning.getByRole("button", { name: "Thought", exact: true })).toHaveAttribute(
"aria-expanded",
"true",
)
await expect(reasoning.getByRole("heading", { name: "Inspecting stability", exact: true })).toBeVisible()
})
await timeline.send(status("busy"), 150)
}
await expect(page.locator('[data-timeline-row="Thinking"]')).toBeVisible()
await expect(page.getByText("Inspecting stability", { exact: true })).toBeVisible()
await expect(page.locator(`[data-timeline-part-id="${reasoningID}"]`)).toHaveCount(0)
await expect(page.locator(`[data-timeline-part-id="${renderedPartID(reasoningID)}"]`)).toHaveCount(0)
await timeline.send(partUpdated(shell("prt_reasoning_shell", "running")), 160)
await expect(page.locator('[data-timeline-row="Thinking"]')).toBeVisible()
await timeline.send(partUpdated(shell("prt_reasoning_shell", "completed", "done")), 180)
await timeline.send(messageUpdated(completedAssistantInfo(assistant)), 100)
await timeline.send(status("idle"), 300)
await expect(page.locator('[data-timeline-row="Thinking"]')).toHaveCount(0)
await expect(page.locator(`[data-timeline-part-id="${reasoningID}"]`)).toHaveCount(0)
await expect(page.locator(`[data-timeline-part-id="${renderedPartID(reasoningID)}"]`)).toHaveCount(0)
})
for (const transition of ["reasoning-end", "idle", "retry"] as const) {
test(`stops active Thinking on ${transition} without a following tool`, async ({ page }) => {
const id = `prt_reasoning_stop_${transition}`
const text = "## Inspecting stability\n\nThe timeline is ready for the next step."
const timeline = await setupTimeline(page, {
messages: [userMessage(), assistantMessage([reasoningPart(id, text)], { completed: false })],
})
const part = page.locator(`[data-timeline-part-id="${renderedPartID(id)}"]`)
const trigger = part.locator('[data-slot="collapsible-trigger"]')
await expect(page.locator('[data-timeline-row="Thinking"]')).toBeVisible()
await expect(trigger).toHaveAttribute("aria-expanded", "false")
await timeline.send(transition === "reasoning-end" ? partUpdated(reasoningPart(id, text)) : status(transition))
await expect(trigger).toContainText("Thought")
await expect(page.locator('[data-timeline-row="Thinking"]')).toHaveCount(0)
await expect(page.locator('[data-timeline-row="Retry"]')).toHaveCount(transition === "retry" ? 1 : 0)
await trigger.click()
await expect(trigger).toHaveAttribute("aria-expanded", "true")
await expect(part.getByText("The timeline is ready for the next step.", { exact: true })).toBeVisible()
})
}
test("moves busy through retry and recovery to final idle content", async ({ page }) => {
test("does not infer Thinking from busy, retry, or recovery without reasoning", async ({ page }) => {
const assistant = assistantMessage([], { completed: false })
const timeline = await setupTimeline(page, {
messages: [
@@ -153,18 +207,17 @@ test("moves busy through retry and recovery to final idle content", async ({ pag
assistant,
],
})
await timeline.send(status("busy"), 140)
await expect(page.locator('[data-timeline-row="Thinking"]')).toBeVisible()
await expect(page.locator('[data-timeline-row="Thinking"]')).toHaveCount(0)
await expect(page.locator('[data-timeline-row="DiffSummary"]')).toHaveCount(0)
await timeline.send(status("retry"), 180)
await timeline.send(status("retry"))
await expect(page.locator('[data-timeline-row="Retry"]')).toBeVisible()
await expect(page.locator('[data-timeline-row="Thinking"]')).toHaveCount(0)
await timeline.send(stepStarted(assistant), 180)
await timeline.send(stepStarted(assistant))
await expect(page.locator('[data-timeline-row="Retry"]')).toHaveCount(0)
await expect(page.locator('[data-timeline-row="Thinking"]')).toBeVisible()
await timeline.send(partUpdated(textPart("prt_recovered", "Recovered response")), 140)
await timeline.send(messageUpdated(completedAssistantInfo(assistant)), 100)
await timeline.send(status("idle"), 350)
await expect(page.locator('[data-timeline-row="Thinking"]')).toHaveCount(0)
await timeline.send(partUpdated(textPart("prt_recovered", "Recovered response")))
await timeline.send(messageUpdated(completedAssistantInfo(assistant)))
await timeline.send(status("idle"))
await expect(page.locator('[data-timeline-row="Thinking"]')).toHaveCount(0)
await expect(page.locator(`[data-timeline-part-id="${renderedPartID("prt_recovered")}"]`)).toContainText(
"Recovered response",
@@ -5,6 +5,7 @@ import {
compactionEnded,
compactionFailed,
compactionStarted,
directory,
event,
session,
sessionID,
@@ -208,6 +209,56 @@ test("navigates from a running subagent card and hides background controls in th
await expect(page.getByText(/move running work to the background/i)).toHaveCount(0)
})
for (const name of ["shell", "subagent"] as const) {
test(`keeps the background shortcut available for a grouped running ${name}`, async ({ page }) => {
const message = assistant(false, true)
await setupTimeline(page, {
sessionMessages: [
user,
{
...message,
content: [
{
type: "tool",
id: "call_read",
name: "read",
state: {
status: "completed",
input: { path: "src/example.ts" },
content: [{ type: "text", text: "export const example = true" }],
metadata: {},
},
time: { created: 1, completed: 2 },
},
{
type: "tool",
id: "call_running",
name,
state: {
status: "running",
input:
name === "shell" ? { command: "echo checking" } : { agent: "general", description: "Inspect code" },
metadata: {},
},
time: { created: 3 },
},
],
},
],
})
const group = page.locator('[data-timeline-part-ids="call_read,call_running"]')
await expect(group).toBeVisible()
await expect(group.locator('[data-slot="collapsible-trigger"]')).toHaveAttribute("aria-expanded", "false")
await expect(page.locator('[data-component="session-background-hint"]')).toBeVisible()
const request = page.waitForRequest(
(request) =>
request.method() === "POST" && new URL(request.url()).pathname === `/api/session/${sessionID}/background`,
)
await page.keyboard.press("Control+b")
await request
})
}
test("shows a badge for active background work", async ({ page }) => {
const childID = "ses_background_child"
await setupTimeline(page, {
@@ -298,6 +349,24 @@ test("separates blocking and already-backgrounded work into two rows", async ({
},
})
await timeline.transport.send({
id: "evt_background_shell_created",
created: 3,
type: "shell.created",
location: { directory },
data: {
info: {
id: "shell_backgrounded",
status: "running",
command: "sleep 120",
cwd: directory,
shell: "bash",
file: "/tmp/background.out",
metadata: { sessionID },
time: { started: 2 },
},
},
})
const backgroundCard = page.locator('[data-timeline-part-id="call_backgrounded"]')
await expect(page.getByText(/move running work to the background/i)).toBeVisible()
await page.getByRole("button", { name: "Session details" }).click()
@@ -4,89 +4,144 @@ import {
assistantMessage,
reasoningPart,
setupTimeline,
status,
textPart,
toolPart,
userMessage,
} from "../performance/timeline-stability/fixture"
const profiles = [
{ name: "summaries off no reasoning", summaries: false, reasoning: "", other: false, thinking: true, body: false },
{
name: "summaries off reasoning heading",
summaries: false,
reasoning: "## Inspecting stability",
other: false,
thinking: true,
body: false,
},
{
name: "summaries off with visible tool",
summaries: false,
reasoning: "## Inspecting stability",
other: true,
thinking: true,
body: false,
},
{ name: "summaries on no content", summaries: true, reasoning: "", other: false, thinking: true, body: false },
{
name: "summaries on blank reasoning",
summaries: true,
reasoning: " ",
other: false,
thinking: true,
body: false,
},
{
name: "summaries on visible reasoning",
summaries: true,
reasoning: "## Inspecting stability",
other: false,
thinking: false,
body: true,
},
{
name: "summaries on visible tool no reasoning",
summaries: true,
reasoning: "",
other: true,
thinking: false,
body: false,
},
] as const
for (const profile of profiles) {
test(`projects busy reasoning profile ${profile.name}`, async ({ page }) => {
const reasoningID = `prt_reasoning_matrix_${profiles.indexOf(profile)}`
const parts = [
...(profile.reasoning ? [reasoningPart(reasoningID, profile.reasoning)] : []),
...(profile.other
? [toolPart(`prt_reasoning_tool_${profiles.indexOf(profile)}`, "skill", "running", { name: "inspect" })]
: []),
]
const timeline = await setupTimeline(page, {
messages: [userMessage(), assistantMessage(parts, { completed: false })],
settings: { showReasoningSummaries: profile.summaries },
})
await timeline.send(status("busy"), 150)
await expect(page.locator('[data-timeline-row="Thinking"]')).toHaveCount(profile.thinking ? 1 : 0)
await expect(page.locator(`[data-timeline-part-id="${assistantID}:reasoning:0"]`)).toHaveCount(profile.body ? 1 : 0)
if (!profile.summaries && profile.reasoning.trim()) {
await expect(page.getByText("Inspecting stability", { exact: true })).toBeVisible()
}
test("changes live reasoning through Settings and persists Hidden, Compact, and Full", async ({ page }) => {
await setupTimeline(page, {
messages: [
userMessage(),
assistantMessage(
[
reasoningPart(
"prt_reasoning_settings",
"## Inspecting stability\n\nThe selected mode controls these details.",
),
],
{ completed: false },
),
],
})
const part = page.locator(`[data-timeline-part-id="${assistantID}:reasoning:0"]`)
await expect(part.getByRole("button")).toHaveAttribute("aria-expanded", "false")
const settings = page.getByTestId("settings-screen")
const select = settings.locator('[data-action="settings-reasoning-mode"] [data-component="select-v2"]')
for (const label of ["Full", "Hidden", "Compact"] as const) {
await page.keyboard.press("Control+,")
await expect(settings.getByText("Model reasoning", { exact: true })).toBeVisible()
await expect(select).toHaveAttribute("aria-expanded", "false")
await select.click()
await expect(page.getByRole("listbox").getByRole("option")).toHaveText(["Hidden", "Compact", "Full"])
await page.getByRole("option", { name: label, exact: true }).click()
await expect(select).toHaveText(label)
await expect(select).toHaveAttribute("aria-expanded", "false")
await expect
.poll(() => page.evaluate(() => JSON.parse(localStorage.getItem("settings.v3") ?? "{}").general?.reasoningMode))
.toBe(label.toLowerCase())
await settings.getByRole("button", { name: "Back to app", exact: true }).click()
await expect(settings).toBeHidden()
await expect(page.locator('[data-timeline-row="Thinking"]')).toHaveCount(label === "Hidden" ? 0 : 1)
await expect(part).toHaveCount(label === "Hidden" ? 0 : 1)
if (label === "Hidden") {
await expect(page.getByText("The selected mode controls these details.", { exact: true })).toBeHidden()
continue
}
await expect(part.getByRole("button")).toHaveAttribute("aria-expanded", String(label === "Full"))
if (label === "Full")
await expect(part.getByText("The selected mode controls these details.", { exact: true })).toBeVisible()
if (label === "Compact") {
await expect(part.getByRole("button")).toContainText("Inspecting stability")
await expect(part.getByText("The selected mode controls these details.", { exact: true })).toBeHidden()
}
}
await page.keyboard.press("Control+,")
await expect(select).toHaveText("Compact")
})
// The persisted boolean migrates to compact (false) or full (true).
for (const summaries of [false, true]) {
for (const profile of ["none", "blank", "heading", "tool", "text"] as const) {
test(`projects legacy ${summaries ? "full" : "compact"} reasoning with ${profile}`, async ({ page }) => {
await setupTimeline(page, {
messages: [
userMessage(),
assistantMessage(
[
...(profile === "none"
? []
: [
reasoningPart(
`prt_reasoning_${summaries}_${profile}`,
profile === "blank"
? " "
: "## Inspecting stability\n\nI will inspect the timeline before changing its state.",
),
]),
...(profile === "tool"
? [toolPart(`prt_reasoning_tool_${summaries}`, "skill", "running", { name: "inspect" })]
: []),
...(profile === "text" ? [textPart(`prt_reasoning_text_${summaries}`, "The timeline is stable.")] : []),
],
{ completed: false },
),
],
settings: { showReasoningSummaries: summaries },
})
const part = page.locator(`[data-timeline-part-id="${assistantID}:reasoning:0"]`)
await expect(page.locator('[data-timeline-row="Thinking"]')).toHaveCount(
profile === "blank" || profile === "heading" ? 1 : 0,
)
if (profile === "none") {
await expect(part).toHaveCount(0)
return
}
if (profile === "blank") {
await expect(part).toContainText("Thinking")
await expect(part.getByRole("heading")).toHaveCount(0)
return
}
if (profile === "tool") {
const group = page.locator('[data-component="collapsed-tool-group"]')
const used = group.locator(':scope > [data-component="collapsible"] > [data-slot="collapsible-trigger"]')
await expect(used).toContainText("UsedSkill")
await expect(used).toHaveAttribute("aria-expanded", "false")
await expect(page.getByText("Inspecting stability", { exact: true })).toBeHidden()
await expect(group.locator('[data-component="tag"]')).toHaveText("1")
await used.click()
await expect(used).toHaveAttribute("aria-expanded", "true")
await expect(group.locator(`[data-timeline-part-id="prt_reasoning_tool_${summaries}"]`)).toBeVisible()
await expect(group.locator('[data-component="reasoning-part"]')).toHaveCount(1)
}
if (profile === "text") await expect(page.getByText("The timeline is stable.", { exact: true })).toBeVisible()
const trigger = part.locator('[data-slot="collapsible-trigger"]')
const body = part.getByText("I will inspect the timeline before changing its state.", { exact: true })
await expect(trigger).toContainText(profile === "heading" ? "Thinking" : "Thought")
await expect(trigger).toHaveAttribute("aria-expanded", String(summaries))
if (!summaries) {
await expect(body).toBeHidden()
if (profile === "heading") await expect(trigger).toContainText("Inspecting stability")
await trigger.click()
await expect(trigger).toHaveAttribute("aria-expanded", "true")
}
await expect(body).toBeVisible()
await trigger.click()
await expect(trigger).toHaveAttribute("aria-expanded", "false")
await expect(body).toBeHidden()
if (profile !== "heading") await expect(trigger).not.toContainText("Inspecting stability")
})
}
}
test("does not infer reasoning visibility from provider identity", async ({ page }) => {
const timeline = await setupTimeline(page, {
await setupTimeline(page, {
messages: [
userMessage(),
assistantMessage([textPart("prt_provider_text", "No reasoning payload")], { completed: false }),
],
settings: { showReasoningSummaries: true },
})
await timeline.send(status("busy"), 150)
await expect(page.locator('[data-timeline-row="Thinking"]')).toHaveCount(0)
await expect(page.locator('[data-timeline-part-id*="reasoning"]')).toHaveCount(0)
@@ -1,4 +1,5 @@
import { expect, test } from "@playwright/test"
import { createTwoFilesPatch } from "diff"
import {
assistantMessage,
completedAssistantInfo,
@@ -44,7 +45,7 @@ test("expands a mixed collapsed tool stack without expanding its individual call
const group = page.locator(
'[data-timeline-part-ids="prt_stack_shell_1,prt_stack_explore,prt_stack_patch,prt_stack_shell_2"]',
)
const summary = group.getByRole("button", { name: "Used Shell, Explore, Patch" })
const summary = group.getByRole("button", { name: "Used Shell, Agent, Patch" })
await expect(summary).toHaveAttribute("aria-expanded", "false")
await expect(summary).toHaveCSS("height", "28px")
await expect(group.locator('[data-component="tag"]')).toHaveText("4")
@@ -78,6 +79,61 @@ test("leaves tools expanded by settings outside the collapsed stack", async ({ p
await expect(page.locator('[data-timeline-spacing="tool"]')).toHaveCSS("padding-top", "8px")
})
test("combines follow-up patches into one three-file stack inside Used", async ({ page }) => {
const file = (path: string, before: number, after: number) => ({
file: path,
status: "modified",
additions: 1,
deletions: 1,
patch: createTwoFilesPatch(
path,
path,
`export const value = ${before}\n`,
`export const value = ${after}\n`,
"",
"",
{ context: Infinity },
),
})
const timeline = await setupTimeline(page, {
messages: [
userMessage(),
assistantMessage([
shell("patch_shell", "completed"),
toolPart(
"patch_first",
"patch",
"completed",
{},
{
metadata: { files: [file("src/a.ts", 0, 1), file("src/b.ts", 0, 1)] },
},
),
]),
],
})
const group = page.locator('[data-component="collapsed-tool-group"]')
await group.getByRole("button", { name: "Used Shell, Patch", exact: true }).click()
await expect(group.getByText("2 files", { exact: true })).toBeVisible()
await timeline.send(
partUpdated(
toolPart(
"patch_next",
"patch",
"completed",
{},
{
metadata: { files: [file("src/a.ts", 1, 2), file("src/c.ts", 0, 1)] },
},
),
),
)
await expect(group.locator('[data-component="tag"]')).toHaveText("3")
await expect(group.locator('[data-component="apply-patch-tool"]')).toHaveCount(1)
await expect(group.getByText("3 files", { exact: true })).toBeVisible()
await expect(group.locator('[data-slot="apply-patch-filename"]')).toHaveText(["a.ts", "b.ts", "c.ts"])
})
test("keeps failed search calls and their error cards inside the collapsed stack", async ({ page }) => {
const parts = [
toolPart(
@@ -52,7 +52,7 @@ test("shows parent lineage while the child timeline loads", async ({ page }) =>
await page.goto(sessionHref(parentID))
await expectSessionTitle(page, parentTitle)
await page.getByRole("button", { name: "Used Explore" }).click()
await page.getByRole("button", { name: "Used Agent" }).click()
await page.locator(`a[href="${sessionHref(childID)}"]`).click()
await Promise.all([requested.promise, expect(page).toHaveURL(sessionHref(childID))])
await Promise.all([
@@ -77,7 +77,7 @@ test("keeps the parent visible while the child session resolves", async ({ page
await page.goto(sessionHref(parentID))
await expectSessionTitle(page, parentTitle)
await page.getByRole("button", { name: "Used Explore" }).click()
await page.getByRole("button", { name: "Used Agent" }).click()
await page.locator(`a[href="${sessionHref(childID)}"]`).click()
await requested.promise
await Promise.all([expect(page).toHaveURL(sessionHref(parentID)), expectSessionTitle(page, parentTitle)]).finally(
@@ -195,7 +195,7 @@ async function setup(page: Page, events?: () => OpenCodeEvent[]) {
async function openChildFromParent(page: Page) {
await page.goto(sessionHref(parentID))
await expectSessionTitle(page, parentTitle)
await page.getByRole("button", { name: "Used Explore" }).click()
await page.getByRole("button", { name: "Used Agent" }).click()
const card = page.locator(`a[href="${sessionHref(childID)}"]`)
await expect(card).toBeVisible()
@@ -1,6 +1,7 @@
import { expect, test, type Page, type Route } from "@playwright/test"
import { base64Encode } from "@opencode-ai/util/encode"
import { currentSession } from "../utils/mock-server"
import pkg from "../../package.json" with { type: "json" }
const server = `http://${process.env.PLAYWRIGHT_SERVER_HOST ?? "127.0.0.1"}:${process.env.PLAYWRIGHT_SERVER_PORT ?? "4096"}`
const sessionA = session("ses_tab_a", "Tab A session")
@@ -175,6 +176,9 @@ test("appearance experimental setting switches tab orientation", async ({ page }
const settings = page.getByTestId("settings-screen")
await expect(settings).toBeVisible()
const version = settings.getByRole("tablist").getByText(`v${pkg.version}`, { exact: true })
await expect(settings.getByRole("tablist").getByText("OpenCode Desktop", { exact: true })).toBeInViewport()
await expect(version).toBeInViewport()
await settings.getByRole("tab", { name: "Appearance" }).click()
await expect(settings.getByRole("heading", { name: "Experimental" })).toBeVisible()
@@ -194,6 +198,17 @@ test("appearance experimental setting switches tab orientation", async ({ page }
await page.setViewportSize({ width: 800, height: 720 })
await expect(settings.getByRole("tablist")).toHaveCSS("width", "160px")
await expect(version).toBeInViewport()
await page.setViewportSize({ width: 390, height: 720 })
await expect(version).toBeInViewport()
await settings.evaluate((element) => element.setAttribute("dir", "rtl"))
await expect(version).toBeInViewport()
await expect(version).toHaveCSS("direction", "ltr")
await page.setViewportSize({ width: 390, height: 360 })
await version.scrollIntoViewIfNeeded()
await expect(version).toBeInViewport()
})
test("vertical tab preference falls back to horizontal on mobile", async ({ page }) => {
@@ -0,0 +1,194 @@
import { expect, test, type Locator, type Page } from "@playwright/test"
import type { OpenCodeEvent, WorktreeDirectory } from "@opencode-ai/client/promise"
import { base64Encode } from "@opencode-ai/util/encode"
import { mockOpenCodeServer } from "../utils/mock-server"
import { expectAppVisible, expectSessionReady } from "../utils/waits"
const root = "C:/OpenCode/WorkspaceAccent"
const workspace = `${root}/.worktrees/feature`
const projectID = "proj_workspace_accent"
const sessionID = "ses_workspace_accent"
const title = "Workspace accent regression"
const server = `http://${process.env.PLAYWRIGHT_SERVER_HOST ?? "127.0.0.1"}:${process.env.PLAYWRIGHT_SERVER_PORT ?? "4096"}`
const inventory: WorktreeDirectory[] = [
{ directory: root },
{ directory: workspace, strategy: "git" },
{ directory: "C:/OpenCode/LinkedWorkspace", strategy: "git" },
{ directory: "C:/OpenCode/WorkspaceCopy", strategy: "copy" },
{ directory: "C:/OpenCode/RegisteredDirectory" },
]
test.use({ serviceWorkers: "block" })
for (const scenario of [
{ name: "managed Git worktree", directory: workspace, accent: true },
{ name: "linked Git worktree outside main", directory: "C:/OpenCode/LinkedWorkspace", accent: true },
{
name: "linked Git worktree on a narrow screen",
directory: "C:/OpenCode/LinkedWorkspace",
accent: true,
viewport: { width: 390, height: 844 },
},
{ name: "main root with Windows case and separators", directory: "c:\\OPENCODE\\workspaceaccent\\", accent: false },
{ name: "nested main directory", directory: `${root}/packages/app`, accent: false },
{ name: "nested workspace inside main", directory: `${workspace}/packages/app`, accent: true },
{
name: "workspace with Windows case and separators",
directory: "c:\\opencode\\WORKSPACEACCENT\\.worktrees\\FEATURE\\src\\",
accent: true,
},
{ name: "unregistered sibling with the same prefix", directory: `${workspace}-unregistered`, accent: false },
{ name: "workspace using another strategy", directory: "C:/OpenCode/WorkspaceCopy", accent: true },
{ name: "registered directory without a strategy", directory: "C:/OpenCode/RegisteredDirectory", accent: true },
]) {
test(`existing session send button: ${scenario.name}`, async ({ page }, testInfo) => {
if (scenario.viewport) await page.setViewportSize(scenario.viewport)
const view = await openSession(page, scenario.directory)
await view.input.fill("Inspect this fixture workspace.")
await expect(view.send).toBeEnabled()
if (scenario.name === "managed Git worktree") {
// Capture before the color assertion so both red and green runs have evidence.
const path = testInfo.outputPath("workspace-accent.png")
await view.composer.screenshot({ path })
await testInfo.attach("workspace-accent", { path, contentType: "image/png" })
}
await expectBackground(view.send, scenario.accent ? "accent" : "contrast")
const message = page.locator('[data-slot="user-message-text"]')
await expect(message).toHaveText("Check this fixture workspace.")
await expectBackground(message, scenario.accent ? "accent" : "layer-02", "background-color")
})
}
test("inventory updates recolor the send button without navigation; disabled and stop stay neutral", async ({
page,
}) => {
const view = await openSession(page, workspace, [{ directory: root }])
await view.input.fill("Keep this draft while the inventory changes.")
await expect(view.send).toBeEnabled()
await expectBackground(view.send, "contrast")
const url = page.url()
const refreshed = page.waitForResponse(
(response) =>
new URL(response.url()).pathname === `/api/worktree/${projectID}` && response.request().method() === "GET",
)
view.worktrees.push({ directory: workspace, strategy: "git" })
view.events.push({
id: "evt_workspace_accent_inventory",
created: 1700000001000,
type: "worktree.updated",
data: { projectID },
})
expect((await refreshed).ok()).toBe(true)
await expectBackground(view.send, "accent")
await expect(page).toHaveURL(url)
await expect(view.input).toHaveText("Keep this draft while the inventory changes.")
await expect(view.send).toBeEnabled()
await view.input.fill("")
await expect(view.send).toBeDisabled()
await expectBackground(view.send, "contrast")
view.events.push({
id: "evt_workspace_accent_running",
created: 1700000002000,
type: "session.execution.started",
durable: { aggregateID: sessionID, seq: 1, version: 1 },
data: { sessionID },
})
const stop = view.composer.getByRole("button", { name: "Stop", exact: true })
await expect(stop).toBeEnabled()
await expectBackground(stop, "contrast")
await view.input.fill("Send a follow-up instead of stopping.")
await expect(view.send).toBeEnabled()
await expectBackground(view.send, "accent")
await expect(page).toHaveURL(url)
})
async function openSession(page: Page, directory: string, worktrees = [...inventory]) {
const events: OpenCodeEvent[] = []
await mockOpenCodeServer(page, {
directory,
project: {
id: projectID,
canonical: root,
worktree: root,
vcs: "git",
name: "workspace-accent",
time: { created: 1700000000000, updated: 1700000000000 },
sandboxes: [],
},
provider: {
all: [
{
id: "opencode",
name: "OpenCode",
models: { "accent-model": { id: "accent-model", name: "Accent Model", limit: { context: 200_000 } } },
},
],
connected: ["opencode"],
default: { providerID: "opencode", modelID: "accent-model" },
},
sessions: [
{
id: sessionID,
projectID,
directory,
title,
model: { id: "accent-model", providerID: "opencode" },
time: { created: 1700000000000, updated: 1700000000000 },
},
],
pageMessages: () => ({
items: [
{
id: "msg_workspace_accent",
type: "user",
text: "Check this fixture workspace.",
time: { created: 1700000000000 },
},
],
}),
events: () => events.splice(0),
})
// Keep authoritative inventory independent of the raw project's empty sandboxes.
await page.route(`**/api/worktree/${projectID}`, (route) => {
if (route.request().method() !== "GET") return route.fallback()
return route.fulfill({ json: worktrees, headers: { "access-control-allow-origin": "*" } })
})
await page.addInitScript(() => {
localStorage.setItem("opencode-theme-id", "oc-2")
localStorage.setItem("opencode-color-scheme", "light")
})
const loaded = page.waitForResponse(
(response) =>
new URL(response.url()).pathname === `/api/worktree/${projectID}` && response.request().method() === "GET",
)
await page.goto(`/server/${base64Encode(server)}/session/${sessionID}`)
expect((await loaded).ok()).toBe(true)
await expectSessionReady(page, { server, sessionID, title })
await expect(page.locator("html")).toHaveAttribute("data-color-scheme", "light")
const composer = page.locator('[data-component="composer"]')
await expectAppVisible(composer)
const input = composer.getByRole("textbox", { name: "Prompt", exact: true })
await expect(input).toBeEditable()
await expect(composer.locator('[data-action="composer-model"]')).toHaveText("Accent Model")
return { composer, input, send: composer.getByRole("button", { name: "Send", exact: true }), events, worktrees }
}
async function expectBackground(element: Locator, token: string, property = "background-image") {
const color = await element.evaluate((element, token) => {
// Resolve semantic colors through the browser, without reproducing the button's gradient.
const probe = document.createElement("span")
probe.hidden = true
probe.style.backgroundColor = `var(--v2-background-bg-${token})`
element.append(probe)
const color = getComputedStyle(probe).backgroundColor
probe.remove()
return color
}, token)
await expect(element).toHaveCSS(property, new RegExp(color.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")))
}
+352 -98
View File
@@ -1,60 +1,124 @@
import { expect, test } from "@playwright/test"
import { readFile } from "node:fs/promises"
import { createServer } from "node:http"
import { expect, test, type Page } from "@playwright/test"
import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"
import { createServer, type ServerResponse } from "node:http"
import { once } from "node:events"
import { createHash } from "node:crypto"
import { join, extname, relative, sep } from "node:path"
import { tmpdir } from "node:os"
import { fileURLToPath } from "node:url"
import { build } from "vite"
import { serviceWorker } from "../../vite.pwa"
const legacy = `
self.addEventListener("install", event => event.waitUntil(
caches.open("workbox-precache-v2-" + self.registration.scope).then(cache =>
cache.addAll(["/index.html", "/assets/app-old.js", "/assets/lazy-old.js"])
)
))
self.addEventListener("fetch", event => {
if (event.request.mode === "navigate") {
event.respondWith(caches.match("/index.html"))
return
}
event.respondWith(caches.match(event.request).then(response => response || fetch(event.request)))
})
`
type Site = {
url: string
deploy: (fault?: "failed" | "html" | "corrupt" | "mixed-html" | "blocked") => void
legacy: () => void
requests: string[]
release: () => void
}
const fixture = test.extend<{ site: { url: string; upgrade: () => void; repair: () => void } }>({
site: async ({}, use) => {
const worker = await readFile(new URL("../../dist/sw.js", import.meta.url), "utf8")
const state = { version: "old", repaired: false }
const fixture = test.extend<{ site: Site }, { builds: Record<string, Record<string, Buffer>> }>({
builds: [
async ({}, use) => {
const directory = await mkdtemp(join(tmpdir(), "opencode-precache-"))
const builds: Record<string, Record<string, Buffer>> = {}
try {
for (const version of ["old", "new"]) {
const root = join(directory, version)
const outDir = join(root, "dist")
await mkdir(join(root, "public", "nested"), { recursive: true })
await Promise.all(
Object.entries({
"index.html": `<html><head></head><body><h1>Loading</h1><label>Draft<textarea></textarea></label><button>Load lazy</button><output></output><script type="module" src="/main.js"></script></body></html>`,
"main.js": `document.querySelector("h1").textContent = "${version}";
document.querySelector("button").onclick = async () => {
document.querySelector("output").textContent = await (await import("./lazy.js")).load()
};`,
"lazy.js": `export async function load() { return (await import("./nested.js")).value }`,
"nested.js": `export const value = "${version} nested lazy loaded"`,
"public/nested/data.json": JSON.stringify({ version }),
"public/nested/font.woff2": `font-${version}`,
"public/nested/module.wasm": Buffer.from([0, 97, 115, 109, 1, 0, 0, 0]),
"public/large.bin": Buffer.alloc(2 * 1024 * 1024 + 1, version === "old" ? 1 : 2),
"public/_headers": "/*\n Cache-Control: no-cache",
"public/_redirects": "/* /index.html 200",
}).map(([path, contents]) => writeFile(join(root, path), contents)),
)
await build({
configFile: false,
root,
logLevel: "silent",
build: { outDir, assetsDir: "_assets", sourcemap: true },
plugins: serviceWorker(outDir),
})
builds[version] = Object.fromEntries(
await Promise.all(
(await readdir(outDir, { recursive: true, withFileTypes: true }))
.filter((entry) => entry.isFile())
.map(async (entry) => {
const path = join(entry.parentPath, entry.name)
return ["/" + relative(outDir, path).split(sep).join("/"), await readFile(path)]
}),
),
)
}
await use(builds)
} finally {
await rm(directory, { recursive: true, force: true })
}
},
{ scope: "worker" },
],
site: async ({ builds }, use) => {
const state = { version: "old", fault: "", legacy: false }
const requests: string[] = []
const blocked: ServerResponse[] = []
const release = () => blocked.splice(0).forEach((response) => response.end(builds.new["/large.bin"]))
const server = createServer((request, response) => {
const pathname = new URL(request.url ?? "/", "http://localhost").pathname
const prefix = state.version === "old" ? "/assets" : "/_assets"
const path = new URL(request.url ?? "/", "http://localhost").pathname
requests.push(path)
response.setHeader("cache-control", "no-store")
if (pathname === "/sw.js") {
if (path === "/observer.html")
return void response.writeHead(200, { "content-type": "text/html" }).end("<title>Worker observer</title>")
if (path === "/api/health")
return void response.writeHead(200, { "content-type": "application/json" }).end('{"healthy":true}')
if (path === "/sw.js" && state.legacy && state.version === "old") {
// Model the shipped worker's shared precache name and cache-first navigation behavior.
const urls = Object.keys(builds.old).filter(
(path) => path === "/index.html" || (path.startsWith("/_assets/") && path.endsWith(".js")),
)
response.setHeader("content-type", "text/javascript")
response.end(state.version === "old" ? legacy : worker)
return
}
if (pathname === `${prefix}/app-${state.version}.js`) {
response.setHeader("content-type", "text/javascript")
response.end(`import "${prefix}/startup-${state.version}.js"`)
return
}
if (pathname === `${prefix}/startup-${state.version}.js`) {
response.setHeader("content-type", "text/javascript")
response.end(`
document.getElementById("root").innerHTML = '<h1>${state.version}</h1><label>Draft<input></label><button>Load older chunk</button><output></output>'
document.querySelector("button").onclick = () => import("/assets/lazy-old.js")
return void response.end(`
self.addEventListener("install", event => event.waitUntil(
caches.open("workbox-precache-v2-" + self.registration.scope).then(cache => cache.addAll(${JSON.stringify(urls)}))
));
self.addEventListener("fetch", event => event.respondWith(
caches.match(event.request.mode === "navigate" ? "/index.html" : event.request)
.then(response => response || fetch(event.request))
));
`)
return
}
if (
(pathname === "/assets/lazy-old.js" && state.version === "old") ||
(pathname === "/_assets/retry.js" && state.repaired)
) {
response.setHeader("content-type", "text/javascript")
response.end('document.querySelector("output").textContent = "Older chunk loaded"')
return
if (path === "/index.html" && state.fault === "mixed-html")
return void response.writeHead(200, { "content-type": "text/html" }).end(builds.old["/index.html"])
if (path === "/large.bin" && state.fault && state.fault !== "mixed-html") {
if (state.fault === "blocked") return void blocked.push(response)
if (state.fault === "failed") return void response.writeHead(503).end("Unavailable")
if (state.fault === "html")
return void response.writeHead(200, { "content-type": "text/html" }).end("<html>Wrong fallback</html>")
return void response.end("Incorrect bytes with a successful status")
}
// Deliberately retain the old server's fallback so the worker must reject HTML asset responses itself.
const file = builds[state.version][path]
const types: Record<string, string> = {
".js": "text/javascript",
".html": "text/html",
".json": "application/json",
".wasm": "application/wasm",
}
response.setHeader("content-type", types[extname(path)] ?? "application/octet-stream")
if (file) return void response.end(file)
if (extname(path)) return void response.writeHead(404).end("Not found")
response.setHeader("content-type", "text/html")
response.end(`<div id="root"></div><script type="module" src="${prefix}/app-${state.version}.js"></script>`)
response.end(builds[state.version]["/index.html"])
})
server.listen(0, "127.0.0.1")
await once(server, "listening")
@@ -63,75 +127,265 @@ const fixture = test.extend<{ site: { url: string; upgrade: () => void; repair:
try {
await use({
url: `http://127.0.0.1:${address.port}`,
upgrade: () => (state.version = "new"),
repair: () => (state.repaired = true),
deploy: (fault = undefined) => {
state.version = "new"
state.fault = fault ?? ""
},
legacy: () => {
state.legacy = true
},
requests,
release,
})
} finally {
release()
server.closeAllConnections()
await new Promise<void>((resolve, reject) => server.close((error) => (error ? reject(error) : resolve())))
}
},
})
fixture("updates a legacy worker without reloading drafts or deleting old chunks", async ({ page, site }) => {
await page.goto(site.url)
async function install(page: Page, url: string) {
await page.goto(url)
await expect(page.getByRole("heading")).toHaveText("old")
await page.evaluate(async () => {
await navigator.serviceWorker.register("/sw.js")
await navigator.serviceWorker.ready
})
await page.goto(site.url)
await page.reload()
await expect.poll(() => page.evaluate(() => navigator.serviceWorker.controller?.state)).toBe("activated")
await expect(page.getByRole("heading")).toHaveText("old")
await page.getByLabel("Draft").fill("Keep this unsent prompt")
}
site.upgrade()
await page.evaluate(async () => {
const cache = await caches.open("opencode-assets")
await cache.put(
"/_assets/startup-new.js",
new Response("<html>stale fallback</html>", {
headers: { "content-type": "text/html" },
}),
)
const changed = new Promise<void>((resolve) =>
navigator.serviceWorker.addEventListener("controllerchange", () => resolve(), { once: true }),
)
async function update(page: Page) {
return page.evaluateHandle(async () => {
const registration = await navigator.serviceWorker.getRegistration()
if (!registration) throw new Error("Missing legacy worker")
await registration.update()
await changed
})
await expect(page.getByLabel("Draft")).toHaveValue("Keep this unsent prompt")
await page.getByRole("button", { name: "Load older chunk" }).click()
await expect(page.getByRole("status")).toHaveText("Older chunk loaded")
await page.goto(`${site.url}/workspace/example`)
await expect(page.getByRole("heading")).toHaveText("new")
await expect
.poll(() =>
page.evaluate(async () =>
(await (await caches.open("opencode-assets")).match("/_assets/startup-new.js"))?.headers.get("content-type"),
if (!registration) throw new Error("Missing installed worker")
const found = new Promise<ServiceWorker>((resolve) =>
registration.addEventListener(
"updatefound",
() => {
if (!registration.installing) throw new Error("Missing installing worker")
resolve(registration.installing)
},
{ once: true },
),
)
.toBe("text/javascript")
await registration.update()
return found
})
}
async function waiting(page: Page) {
await expect
.poll(() => page.evaluate(async () => (await navigator.serviceWorker.getRegistration())?.waiting?.state))
.toBe("installed")
}
fixture(
"opens an uncached route offline and executes never-used nested lazy chunks",
async ({ page, context, site }) => {
await install(page, site.url)
await expect(page.getByRole("status")).toBeEmpty()
await context.setOffline(true)
await page.goto(`${site.url}/workspace/never-visited`)
await expect(page.getByRole("heading")).toHaveText("old")
await page.getByRole("button", { name: "Load lazy" }).click()
await expect(page.getByRole("status")).toHaveText("old nested lazy loaded")
},
)
fixture(
"precaches public files of every type and size, excluding deployment metadata and source maps",
async ({ page, site, builds, context }) => {
await install(page, site.url)
const files = ["/nested/data.json", "/nested/font.woff2", "/nested/module.wasm", "/large.bin"]
await context.setOffline(true)
for (const path of files) {
const digest = await page.evaluate(
async (path) =>
Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256", await (await fetch(path)).arrayBuffer()))),
path,
)
expect(Buffer.from(digest)).toEqual(createHash("sha256").update(builds.old[path]).digest())
}
expect(site.requests).not.toContain("/_headers")
expect(site.requests).not.toContain("/_redirects")
expect(site.requests.filter((path) => path.endsWith(".map"))).toEqual([])
},
)
fixture(
"keeps drafts and removed old lazy chunks until every controlled tab closes",
async ({ page, context, site, builds }) => {
await install(page, site.url)
const second = await context.newPage()
await second.goto(site.url)
await expect(second.getByRole("heading")).toHaveText("old")
await second.getByLabel("Draft").fill("Keep this unsent prompt")
site.deploy()
const created = context.waitForEvent("serviceworker")
const worker = await update(page)
const replacement = await created
await waiting(page)
expect(await worker.evaluate((worker) => worker.state)).toBe("installed")
await expect(second.getByLabel("Draft")).toHaveValue("Keep this unsent prompt")
await page.close()
await waiting(second)
await expect(second.getByRole("heading")).toHaveText("old")
await expect(second.getByLabel("Draft")).toHaveValue("Keep this unsent prompt")
const removed = Object.keys(builds.old).find((path) => path.includes("/nested-") && path.endsWith(".js"))
expect(removed).toBeDefined()
expect((await second.request.get(`${site.url}${removed}`)).status()).toBe(404)
await second.getByRole("button", { name: "Load lazy" }).click()
await expect(second.getByRole("status")).toHaveText("old nested lazy loaded")
await expect(second.getByLabel("Draft")).toHaveValue("Keep this unsent prompt")
await second.close()
await expect
.poll(() =>
replacement.evaluate(() => {
const registration = (self as unknown as { registration: ServiceWorkerRegistration }).registration
return { waiting: !!registration.waiting, active: registration.active?.state }
}),
)
.toEqual({ waiting: false, active: "activated" })
await context.setOffline(true)
const observer = await context.newPage()
await observer.goto(`${site.url}/workspace/reopened`)
await expect(observer.getByRole("heading")).toHaveText("new")
await observer.getByRole("button", { name: "Load lazy" }).click()
await expect(observer.getByRole("status")).toHaveText("new nested lazy loaded")
},
)
for (const fault of ["failed", "html", "corrupt", "mixed-html"] as const) {
fixture(`retains the old complete build when a precache download is ${fault}`, async ({ page, context, site }) => {
await install(page, site.url)
await page.getByLabel("Draft").fill("Still editing")
site.deploy(fault)
const worker = await update(page)
await expect.poll(() => worker.evaluate((worker) => worker.state)).toBe("redundant")
expect(await page.evaluate(async () => (await navigator.serviceWorker.getRegistration())?.waiting)).toBeNull()
await expect(page.getByLabel("Draft")).toHaveValue("Still editing")
await context.setOffline(true)
await page.goto(`${site.url}/workspace/after-failure`)
await expect(page.getByRole("heading")).toHaveText("old")
await page.getByRole("button", { name: "Load lazy" }).click()
await expect(page.getByRole("status")).toHaveText("old nested lazy loaded")
})
}
fixture("does not expose new HTML while a precache download is blocked", async ({ page, context, site }) => {
await install(page, site.url)
site.requests.length = 0
site.deploy("blocked")
const worker = await update(page)
await expect.poll(() => site.requests.includes("/large.bin")).toBe(true)
expect(await worker.evaluate((worker) => worker.state)).toBe("installing")
const second = await context.newPage()
await second.goto(`${site.url}/workspace/during-install`)
await expect(second.getByRole("heading")).toHaveText("old")
site.release()
await waiting(page)
await second.reload()
await expect(second.getByRole("heading")).toHaveText("old")
})
fixture("does not cache HTML responses under asset URLs", async ({ page, site }) => {
site.upgrade()
await page.goto(site.url)
await expect(page.getByRole("heading")).toHaveText("new")
await page.evaluate(async () => {
await navigator.serviceWorker.register("/sw.js")
await navigator.serviceWorker.ready
})
await page.goto(site.url)
await expect(page.getByRole("heading")).toHaveText("new")
expect(await page.evaluate(async () => (await fetch("/_assets/retry.js")).headers.get("content-type"))).toBe(
"text/html",
)
site.repair()
expect(await page.evaluate(async () => (await fetch("/_assets/retry.js")).headers.get("content-type"))).toBe(
"text/javascript",
)
fixture("upgrades the legacy shared precache only after old tabs close", async ({ page, context, site, builds }) => {
site.legacy()
const observer = await context.newPage()
await observer.goto(`${site.url}/observer.html`)
await install(page, site.url)
await page.getByLabel("Draft").fill("Legacy unsent prompt")
// A stale runtime-cache HTML response must not contaminate the new generated precache.
const entry = Object.keys(builds.new).find((path) => path.includes("/index-") && path.endsWith(".js"))
expect(entry).toBeDefined()
await page.evaluate(async (entry) => {
await (
await caches.open("opencode-assets")
).put(entry!, new Response("<html>stale fallback</html>", { headers: { "content-type": "text/html" } }))
}, entry)
site.deploy()
await update(page)
await waiting(page)
await expect(page.getByLabel("Draft")).toHaveValue("Legacy unsent prompt")
await page.getByRole("button", { name: "Load lazy" }).click()
await expect(page.getByRole("status")).toHaveText("old nested lazy loaded")
await page.close()
await expect
.poll(() => observer.evaluate(async () => !!(await navigator.serviceWorker.getRegistration())?.waiting))
.toBe(false)
await context.setOffline(true)
await observer.goto(`${site.url}/workspace/legacy-upgraded`)
await expect(observer.getByRole("heading")).toHaveText("new")
await observer.getByRole("button", { name: "Load lazy" }).click()
await expect(observer.getByRole("status")).toHaveText("new nested lazy loaded")
})
fixture("does not substitute cached HTML for API or missing asset navigations", async ({ page, site }) => {
await install(page, site.url)
const api = await page.goto(`${site.url}/api/health`)
expect(await api?.json()).toEqual({ healthy: true })
expect(api?.fromServiceWorker()).toBe(false)
const asset = await page.goto(`${site.url}/_assets/missing.js`)
expect(asset?.status()).toBe(404)
expect(await asset?.text()).toBe("Not found")
})
test("the production build precaches every deployable file", async ({ page, context }) => {
const directory = new URL("../../dist/", import.meta.url)
const files = (await readdir(directory, { recursive: true, withFileTypes: true }))
.filter((entry) => entry.isFile())
.map((entry) => "/" + relative(fileURLToPath(directory), join(entry.parentPath, entry.name)).split(sep).join("/"))
.filter((path) => !path.endsWith(".map") && !["/_headers", "/_redirects", "/sw.js"].includes(path))
expect(files.length).toBeGreaterThan(1)
const server = createServer(async (request, response) => {
const path = new URL(request.url ?? "/", "http://localhost").pathname
response.setHeader("cache-control", "no-store")
if (path === "/probe.html")
return void response.writeHead(200, { "content-type": "text/html" }).end("<title>Precache probe</title>")
const bytes = await readFile(new URL(`.${path}`, directory)).catch(() => undefined)
if (!bytes) return void response.writeHead(404).end("Not found")
if (path.endsWith(".js")) response.setHeader("content-type", "text/javascript")
if (path.endsWith(".html")) {
response.setHeader("content-type", "text/html")
// Inspect the real cached HTML without executing the app or contacting a backend.
response.setHeader("content-security-policy", "default-src 'none'")
}
response.end(bytes)
})
server.listen(0, "127.0.0.1")
await once(server, "listening")
const address = server.address()
if (!address || typeof address === "string") throw new Error("Expected a TCP address")
const url = `http://127.0.0.1:${address.port}`
try {
await page.goto(`${url}/probe.html`)
await page.evaluate(async () => {
await navigator.serviceWorker.register("/sw.js")
await navigator.serviceWorker.ready
})
const cached = await page.evaluate(async () =>
(
await Promise.all(
(await caches.keys()).map(async (name) =>
(await (await caches.open(name)).keys()).map((request) => new URL(request.url).pathname),
),
)
)
.flat()
.sort(),
)
expect(cached).toEqual(files.sort())
await context.setOffline(true)
const response = await page.goto(`${url}/workspace/offline-probe`)
expect(response?.fromServiceWorker()).toBe(true)
expect(await response?.text()).toBe(await readFile(new URL("index.html", directory), "utf8"))
} finally {
server.closeAllConnections()
await new Promise<void>((resolve, reject) => server.close((error) => (error ? reject(error) : resolve())))
}
})
@@ -1,9 +1,14 @@
import { defineConfig } from "@playwright/test"
// Tiny fixture builds do not need a Rolldown thread for every host CPU.
process.env.RAYON_NUM_THREADS ??= "2"
export default defineConfig({
testDir: ".",
testMatch: "*.spec.ts",
outputDir: "../test-results/service-worker",
timeout: 30_000,
timeout: 60_000,
workers: 1,
expect: { timeout: 15_000 },
use: { browserName: "chromium" },
})
+2 -4
View File
@@ -7,10 +7,8 @@
content="width=device-width, initial-scale=1, interactive-widget=resizes-content, viewport-fit=cover"
/>
<title>OpenCode</title>
<link rel="icon" type="image/png" href="/favicon-96x96-v3.png" sizes="96x96" />
<link rel="icon" type="image/svg+xml" href="/favicon-v3.svg" />
<link rel="shortcut icon" href="/favicon-v3.ico" />
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon-v3.png" />
<link rel="icon" type="image/x-icon" href="%OPENCODE_FAVICON%" />
<link rel="apple-touch-icon" sizes="180x180" href="%OPENCODE_APPLE_TOUCH_ICON%" />
<link rel="manifest" href="/site.webmanifest" />
<meta name="theme-color" content="#fafafa" />
<meta name="mobile-web-app-capable" content="yes" />
+24
View File
@@ -0,0 +1,24 @@
{
"name": "OpenCode",
"short_name": "OpenCode",
"id": "/",
"start_url": "/",
"scope": "/",
"icons": [
{
"src": "/web-app-manifest-192x192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "any"
},
{
"src": "/web-app-manifest-512x512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "any"
}
],
"theme_color": "#080808",
"background_color": "#080808",
"display": "standalone"
}
-1
View File
@@ -1 +0,0 @@
../../ui/src/assets/favicon/site.webmanifest
+2 -1
View File
@@ -103,7 +103,8 @@ export type NewSessionComposerAdapter = ComposerAdapterBase & {
start: (
selection: ComposerSelection,
submission: ReturnType<typeof createComposerSubmission>,
) => Promise<{ session: ComposerSession; cleanupReady: Promise<void> } | undefined>
message: SessionMessageUser,
) => Promise<{ session: ComposerSession; cleanupReady: Promise<void>; complete?: () => Promise<void> } | undefined>
}
export type ComposerAdapter = ActiveComposerAdapter | NewSessionComposerAdapter
@@ -384,10 +384,18 @@ export function createComposerEditor(input: {
void attachments.handlePaste(event)
return
}
const text = clipboard?.getData("text/plain")
const text = clipboard?.getData("text/plain").replace(/\r\n?/g, "\n")
if (!text) return
event.preventDefault()
if (typeof document.execCommand === "function" && document.execCommand("insertText", false, text)) return
// insertText emits input events per line, repeatedly parsing and saving the draft.
// Escaped HTML inserts multiline text once and preserves native selection and undo.
const multiline = text.includes("\n")
const value = multiline ? text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;") : text
if (
typeof document.execCommand === "function" &&
document.execCommand(multiline ? "insertHTML" : "insertText", false, value)
)
return
const target = event.currentTarget
const selection = window.getSelection()
if (!(target instanceof HTMLElement) || !selection?.rangeCount || !target.contains(selection.anchorNode)) return
+44
View File
@@ -229,6 +229,50 @@ describe("Composer submission", () => {
})
})
test("previews the first prompt while starting and hands it off before completing preparation", async () => {
const draft = createMemoryComposerState({ prompt: "prepare my worktree" }).capture()
const preview = Promise.withResolvers<SessionMessageUser>()
const ready = Promise.withResolvers<void>()
const calls: string[] = []
const handoff: SessionMessageUser[] = []
const target = session({
calls,
handoff: { set: (message) => handoff.push(message), clear() {} },
prompt: async () => undefined,
})
const adapter: NewSessionComposerAdapter = {
kind: "new-session",
state: draft,
ready: () => true,
controls,
working: () => false,
submitted() {},
async start(_selection, _submission, message) {
preview.resolve(message)
await ready.promise
return {
session: target,
cleanupReady: Promise.resolve(),
async complete() {
expect(handoff).toHaveLength(1)
expect(handoff[0]?.id).toBe(message.id)
expect(handoff[0]?.text).toBe("prepare my worktree")
calls.push("complete")
},
}
},
}
const submitted = submitInput(adapter).submit(new Event("submit"))
expect(await preview.promise).toMatchObject({ type: "user", text: "prepare my worktree" })
expect(calls).toEqual([])
expect(draft.current()).toMatchObject([{ content: "prepare my worktree" }])
ready.resolve()
await submitted
expect(calls).toContain("complete")
expect(draft.current()).toEqual([{ type: "text", content: "", start: 0, end: 0 }])
})
test("does not restore a prompt already acknowledged by the durable inbox", async () => {
const state = createMemoryComposerState({ prompt: "admitted prompt" }).capture()
const checked = Promise.withResolvers<void>()
+17 -3
View File
@@ -70,7 +70,7 @@ export function createComposerSubmit(input: ComposerSubmitInput) {
const started =
input.adapter.kind === "active-session"
? { session: input.adapter.session(), cleanupReady: Promise.resolve() }
: await input.adapter.start(value.selection, submission)
: await input.adapter.start(value.selection, submission, handoffMessage(value))
if (!started) return
const session = started.session
@@ -80,7 +80,7 @@ export function createComposerSubmit(input: ComposerSubmitInput) {
const command = value.mode === "normal" ? findCommand(session, value.text) : undefined
if (value.mode === "normal" && !command) {
if (value.images.length > 0) session.handoff?.set(handoffMessage(value))
session.handoff?.set(handoffMessage(value))
const optimisticBusy = !input.adapter.working()
if (optimisticBusy) session.data.session.setStatus(session.id, "running")
const sending = sendPrompt(session, value).then(
@@ -88,6 +88,7 @@ export function createComposerSubmit(input: ComposerSubmitInput) {
(error) => ({ ok: false as const, error }),
)
await started.cleanupReady
await started.complete?.()
input.adapter.submitted()
submission.context
.filter((item) => !!item.comment?.trim())
@@ -104,6 +105,7 @@ export function createComposerSubmit(input: ComposerSubmitInput) {
}
await started.cleanupReady
await started.complete?.()
input.adapter.submitted()
if (value.mode === "shell") {
@@ -122,7 +124,6 @@ export function createComposerSubmit(input: ComposerSubmitInput) {
)
return
}
} finally {
submitting.delete(input.adapter.state)
}
@@ -147,6 +148,19 @@ function handoffMessage(value: ComposerSubmission): SessionMessageUser {
})),
metadata: {
displayText: value.text,
comments: value.context.flatMap((item) =>
item.comment?.trim()
? [
{
path: item.path,
comment: item.comment.trim(),
...(item.selection ? { selection: { ...item.selection } } : {}),
...(item.preview !== undefined ? { preview: item.preview } : {}),
...(item.commentOrigin ? { origin: item.commentOrigin } : {}),
},
]
: [],
),
agent: value.selection.agent,
model: {
...value.selection.model,
@@ -1,6 +1,7 @@
import { base64Encode } from "@opencode-ai/util/encode"
import { getDirectory } from "@opencode-ai/util/path"
import type { SessionMessageUser } from "@opencode-ai/client/promise"
import { Session } from "@opencode-ai/schema/session"
import { startTransition } from "solid-js"
import type { NewSessionComposerAdapter } from "@/composer/adapter"
import { useComposerState } from "@/composer/persistence"
@@ -43,20 +44,32 @@ export function createNewSessionComposerAdapter(props: {
controls,
working: () => false,
submitted: props.submitted,
async start(selection, submission) {
async start(selection, submission, message) {
const draftID = props.draftID
const projectDirectory = location().directory
const worktree = props.worktree()
const branch = props.branch()
const id = Session.ID.create()
const pending =
worktree === "create"
? tabs.prepareSession(draftID, { server: server.key, sessionId: id }, { message, selection })
: undefined
await pending?.ready
const sessionDirectory = await resolveSessionDirectory({
projectDirectory,
worktree,
branch: props.branch(),
branch,
data,
serverSDK,
language,
})
if (!sessionDirectory) return
if (!sessionDirectory) {
await pending?.rollback()
return
}
const created = data.session.create({
id,
agent: selection.agent,
model: {
id: selection.model.modelID,
@@ -75,6 +88,13 @@ export function createNewSessionComposerAdapter(props: {
return { ok: false as const, error }
},
)
if (pending && !(await creation).ok) {
// Keep retries on the worktree that was already created, not another new checkout.
data.project.invalidate()
await data.project.sync().catch(() => undefined)
await pending.rollback(sessionDirectory)
return
}
const afterCreation = async <T>(run: () => Promise<T>) => {
const result = await creation
if (!result.ok) throw result.error
@@ -85,13 +105,13 @@ export function createNewSessionComposerAdapter(props: {
SessionRouteKey.fromRoute(base64Encode(sessionDirectory), created.id),
)
const cleanupReady = startTransition(() => {
tabs.updateDraft(props.draftID, { worktree: undefined, branch: undefined })
if (!pending) tabs.updateDraft(draftID, { worktree: undefined, branch: undefined })
local.session.promote(sessionDirectory, created.id, {
agent: selection.agent,
model: selection.model,
variant: selection.variant ?? null,
})
tabs.promoteDraft(props.draftID, { server: server.key, sessionId: created.id })
if (!pending) tabs.promoteDraft(draftID, { server: server.key, sessionId: created.id })
submission.retarget(
prompt.capture(
{ dir: base64Encode(sessionDirectory), id: created.id },
@@ -102,6 +122,7 @@ export function createNewSessionComposerAdapter(props: {
return {
cleanupReady,
complete: pending?.complete,
session: {
id: created.id,
directory: sessionDirectory,
@@ -25,7 +25,7 @@ export const DialogSelectMcp: Component = () => {
.sort((a, b) => a.name.localeCompare(b.name)),
)
const toggle = useMcpToggle()
const toggle = useMcpToggle(() => sdk().directory)
const enabledCount = createMemo(() => items().filter((i) => i.status === "connected").length)
const totalCount = createMemo(() => items().length)
@@ -40,6 +40,9 @@ export function useMcpToggle(directory?: Accessor<string | undefined>, onSuccess
data.location.mcp.server.invalidate(ref)
data.location.mcp.resource.invalidate(ref)
await Promise.all([data.location.mcp.server.sync(ref), data.location.mcp.resource.sync(ref), onSuccess?.()])
// A successful HTTP response can still leave the MCP connection in a failed state.
const status = data.location.mcp.server.list(ref)?.find((item) => item.name === name)?.status
if (status?.status === "failed") throw new Error(`${name}: ${status.error}`)
},
onError: (error) =>
showToast({
+6
View File
@@ -734,6 +734,7 @@ export const dict = {
"session.new.worktree.main": "Main branch",
"session.new.worktree.mainWithBranch": "Main branch ({{branch}})",
"session.new.worktree.create": "Create new worktree",
"session.new.worktree.creating": "Creating worktree",
"session.new.workspace.runIn": "Run session in",
"session.new.workspace.triggerLocal": "Local",
"session.new.workspace.local": "Local repository",
@@ -983,6 +984,11 @@ export const dict = {
"settings.general.row.followUpBehavior.steer": "Steer",
"settings.general.row.reasoningSummaries.title": "Show reasoning summaries",
"settings.general.row.reasoningSummaries.description": "Display model reasoning summaries in the timeline",
"settings.general.row.reasoningMode.title": "Model reasoning",
"settings.general.row.reasoningMode.description": "Choose how model reasoning is displayed in the timeline",
"settings.general.row.reasoningMode.hidden": "Hidden",
"settings.general.row.reasoningMode.compact": "Compact",
"settings.general.row.reasoningMode.full": "Full",
"settings.general.row.shellToolPartsExpanded.title": "Expand shell tool parts",
"settings.general.row.shellToolPartsExpanded.description":
"Show shell tool parts expanded by default in the timeline",
+12 -2
View File
@@ -5,7 +5,8 @@ import { useFile } from "@/workspaces/files/model"
import { useWorkspaceLocation } from "@/workspaces/location"
import { useData } from "@/runtime/server/current"
import { same } from "@/runtime/persistence/equality"
import { containsDirectory, isWorkspaceDirectory } from "@/workspaces/paths"
import { containsDirectory, isProjectDirectory, isWorkspaceDirectory } from "@/workspaces/paths"
import { projectForSession } from "@/shell/layout/helpers"
import { createSessionTabs } from "./helpers"
import {
normalizeSessionTab,
@@ -90,7 +91,16 @@ export function useSessionModel() {
isDesktop,
workspace: {
directory: createMemo(() => info()?.location.directory ?? location().directory),
current: createMemo(() => isWorkspaceDirectory(project(), info()?.location.directory ?? location().directory)),
current: createMemo(() => {
const current = info()
const directory = current?.location.directory ?? location().directory
// Global sync enriches projects with discovered worktrees; raw project metadata does not.
const projects = server.ctx.sync.data.project
const value = current
? projectForSession(current, projects)
: projects.find((item) => isProjectDirectory(item, directory))
return isWorkspaceDirectory(value, directory)
}),
},
identity: {
params: layout.params,
+52 -2
View File
@@ -1,9 +1,15 @@
import { ErrorBoundary, createEffect, createMemo, Show, type ParentProps } from "solid-js"
import { useParams } from "@solidjs/router"
import { DataProvider } from "@opencode-ai/session-ui/context"
import { SessionUserMessage } from "@opencode-ai/session-ui/message"
import { TextShimmer } from "@opencode-ai/ui/text-shimmer"
import { CommentsProvider } from "@/composer/comments"
import { readPromptPresentation } from "@/composer/comment-note"
import { FileProvider } from "@/workspaces/files/model"
import { LocationProvider } from "@/workspaces/location"
import { ModelsProvider } from "@/providers/models/models"
import { useProviders } from "@/providers/catalog/providers"
import { useLanguage } from "@/runtime/i18n/language"
import { useNotification } from "@/shell/notifications/notification"
import { ComposerPersistenceProvider } from "@/composer/persistence"
import { useData, useServer } from "@/runtime/server/current"
@@ -11,7 +17,7 @@ import { ServerConnection } from "@/runtime/server/registry"
import { TerminalProvider } from "@/session/terminal/context"
import { useSettingsCommand } from "@/settings/command"
import { SessionUIProvider } from "@/shell/routes/session-ui-provider"
import { useTabs } from "@/shell/tabs/tabs"
import { useTabs, type PendingSession } from "@/shell/tabs/tabs"
import { requireServerKey } from "@/shell/routes/session"
import { useSessionModel } from "./model"
import { SessionPanelFrame } from "./session-frame"
@@ -24,6 +30,8 @@ import { SessionScreen } from "./screen"
export function TargetSessionRouteContent() {
const params = useParams<{ serverKey: string; id: string }>()
const data = useData()
const server = useServer()
const tabs = useTabs()
const directory = createMemo(() => data.session.get(params.id)?.location.directory)
return (
@@ -32,13 +40,55 @@ export function TargetSessionRouteContent() {
<ModelsProvider directory={directory}>
<TargetSessionSettingsCommand />
<SessionRouteErrorBoundary sessionID={params.id} serverKey={requireServerKey(params.serverKey)}>
<ResolvedTargetSessionRoute />
<Show when={tabs.pendingSession(server.key, params.id)} fallback={<ResolvedTargetSessionRoute />}>
{(pending) => <PreparingSession sessionID={params.id} pending={pending()} />}
</Show>
</SessionRouteErrorBoundary>
</ModelsProvider>
</>
)
}
function PreparingSession(props: { sessionID: string; pending: PendingSession }) {
const language = useLanguage()
const providers = useProviders(() => props.pending.draft.directory)
return (
<SessionStatePanel>
<DataProvider
directory={props.pending.draft.directory}
data={{
session: [],
session_status: {},
session_diff: {},
provider: { all: providers.all(), default: providers.default(), connected: [] },
}}
>
<div data-component="session-preparing" class="min-h-0 flex-1 overflow-y-auto">
<div class="mx-auto w-full min-w-0 max-w-[1000px] px-4 pt-5 pb-5 md:px-5">
<SessionUserMessage
sessionID={props.sessionID}
message={props.pending.message}
comments={readPromptPresentation(props.pending.message.metadata)?.comments}
historicalAgent={props.pending.selection.agent}
historicalModel={{
id: props.pending.selection.model.modelID,
providerID: props.pending.selection.model.providerID,
variant: props.pending.selection.variant,
}}
/>
<div
role="status"
class="mt-3 flex min-h-6 items-center text-[13px] font-medium leading-[var(--line-height-compact)] text-v2-text-text-muted"
>
<TextShimmer text={language.t("session.new.worktree.creating")} active />
</div>
</div>
</div>
</DataProvider>
</SessionStatePanel>
)
}
function TargetSessionSettingsCommand() {
useSettingsCommand()
return null
@@ -49,7 +49,7 @@ describe("visibleTimelineMessages", () => {
time: { created: 5, completed: 6 },
} satisfies SessionMessageInfo
test("keeps work and thinking above an undelivered steer", () => {
test("keeps work above an undelivered steer without adding a thinking row", () => {
const source = [...messages.slice(0, 3), work]
const visible = visibleTimelineMessages(source, [steer])
expect(visible.map((message) => message.id)).toEqual(["msg_1", "msg_2", "msg_5", "msg_3"])
@@ -60,7 +60,7 @@ describe("visibleTimelineMessages", () => {
const projection = createTimelineProjection({
sessionMessages: () => visible,
status: () => ({ type: "busy" }),
showReasoningSummaries: () => false,
reasoningMode: () => "compact",
shellToolDefaultOpen: () => false,
editToolDefaultOpen: () => false,
pendingUserMessageIDs: () => new Set([steer.id]),
@@ -69,7 +69,6 @@ describe("visibleTimelineMessages", () => {
expect(projection.rows().map((row) => [row._tag, row.userMessageID])).toEqual([
["UserMessage", "msg_1"],
["AssistantPart", "msg_1"],
["Thinking", "msg_1"],
["TurnGap", "msg_3"],
["UserMessage", "msg_3"],
])
@@ -104,7 +104,7 @@ export function createTimelineController(input: { session: TimelineSessionSource
const projection = createTimelineProjection({
sessionMessages: projectedMessages,
status: input.session.data.status,
showReasoningSummaries: settings.general.showReasoningSummaries,
reasoningMode: settings.general.reasoningMode,
shellToolDefaultOpen: settings.general.shellToolPartsExpanded,
editToolDefaultOpen: settings.general.editToolPartsExpanded,
pendingUserMessageIDs,
@@ -235,7 +235,7 @@ export function createTimelineController(input: { session: TimelineSessionSource
childTitle,
showHeader,
projection,
showReasoningSummaries: settings.general.showReasoningSummaries,
reasoningMode: settings.general.reasoningMode,
shellToolPartsExpanded: settings.general.shellToolPartsExpanded,
editToolPartsExpanded: settings.general.editToolPartsExpanded,
},
@@ -349,8 +349,7 @@ function MessageTimelineView(
: projects.find((item) => containsDirectory(item.worktree, sessionDirectory()))
})
const workspaceSession = createMemo(() => isWorkspaceDirectory(project(), sessionDirectory()))
const showProjectIcon = () =>
import.meta.env.VITE_OPENCODE_CHANNEL !== "prod" && settings.general.showProjectIcon()
const showProjectIcon = () => import.meta.env.VITE_OPENCODE_CHANNEL !== "prod" && settings.general.showProjectIcon()
const avatarProject = createMemo(() => {
if (!showProjectIcon()) return
const session = props.session.data.info()
@@ -459,7 +458,7 @@ function MessageTimelineView(
}
},
actions: props.actions,
showReasoningSummaries: props.data.showReasoningSummaries,
reasoningMode: props.data.reasoningMode,
shellToolDefaultOpen: props.data.shellToolPartsExpanded,
editToolDefaultOpen: props.data.editToolPartsExpanded,
disclosure: virtualized.disclosure,
@@ -469,18 +468,19 @@ function MessageTimelineView(
})
const backgroundHintPartID = createMemo(() => {
const blocking = new Set(props.background.blocking().map((task) => task.partID))
const row = projection
if (blocking.size === 0) return
return projection
.rows()
.findLast(
(row) => row._tag === "AssistantPart" && row.group.type === "part" && blocking.has(row.group.ref.partID),
.flatMap((row) =>
row._tag === "AssistantPart" ? (row.group.type === "part" ? [row.group.ref] : row.group.refs) : [],
)
if (row?._tag !== "AssistantPart" || row.group.type !== "part") return
return row.group.ref.partID
.findLast((ref) => blocking.has(ref.partID))?.partID
})
const [backgroundHintRef, setBackgroundHintRef] = createSignal<HTMLDivElement>()
const backgroundHintPresence = createAnimatedPresence(backgroundHintPartID, () => backgroundHintRef() ?? null)
return (
<VirtualizedTimeline
workspaceSession={workspaceSession}
bottomSpacer={
<Show when={backgroundHintPresence.present()}>
<div
@@ -1,5 +1,10 @@
import type { ModelRef, SessionMessageInfo, SessionStatus } from "@opencode-ai/client/promise"
import { reuseTimelineRows, Timeline, TimelineRow } from "@opencode-ai/session-ui/timeline/projection"
import {
reuseTimelineRows,
Timeline,
TimelineRow,
type ReasoningMode,
} from "@opencode-ai/session-ui/timeline/projection"
import { createMemo, type Accessor } from "solid-js"
export { reuseTimelineRows } from "@opencode-ai/session-ui/timeline/projection"
@@ -7,7 +12,7 @@ export { reuseTimelineRows } from "@opencode-ai/session-ui/timeline/projection"
export function createTimelineProjection(input: {
sessionMessages: Accessor<SessionMessageInfo[]>
status: Accessor<SessionStatus>
showReasoningSummaries: Accessor<boolean>
reasoningMode: Accessor<ReasoningMode>
shellToolDefaultOpen: Accessor<boolean>
editToolDefaultOpen: Accessor<boolean>
pendingUserMessageIDs: Accessor<ReadonlySet<string>>
@@ -80,7 +85,7 @@ export function createTimelineProjection(input: {
const projection = createMemo(() =>
Timeline.constructSessionMessageRows(
input.sessionMessages(),
input.showReasoningSummaries(),
input.reasoningMode() !== "hidden",
input.status(),
input.pendingUserMessageIDs(),
input.shellToolDefaultOpen(),
@@ -62,6 +62,7 @@ type Input = {
type ViewProps = {
header: JSX.Element
bottomSpacer?: JSX.Element
workspaceSession: Accessor<boolean>
deferred: (row: TimelineRow.TimelineRow) => boolean
renderRow: (row: Accessor<TimelineRow.TimelineRow>, onSizeChange?: () => void) => JSX.Element
}
@@ -400,7 +401,7 @@ export function createTimelineVirtualizer(input: Input) {
}
return (
<div class="relative w-full h-full min-w-0">
<div class="relative w-full h-full min-w-0" data-workspace-session={props.workspaceSession() ? "" : undefined}>
<div
class="absolute left-1/2 -translate-x-1/2 z-[60] pointer-events-none transition-all duration-200 ease-out"
classList={{
+30 -11
View File
@@ -4,6 +4,7 @@ import { Button } from "@opencode-ai/ui/button"
import { Select } from "@opencode-ai/ui/select"
import { Switch } from "@opencode-ai/ui/switch"
import { TextInput } from "@opencode-ai/ui/text-input"
import type { ReasoningMode } from "@opencode-ai/session-ui/timeline/projection"
import { useLanguage } from "@/runtime/i18n/language"
import { usePlatform } from "@/runtime/platform/platform"
import { useUpdaterAction } from "@/shell/updates/action"
@@ -183,6 +184,34 @@ const FollowUpBehaviorSetting: Component = () => {
)
}
const ReasoningModeSetting: Component = () => {
const language = useLanguage()
const settings = useSettings()
const options = createMemo((): { value: ReasoningMode; label: string }[] => [
{ value: "hidden", label: language.t("settings.general.row.reasoningMode.hidden") },
{ value: "compact", label: language.t("settings.general.row.reasoningMode.compact") },
{ value: "full", label: language.t("settings.general.row.reasoningMode.full") },
])
return (
<SettingsRow
title={language.t("settings.general.row.reasoningMode.title")}
description={language.t("settings.general.row.reasoningMode.description")}
>
<Select
data-action="settings-reasoning-mode"
options={options()}
current={options().find((option) => option.value === settings.general.reasoningMode())}
value={(option) => option.value}
label={(option) => option.label}
placement="bottom-end"
gutter={6}
onSelect={(option) => option && settings.general.setReasoningMode(option.value)}
/>
</SettingsRow>
)
}
const AppearanceSection: Component<{ controller: AppearanceSettingsController }> = (props) => {
const language = useLanguage()
return (
@@ -331,17 +360,7 @@ export const SettingsGeneral: Component<{
<TerminalPlacementSetting />
<FollowUpBehaviorSetting />
<SettingsRow
title={language.t("settings.general.row.reasoningSummaries.title")}
description={language.t("settings.general.row.reasoningSummaries.description")}
>
<div data-action="settings-feed-reasoning-summaries">
<Switch
checked={settings.general.showReasoningSummaries()}
onChange={(checked) => settings.general.setShowReasoningSummaries(checked)}
/>
</div>
</SettingsRow>
<ReasoningModeSetting />
<SettingsRow
title={language.t("settings.general.row.shellToolPartsExpanded.title")}
+29 -1
View File
@@ -1,5 +1,33 @@
import { describe, expect, test } from "bun:test"
import { monoDefault, monoFontFamily, sansDefault, sansFontFamily, terminalFontFamily } from "./model"
import { migrateSettings, monoDefault, monoFontFamily, sansDefault, sansFontFamily, terminalFontFamily } from "./model"
describe("settings reasoning mode migration", () => {
test.each([
[true, "full"],
[false, "compact"],
])("maps persisted reasoning summaries %s to %s", (showReasoningSummaries, reasoningMode) => {
const value = { general: { showReasoningSummaries, showTerminal: true }, appearance: { fontSize: 16 } }
expect(migrateSettings(value)).toEqual({
...value,
general: { ...value.general, reasoningMode },
})
expect(value.general).not.toHaveProperty("reasoningMode")
})
test.each(["hidden", "compact", "full"])(
"preserves an explicit %s mode over either legacy value",
(reasoningMode) => {
;[true, false].forEach((showReasoningSummaries) => {
const value = { general: { reasoningMode, showReasoningSummaries } }
expect(migrateSettings(value)).toBe(value)
})
},
)
test.each([undefined, null, {}, { general: {} }])("leaves missing legacy settings to the defaults: %j", (value) => {
expect(migrateSettings(value)).toBe(value)
})
})
describe("settings font families", () => {
test("defaults normal text to Inter", () => {
+22 -9
View File
@@ -1,6 +1,7 @@
import { createStore, reconcile } from "solid-js/store"
import { createEffect, createMemo } from "solid-js"
import { createSimpleContext } from "@opencode-ai/ui/context"
import type { ReasoningMode } from "@opencode-ai/session-ui/timeline/projection"
import { persisted } from "@/runtime/persistence/storage"
import { ScopedKey, type ServerScope } from "@/runtime/server/scope"
@@ -35,7 +36,7 @@ export interface Settings {
showStatus: boolean
showProjectIcon: boolean
showTerminal: boolean
showReasoningSummaries: boolean
reasoningMode: ReasoningMode
shellToolPartsExpanded: boolean
editToolPartsExpanded: boolean
showCustomAgents: boolean
@@ -124,7 +125,7 @@ const defaultSettings: Settings = {
showStatus: false,
showProjectIcon: false,
showTerminal: false,
showReasoningSummaries: false,
reasoningMode: "compact",
shellToolPartsExpanded: false,
editToolPartsExpanded: false,
showCustomAgents: false,
@@ -166,11 +167,26 @@ function withFallback<T>(read: () => T | undefined, fallback: T) {
return createMemo(() => read() ?? fallback)
}
export function migrateSettings(value: unknown) {
if (!value || typeof value !== "object" || !("general" in value)) return value
const general = value.general
if (!general || typeof general !== "object") return value
if ("reasoningMode" in general && general.reasoningMode !== undefined) return value
if (!("showReasoningSummaries" in general) || typeof general.showReasoningSummaries !== "boolean") return value
return {
...value,
general: { ...general, reasoningMode: general.showReasoningSummaries ? "full" : "compact" },
}
}
export const { use: useSettings, provider: SettingsProvider } = createSimpleContext({
name: "Settings",
gate: false,
init: () => {
const [store, setStore, , ready] = persisted("settings.v3", createStore<Settings>(defaultSettings))
const [store, setStore, , ready] = persisted(
{ key: "settings.v3", migrate: migrateSettings },
createStore<Settings>(defaultSettings),
)
const showFileTree = withFallback(() => store.general?.showFileTree, defaultSettings.general.showFileTree)
const showSearch = withFallback(() => store.general?.showSearch, defaultSettings.general.showSearch)
const showStatus = withFallback(() => store.general?.showStatus, defaultSettings.general.showStatus)
@@ -223,12 +239,9 @@ export const { use: useSettings, provider: SettingsProvider } = createSimpleCont
setShowTerminal(value: boolean) {
setStore("general", "showTerminal", value)
},
showReasoningSummaries: withFallback(
() => store.general?.showReasoningSummaries,
defaultSettings.general.showReasoningSummaries,
),
setShowReasoningSummaries(value: boolean) {
setStore("general", "showReasoningSummaries", value)
reasoningMode: withFallback(() => store.general?.reasoningMode, defaultSettings.general.reasoningMode),
setReasoningMode(value: ReasoningMode) {
setStore("general", "reasoningMode", value)
},
shellToolPartsExpanded: withFallback(
() => store.general?.shellToolPartsExpanded,
+16
View File
@@ -54,10 +54,26 @@
.settings-nav {
display: flex;
width: 200px;
flex-shrink: 0;
flex-direction: column;
gap: 16px;
}
.settings-nav-footer {
display: flex;
flex-shrink: 0;
flex-direction: column;
gap: 8px;
margin-top: auto;
padding-block: 20px 4px;
padding-inline-start: 4px;
font-size: 11px;
font-weight: 440;
line-height: var(--line-height-tight);
color: var(--v2-text-text-faint);
user-select: none;
}
.settings-back {
display: flex;
height: 28px;
+8
View File
@@ -2,6 +2,7 @@ import { Component, createEffect, createMemo, createSignal, onCleanup, onMount,
import { Tabs } from "@opencode-ai/ui/tabs"
import { Icon } from "@opencode-ai/ui/icon"
import { useLanguage } from "@/runtime/i18n/language"
import { usePlatform } from "@/runtime/platform/platform"
import { SettingsGeneral } from "./general/general"
import { SettingsAppearance } from "./appearance/appearance"
import { SettingsKeybinds } from "./keybinds/keybinds"
@@ -26,6 +27,7 @@ export const SettingsScreen: Component<{
defaultValue?: string
}> = (props) => {
const language = useLanguage()
const platform = usePlatform()
const dialog = useDialog()
const command = useCommand()
const surface = useSettingsSurface()
@@ -161,6 +163,12 @@ export const SettingsScreen: Component<{
</div>
</div>
</div>
<div class="settings-nav-footer">
<span>{language.t("app.name.desktop")}</span>
<span>
<bdi dir="ltr">v{platform.version}</bdi>
</span>
</div>
</Tabs.List>
<Tabs.Content value="general" class="settings-panel">
@@ -55,6 +55,7 @@ export function SessionUIProvider(
data={sessionUIData()}
directory={directory()}
sessionID={params.id}
shellRunning={(id) => !!data.shell.get(id)}
shellOutput={(input) => serverSDK.api.shell.output(input)}
onNavigateToSession={navigateToSession}
onSessionHref={href}
+2 -1
View File
@@ -79,7 +79,8 @@ export default function Layout(props: ParentProps) {
/>
</aside>
</Show>
<main class="flex-1 min-h-0 min-w-0 overflow-x-hidden flex flex-col items-start contain-strict">
{/* Size containment collapses percentage-height descendants in WebKit. */}
<main class="flex-1 min-h-0 min-w-0 overflow-x-hidden flex flex-col items-start contain-content">
<div
class="flex size-full min-h-0 min-w-0 flex-col"
hidden={settings.store.open}
+77 -1
View File
@@ -1,4 +1,5 @@
import type { SessionInfo } from "@opencode-ai/client/promise"
import type { SessionInfo, SessionMessageUser } from "@opencode-ai/client/promise"
import type { ComposerSelection } from "@/composer/adapter"
import { createSimpleContext } from "@opencode-ai/ui/context"
import { createStore, produce } from "solid-js/store"
import { Persist, persisted, removePersisted, draftPersistedKeys } from "@/runtime/persistence/storage"
@@ -34,6 +35,12 @@ export type DraftTab = {
export type Tab = SessionTab | DraftTab
export type PendingSession = {
draft: DraftTab
message: SessionMessageUser
selection: ComposerSelection
}
export type TabInfo = {
title?: string
directory?: string
@@ -83,6 +90,7 @@ export const { use: useTabs, provider: TabsProvider } = createSimpleContext({
createStore<Record<string, TabInfo>>({}),
)
const [closed, setClosed, , closedReady] = persisted(Persist.window("tabs.closed"), createStore<ClosedTab[]>([]))
const [pending, setPending] = createStore<Record<string, PendingSession | undefined>>({})
const params = useParams()
const navigate = useNavigate()
@@ -271,6 +279,74 @@ export const { use: useTabs, provider: TabsProvider } = createSimpleContext({
memory.remove(`draft:${draftID}`)
removeDraftPersisted(draftID)
},
pendingSession(server: ServerConnection.Key, sessionID: string): PendingSession | undefined {
return pending[tabKey({ type: "session", server, sessionId: sessionID })]
},
prepareSession(
draftID: string,
session: Omit<SessionTab, "type">,
preview: { message: SessionMessageUser; selection: ComposerSelection },
) {
// Snapshot the draft before replacing its store entry; keep its composer alive for rollback.
const draft = { ...actions.draft(draftID) }
const next = { type: "session" as const, ...session }
const key = tabKey(next)
const ready = startTransition(() => {
setPending(key, { draft, ...preview })
const index = store.findIndex((tab) => tab.type === "draft" && tab.draftID === draftID)
if (index === -1) return
const active = location.pathname === "/new-session" && location.query.draftId === draftID
setStore(
produce((tabs) => {
tabs[index] = next
}),
)
if (recentKey() === tabKey(draft)) setRecentKey(key)
if (active) navigateTab(next)
})
return {
ready,
async complete() {
await ready
if (!pending[key]) return
await startTransition(() => setPending(key, undefined))
memory.remove(tabKey(draft))
removeDraftPersisted(draftID)
},
async rollback(worktree?: string) {
await ready
if (!pending[key]) return
await startTransition(() => {
const index = store.findIndex((tab) => tabKey(tab) === key)
if (index !== -1) {
const restored = worktree === undefined ? draft : { ...draft, worktree, branch: undefined }
const route = currentRoute()
setStore(
produce((tabs) => {
tabs[index] = restored
}),
)
if (recentKey() === key) setRecentKey(tabKey(restored))
if (
route.type === "session" &&
route.server === session.server &&
route.sessionId === session.sessionId
) {
navigateTab(restored)
}
}
setPending(key, undefined)
})
updateClosed((stack) => removeClosedTabs(stack, session.server, [session.sessionId]))
memory.remove(key)
removeInfo(key)
if (store.some((tab) => tab.type === "draft" && tab.draftID === draftID)) return
memory.remove(tabKey(draft))
removeDraftPersisted(draftID)
},
}
},
removeTab,
// User-initiated close: records the tab so it can be reopened.
// Cleanup paths (missing sessions, archive, server removal) go through
+10 -4
View File
@@ -92,10 +92,12 @@ function SessionTabEntry(props: {
const tabs = useTabs()
const language = useLanguage()
const sdk = createMemo(() => props.serverCtx?.sdk ?? null)
const pending = createMemo(() => tabs.pendingSession(props.tab.server, props.tab.sessionId))
const cachedSession = createMemo(() => props.serverCtx?.data.session.get(props.tab.sessionId))
const persisted = createMemo(() => tabs.info[props.id])
const [loadedSession] = createResource(
() => {
if (pending()) return null
const ctx = props.serverCtx
return ctx ? { id: props.tab.sessionId, ctx } : null
},
@@ -105,9 +107,9 @@ function SessionTabEntry(props: {
.then(() => ctx.data.session.get(id))
.catch(() => undefined),
)
const session = createMemo(() => cachedSession() ?? loadedSession())
const missingSession = createMemo(() => !!props.serverCtx && !loadedSession.loading && !session())
const visible = createMemo(() => !!session() || missingSession() || !!persisted()?.title)
const session = createMemo(() => (pending() ? undefined : (cachedSession() ?? loadedSession())))
const missingSession = createMemo(() => !pending() && !!props.serverCtx && !loadedSession.loading && !session())
const visible = createMemo(() => !!pending() || !!session() || missingSession() || !!persisted()?.title)
const rename = async (title: string) => {
const value = session()
@@ -170,7 +172,11 @@ function SessionTabEntry(props: {
forceTruncate={props.forceTruncate}
orientation={props.orientation}
session={session()}
fallbackTitle={persisted()?.title ?? (missingSession() ? language.t("session.tab.unknown") : undefined)}
fallbackTitle={
pending()
? language.t("command.session.new")
: (persisted()?.title ?? (missingSession() ? language.t("session.tab.unknown") : undefined))
}
onRename={rename}
onNavigate={props.onNavigate}
onClose={props.onClose}
@@ -161,6 +161,7 @@ export function Titlebar(props: {
() => {
const route = layout.route()
if (route.type !== "session") return undefined
if (tabs.pendingSession(route.server, route.sessionId)) return undefined
const conn = global.servers.list().find((item) => ServerConnection.key(item) === route.server)
return conn ? { route, ctx: global.ensureServerCtx(conn) } : undefined
},
@@ -169,6 +170,7 @@ export function Titlebar(props: {
const session = createMemo(() => {
const route = layout.route()
if (route.type !== "session") return
if (tabs.pendingSession(route.server, route.sessionId)) return
const conn = global.servers.list().find((item) => ServerConnection.key(item) === route.server)
const cached = conn ? global.ensureServerCtx(conn).data.session.get(route.sessionId) : undefined
if (cached) return cached
@@ -220,6 +222,10 @@ export function Titlebar(props: {
}
if (route.type === "session") {
if (tabs.pendingSession(route.server, route.sessionId)) {
tabsStoreActions.addSessionTab({ server: route.server, sessionId: route.sessionId })
return
}
const s = session()
if (!s) return
const sessionId = s.parentID ?? s.id
@@ -238,6 +244,12 @@ export function Titlebar(props: {
const route = layout.route()
switch (route.type) {
case "session": {
const pending = tabs.pendingSession(route.server, route.sessionId)
if (pending) {
const model = tabs.stateValue<ComposerState>(pending.draft, "prompt")?.model.current()
void tabs.newDraft({ server: route.server, directory: pending.draft.directory }, "", model)
return
}
const activeSession = session()
if (!activeSession) return
+6 -54
View File
@@ -1,7 +1,9 @@
import { sentryVitePlugin } from "@sentry/vite-plugin"
import { fileURLToPath } from "node:url"
import { defineConfig } from "vite"
import { VitePWA } from "vite-plugin-pwa"
import desktopPlugin from "./vite.js"
import desktopPlugin, { channel } from "./vite.js"
import { icons } from "./vite.icons"
import { serviceWorker } from "./vite.pwa"
const sentry =
process.env.SENTRY_AUTH_TOKEN && process.env.SENTRY_ORG && process.env.SENTRY_PROJECT
@@ -23,58 +25,8 @@ const sentry =
export default defineConfig({
plugins: [
desktopPlugin,
VitePWA({
strategies: "generateSW",
registerType: "prompt",
injectRegister: false,
manifest: false,
workbox: {
clientsClaim: false,
skipWaiting: true,
inlineWorkboxRuntime: true,
// Always fetch the current HTML. Precaching a partial build can strand it without its chunks after an upgrade.
navigateFallback: null,
globPatterns: [],
runtimeCaching: [
{
urlPattern: ({ url }) =>
url.origin === self.location.origin &&
(url.pathname.startsWith("/_assets/") || url.pathname.startsWith("/assets/")),
handler: "CacheFirst",
options: {
cacheName: "opencode-assets",
plugins: [
{
cachedResponseWillBeUsed: async ({ request, cachedResponse }) => {
if (
cachedResponse?.status === 200 &&
!/^(text\/html|application\/xhtml\+xml)\b/i.test(cachedResponse.headers.get("content-type") ?? "")
)
return cachedResponse
// Keep old tabs' precached chunks usable without retaining their stale HTML navigation handler.
const response = await caches.match(request, {
cacheName: `workbox-precache-v2-${self.location.origin}/`,
})
return response?.status === 200 &&
!/^(text\/html|application\/xhtml\+xml)\b/i.test(response.headers.get("content-type") ?? "")
? response
: null
},
cacheWillUpdate: async ({ response }) =>
response.status === 200 &&
!/^(text\/html|application\/xhtml\+xml)\b/i.test(response.headers.get("content-type") ?? "")
? response
: null,
},
],
expiration: {
maxEntries: 1000,
},
},
},
],
},
}),
icons(channel),
serviceWorker(fileURLToPath(new URL("./dist", import.meta.url))),
sentry,
] as any,
server: {
+86
View File
@@ -0,0 +1,86 @@
import { expect, test } from "bun:test"
import { fetch } from "bun"
import { build, createServer } from "vite"
import { icons } from "./vite.icons"
import manifest from "./manifest.json" with { type: "json" }
test.each(["dev", "beta", "prod", "local"])("bundles %s app icons", async (channel) => {
const result = await build({
root: import.meta.dirname,
configFile: false,
logLevel: "silent",
plugins: [
icons(channel),
{
name: "icons-only-fixture",
transformIndexHtml: {
order: "pre",
handler: (html) => html.replace(/<script\b[^>]*>[\s\S]*?<\/script>/g, ""),
},
},
],
build: { write: false, copyPublicDir: false },
})
if (!("output" in result)) throw new Error("Expected a single build output")
await check(channel === "local" ? "dev" : channel, async (path) => {
const file = result.output.find((file) => `/${file.fileName}` === path)
if (file?.type !== "asset") throw new Error(`Missing asset: ${path}`)
return typeof file.source === "string" ? new TextEncoder().encode(file.source) : file.source
})
})
test.each(["dev", "beta", "prod"])("serves %s app icons", async (channel) => {
const server = await createServer({
root: import.meta.dirname,
configFile: false,
logLevel: "silent",
plugins: [icons(channel)],
optimizeDeps: { noDiscovery: true, include: [] },
server: { host: "127.0.0.1", port: 0, hmr: false, preTransformRequests: false, watch: null },
})
try {
await server.listen()
const address = server.httpServer?.address()
if (!address || typeof address === "string") throw new Error("Expected an HTTP port")
await check(channel, async (path) => {
const response = await fetch(`http://127.0.0.1:${address.port}${path}`)
expect(response.status).toBe(200)
if (path.endsWith(".webmanifest")) expect(response.headers.get("content-type")).toBe("application/manifest+json")
if (path.endsWith(".png")) expect(response.headers.get("content-type")).toBe("image/png")
return new Uint8Array(await response.arrayBuffer())
})
} finally {
await server.close()
}
})
async function check(channel: string, read: (path: string) => Promise<Uint8Array>) {
const html = new TextDecoder().decode(await read("/index.html"))
const actual: typeof manifest = JSON.parse(new TextDecoder().decode(await read("/site.webmanifest")))
expect(actual).toEqual({
...manifest,
icons: manifest.icons.map((icon) => ({ ...icon, src: `/icons/${channel}${icon.src}` })),
})
expect(html).toContain(`href="/icons/${channel}/favicon.ico"`)
expect(html).toContain(`href="/icons/${channel}/apple-touch-icon.png"`)
expect(html).toContain(`href="/site.webmanifest"`)
expect(html).not.toContain("%OPENCODE_")
await Promise.all(
Object.entries({
"favicon.ico": "icon.ico",
"apple-touch-icon.png": "ios/AppIcon-60x60@3x.png",
"web-app-manifest-192x192.png": "android/mipmap-xxxhdpi/ic_launcher.png",
"web-app-manifest-512x512.png": "icon.png",
}).map(async ([name, source]) => {
const bytes = await read(`/icons/${channel}/${name}`)
expect(bytes).toEqual(await Bun.file(new URL(`../desktop/icons/${channel}/${source}`, import.meta.url)).bytes())
if (!name.endsWith(".png")) return
const size = name === "apple-touch-icon.png" ? 180 : Number(name.match(/(192|512)/)?.[0])
expect(new DataView(bytes.buffer, bytes.byteOffset).getUint32(16)).toBe(size)
expect(new DataView(bytes.buffer, bytes.byteOffset).getUint32(20)).toBe(size)
}),
)
}
+51
View File
@@ -0,0 +1,51 @@
import { readFileSync } from "node:fs"
import type { Plugin } from "vite"
import manifest from "./manifest.json" with { type: "json" }
export function icons(channel: string): Plugin {
const selected = channel === "beta" || channel === "prod" ? channel : "dev"
const prefix = `icons/${selected}`
const files = [
...Object.entries({
"favicon.ico": "icon.ico",
"apple-touch-icon.png": "ios/AppIcon-60x60@3x.png",
"web-app-manifest-192x192.png": "android/mipmap-xxxhdpi/ic_launcher.png",
"web-app-manifest-512x512.png": "icon.png",
}).map(([name, source]) => ({
fileName: `${prefix}/${name}`,
source: readFileSync(new URL(`../desktop/icons/${selected}/${source}`, import.meta.url)),
type: name.endsWith(".ico") ? "image/x-icon" : "image/png",
})),
{
fileName: "site.webmanifest",
source: JSON.stringify({
...manifest,
icons: manifest.icons.map((icon) => ({ ...icon, src: `/${prefix}${icon.src}` })),
}),
type: "application/manifest+json",
},
]
return {
name: "opencode-app:icons",
generateBundle() {
files.forEach((file) => this.emitFile({ type: "asset", fileName: file.fileName, source: file.source }))
},
configureServer(server) {
server.middlewares.use((request, response, next) => {
const file = files.find((file) => `/${file.fileName}` === request.url?.split("?")[0])
if (!file) return next()
response.setHeader("Content-Type", file.type)
response.end(file.source)
})
},
transformIndexHtml: {
order: "pre",
handler(html) {
return html
.replace("%OPENCODE_FAVICON%", `/${prefix}/favicon.ico`)
.replace("%OPENCODE_APPLE_TOUCH_ICON%", `/${prefix}/apple-touch-icon.png`)
},
},
}
}
+1 -1
View File
@@ -17,7 +17,7 @@ if (tailwindGenerate && typeof tailwindHotUpdate === "function") {
}
}
const channel = (() => {
export const channel = (() => {
const raw = process.env.OPENCODE_CHANNEL
if (raw === "local" || raw === "dev" || raw === "beta" || raw === "prod") return raw
if (process.env.OPENCODE_CHANNEL === "latest") return "prod"
+41
View File
@@ -0,0 +1,41 @@
import { createHash } from "node:crypto"
import { readFile } from "node:fs/promises"
import { resolve } from "node:path"
import { VitePWA } from "vite-plugin-pwa"
export function serviceWorker(directory: string) {
return VitePWA({
strategies: "generateSW",
registerType: "prompt",
injectRegister: false,
manifest: false,
workbox: {
globDirectory: directory,
clientsClaim: false,
// Keep each open tab on its complete build until all old clients close.
skipWaiting: false,
inlineWorkboxRuntime: true,
navigateFallback: "/index.html",
navigateFallbackDenylist: [/^\/api(?:\/|$)/, /^\/(?:_assets|assets)(?:\/|$)/],
// Include lazy chunks and non-JS dependencies, not just the startup bundle.
globPatterns: ["**/*"],
globIgnores: ["**/*.map", "_headers", "_redirects"],
maximumFileSizeToCacheInBytes: Number.MAX_SAFE_INTEGER,
manifestTransforms: [
async (entries) => ({
manifest: await Promise.all(
entries.map(async (entry) => ({
...entry,
// A revision labels a cache entry; integrity rejects mixed deployments
// and HTML fallback responses instead of installing a broken build.
integrity: `sha256-${createHash("sha256")
.update(await readFile(resolve(directory, entry.url)))
.digest("base64")}`,
})),
),
warnings: [],
}),
],
},
})
}
+247 -295
View File
@@ -6,6 +6,7 @@ import { expect, test } from "bun:test"
import { parse } from "jsonc-parser"
import path from "path"
import { Config } from "../src/config"
import { tmpdir } from "./fixture/tmpdir"
function run<A, E>(directory: string, effect: Effect.Effect<A, E, Config.Service>) {
return Effect.runPromise(
@@ -35,53 +36,45 @@ test("generates reusable keybind schemas and preserves descriptions and numeric
})
test("includes the published schema when creating cli.json", async () => {
const directory = await Bun.$`mktemp -d`.text().then((value) => value.trim())
await using directory = await tmpdir()
try {
const config = await run(
directory,
Effect.gen(function* () {
const service = yield* Config.Service
return yield* service.update((draft) => {
draft.animations = false
})
}),
)
const config = await run(
directory.path,
Effect.gen(function* () {
const service = yield* Config.Service
return yield* service.update((draft) => {
draft.animations = false
})
}),
)
expect(config).toEqual({ $schema: "https://opencode.ai/v2/cli.json", animations: false })
expect(await Bun.file(path.join(directory, "cli.json")).json()).toEqual(config)
} finally {
await Bun.$`rm -rf ${directory}`
}
expect(config).toEqual({ $schema: "https://opencode.ai/v2/cli.json", animations: false })
expect(await Bun.file(path.join(directory.path, "cli.json")).json()).toEqual(config)
})
test("preserves the schema in an existing cli.json", async () => {
const directory = await Bun.$`mktemp -d`.text().then((value) => value.trim())
const file = path.join(directory, "cli.json")
await using directory = await tmpdir()
const file = path.join(directory.path, "cli.json")
await Bun.write(file, JSON.stringify({ $schema: "https://opencode.ai/v2/cli.json", animations: true }))
try {
const config = await run(
directory,
Effect.gen(function* () {
const service = yield* Config.Service
return yield* service.update((draft) => {
draft.animations = false
})
}),
)
const config = await run(
directory.path,
Effect.gen(function* () {
const service = yield* Config.Service
return yield* service.update((draft) => {
draft.animations = false
})
}),
)
expect(config).toEqual({ $schema: "https://opencode.ai/v2/cli.json", animations: false })
expect(await Bun.file(file).json()).toEqual(config)
} finally {
await Bun.$`rm -rf ${directory}`
}
expect(config).toEqual({ $schema: "https://opencode.ai/v2/cli.json", animations: false })
expect(await Bun.file(file).json()).toEqual(config)
})
test("migrates tui and kv config into cli.json", async () => {
const directory = await Bun.$`mktemp -d`.text().then((value) => value.trim())
await using directory = await tmpdir()
await Bun.write(
path.join(directory, "tui.json"),
path.join(directory.path, "tui.json"),
JSON.stringify({
theme: "legacy",
keybinds: {
@@ -102,7 +95,7 @@ test("migrates tui and kv config into cli.json", async () => {
}),
)
await Bun.write(
path.join(directory, "kv.json"),
path.join(directory.path, "kv.json"),
JSON.stringify({
theme_mode_lock: "light",
attention_sound_pack: "custom.pack",
@@ -124,115 +117,108 @@ test("migrates tui and kv config into cli.json", async () => {
}),
)
try {
const config = await run(
directory,
Effect.gen(function* () {
const service = yield* Config.Service
return yield* service.get()
}),
)
const config = await run(
directory.path,
Effect.gen(function* () {
const service = yield* Config.Service
return yield* service.get()
}),
)
expect(config).toMatchObject({
$schema: "https://opencode.ai/v2/cli.json",
theme: { name: "legacy", mode: "light" },
keybinds: {
leader: "ctrl+o",
"app.exit": "ctrl+q",
"prompt.paste": { key: "ctrl+v", preventDefault: false },
"session.delete": false,
"dialog.select.next": "ctrl+n",
},
plugins: [{ package: "example", options: { mode: "safe" } }, "-disabled"],
leader: { timeout: 500 },
scroll: { speed: 2, acceleration: true },
attention: { sound_pack: "custom.pack" },
diffs: { wrap: "none", tree: false, single: true, view: "split" },
terminal: { title: false },
prompt: { editor: false, paste: "full" },
session: { sidebar: "hide", scrollbar: true, thinking: "show", grouping: "none" },
animations: false,
mouse: false,
})
expect(config).not.toHaveProperty("skipped_version")
expect(config).not.toHaveProperty("which_key")
expect(config).not.toHaveProperty("hints")
expect((await Bun.file(path.join(directory, "cli.json")).json()).keybinds).toEqual({
expect(config).toMatchObject({
$schema: "https://opencode.ai/v2/cli.json",
theme: { name: "legacy", mode: "light" },
keybinds: {
leader: "ctrl+o",
"app.exit": "ctrl+q",
"prompt.paste": { key: "ctrl+v", preventDefault: false },
"session.delete": false,
"dialog.select.next": "ctrl+n",
})
expect(await Bun.file(path.join(directory, "cli.json")).exists()).toBe(true)
expect(await Bun.file(path.join(directory, "tui.json")).exists()).toBe(true)
expect(await Bun.file(path.join(directory, "kv.json")).exists()).toBe(true)
} finally {
await Bun.$`rm -rf ${directory}`
}
},
plugins: [{ package: "example", options: { mode: "safe" } }, "-disabled"],
leader: { timeout: 500 },
scroll: { speed: 2, acceleration: true },
attention: { sound_pack: "custom.pack" },
diffs: { wrap: "none", tree: false, single: true, view: "split" },
terminal: { title: false },
prompt: { editor: false, paste: "full" },
session: { sidebar: "hide", scrollbar: true, thinking: "show", grouping: "none" },
animations: false,
mouse: false,
})
expect(config).not.toHaveProperty("skipped_version")
expect(config).not.toHaveProperty("which_key")
expect(config).not.toHaveProperty("hints")
expect((await Bun.file(path.join(directory.path, "cli.json")).json()).keybinds).toEqual({
leader: "ctrl+o",
"app.exit": "ctrl+q",
"prompt.paste": { key: "ctrl+v", preventDefault: false },
"session.delete": false,
"dialog.select.next": "ctrl+n",
})
expect(await Bun.file(path.join(directory.path, "cli.json")).exists()).toBe(true)
expect(await Bun.file(path.join(directory.path, "tui.json")).exists()).toBe(true)
expect(await Bun.file(path.join(directory.path, "kv.json")).exists()).toBe(true)
})
test("migrates before the first update and does not remigrate afterward", async () => {
const directory = await Bun.$`mktemp -d`.text().then((value) => value.trim())
await Bun.write(path.join(directory, "tui.json"), JSON.stringify({ theme: "legacy" }))
await using directory = await tmpdir()
await Bun.write(path.join(directory.path, "tui.json"), JSON.stringify({ theme: "legacy" }))
try {
const config = await run(
directory,
Effect.gen(function* () {
const service = yield* Config.Service
yield* service.update((draft) => {
draft.animations = false
draft.mouse = false
})
yield* Effect.promise(() => Bun.write(path.join(directory, "tui.json"), JSON.stringify({ theme: "changed" })))
return yield* service.get()
}),
)
const config = await run(
directory.path,
Effect.gen(function* () {
const service = yield* Config.Service
yield* service.update((draft) => {
draft.animations = false
draft.mouse = false
})
yield* Effect.promise(() =>
Bun.write(path.join(directory.path, "tui.json"), JSON.stringify({ theme: "changed" })),
)
return yield* service.get()
}),
)
expect(config).toEqual({
$schema: "https://opencode.ai/v2/cli.json",
theme: { name: "legacy" },
animations: false,
mouse: false,
})
expect(await Bun.file(path.join(directory, "cli.json")).json()).toEqual({
$schema: "https://opencode.ai/v2/cli.json",
theme: { name: "legacy" },
animations: false,
mouse: false,
})
} finally {
await Bun.$`rm -rf ${directory}`
}
expect(config).toEqual({
$schema: "https://opencode.ai/v2/cli.json",
theme: { name: "legacy" },
animations: false,
mouse: false,
})
expect(await Bun.file(path.join(directory.path, "cli.json")).json()).toEqual({
$schema: "https://opencode.ai/v2/cli.json",
theme: { name: "legacy" },
animations: false,
mouse: false,
})
})
test("preserves legacy cursor settings", async () => {
const directory = await Bun.$`mktemp -d`.text().then((value) => value.trim())
await Bun.write(path.join(directory, "tui.json"), JSON.stringify({ cursor: { style: "underline", blinking: false } }))
await using directory = await tmpdir()
await Bun.write(
path.join(directory.path, "tui.json"),
JSON.stringify({ cursor: { style: "underline", blinking: false } }),
)
try {
const config = await run(
directory,
Effect.gen(function* () {
const service = yield* Config.Service
return yield* service.get()
}),
)
const config = await run(
directory.path,
Effect.gen(function* () {
const service = yield* Config.Service
return yield* service.get()
}),
)
expect(config.cursor).toEqual({ style: "underline", blinking: false })
expect((await Bun.file(path.join(directory, "cli.json")).json()).cursor).toEqual({
style: "underline",
blinking: false,
})
} finally {
await Bun.$`rm -rf ${directory}`
}
expect(config.cursor).toEqual({ style: "underline", blinking: false })
expect((await Bun.file(path.join(directory.path, "cli.json")).json()).cursor).toEqual({
style: "underline",
blinking: false,
})
})
test("migrates legacy keybind names in an existing cli.json", async () => {
const directory = await Bun.$`mktemp -d`.text().then((value) => value.trim())
const file = path.join(directory, "cli.json")
await using directory = await tmpdir()
const file = path.join(directory.path, "cli.json")
await Bun.write(
file,
`{
@@ -251,31 +237,27 @@ test("migrates legacy keybind names in an existing cli.json", async () => {
`,
)
try {
const config = await run(
directory,
Effect.gen(function* () {
const service = yield* Config.Service
return yield* service.get()
}),
)
const config = await run(
directory.path,
Effect.gen(function* () {
const service = yield* Config.Service
return yield* service.get()
}),
)
expect(config.keybinds).toEqual({
"session.list": "ctrl+l",
"session.delete": "ctrl+x",
})
const text = await Bun.file(file).text()
expect(text).toContain("// Preserve this comment")
expect(text).toContain("// Session list shortcut")
expect(text).toContain("// Legacy delete shortcut")
expect(text).toContain("// Canonical delete shortcut")
expect(parse(text).keybinds).toEqual({
"session.list": "ctrl+l",
"session.delete": "ctrl+x",
})
} finally {
await Bun.$`rm -rf ${directory}`
}
expect(config.keybinds).toEqual({
"session.list": "ctrl+l",
"session.delete": "ctrl+x",
})
const text = await Bun.file(file).text()
expect(text).toContain("// Preserve this comment")
expect(text).toContain("// Session list shortcut")
expect(text).toContain("// Legacy delete shortcut")
expect(text).toContain("// Canonical delete shortcut")
expect(parse(text).keybinds).toEqual({
"session.list": "ctrl+l",
"session.delete": "ctrl+x",
})
})
test("migrates copy_on_select in an existing cli.json", async () => {
@@ -284,8 +266,8 @@ test("migrates copy_on_select in an existing cli.json", async () => {
{ legacy: false, expected: "manual" },
{ legacy: true, copy: "manual", expected: "manual" },
] as const) {
const directory = await Bun.$`mktemp -d`.text().then((value) => value.trim())
const file = path.join(directory, "cli.json")
await using directory = await tmpdir()
const file = path.join(directory.path, "cli.json")
await Bun.write(
file,
`{
@@ -298,29 +280,25 @@ test("migrates copy_on_select in an existing cli.json", async () => {
`,
)
try {
const config = await run(
directory,
Effect.gen(function* () {
const service = yield* Config.Service
return yield* service.get()
}),
)
const config = await run(
directory.path,
Effect.gen(function* () {
const service = yield* Config.Service
return yield* service.get()
}),
)
expect(config.terminal).toEqual({ copy: item.expected })
const text = await Bun.file(file).text()
expect(text).toContain("// Preserve this comment")
expect(text).not.toContain("copy_on_select")
expect(parse(text).terminal).toEqual({ copy: item.expected })
} finally {
await Bun.$`rm -rf ${directory}`
}
expect(config.terminal).toEqual({ copy: item.expected })
const text = await Bun.file(file).text()
expect(text).toContain("// Preserve this comment")
expect(text).not.toContain("copy_on_select")
expect(parse(text).terminal).toEqual({ copy: item.expected })
}
})
test("uses migrated keybinds when persistence fails", async () => {
const directory = await Bun.$`mktemp -d`.text().then((value) => value.trim())
const file = path.join(directory, "cli.json")
await using directory = await tmpdir()
const file = path.join(directory.path, "cli.json")
await Bun.write(file, `{"keybinds":{"session_list":"ctrl+l"}}`)
const node = await Effect.runPromise(FileSystem.FileSystem.pipe(Effect.provide(NodeFileSystem.layer)))
const fs = new Proxy(node, {
@@ -330,88 +308,76 @@ test("uses migrated keybinds when persistence fails", async () => {
},
})
try {
const config = await Effect.runPromise(
Effect.gen(function* () {
const service = yield* Config.Service
return yield* service.get()
}).pipe(
Effect.provide(Config.layer),
Effect.provide(Global.layerWith({ config: directory, state: directory })),
Effect.provideService(FileSystem.FileSystem, fs),
),
)
const config = await Effect.runPromise(
Effect.gen(function* () {
const service = yield* Config.Service
return yield* service.get()
}).pipe(
Effect.provide(Config.layer),
Effect.provide(Global.layerWith({ config: directory.path, state: directory.path })),
Effect.provideService(FileSystem.FileSystem, fs),
),
)
expect(config.keybinds).toEqual({ "session.list": "ctrl+l" })
expect(await Bun.file(file).json()).toEqual({ keybinds: { session_list: "ctrl+l" } })
expect(await Array.fromAsync(new Bun.Glob("*.tmp").scan(directory))).toEqual([])
} finally {
await Bun.$`rm -rf ${directory}`
}
expect(config.keybinds).toEqual({ "session.list": "ctrl+l" })
expect(await Bun.file(file).json()).toEqual({ keybinds: { session_list: "ctrl+l" } })
expect(await Array.fromAsync(new Bun.Glob("*.tmp").scan(directory.path))).toEqual([])
})
test("preserves the effective value when migrating duplicate legacy keybinds", async () => {
const directory = await Bun.$`mktemp -d`.text().then((value) => value.trim())
const file = path.join(directory, "cli.json")
await using directory = await tmpdir()
const file = path.join(directory.path, "cli.json")
await Bun.write(file, `{"keybinds":{"session_delete":"ctrl+a","session_delete":"ctrl+b"}}`)
try {
const config = await run(
directory,
Effect.gen(function* () {
const service = yield* Config.Service
return yield* service.get()
}),
)
const config = await run(
directory.path,
Effect.gen(function* () {
const service = yield* Config.Service
return yield* service.get()
}),
)
expect(config.keybinds).toEqual({ "session.delete": "ctrl+b" })
expect(parse(await Bun.file(file).text()).keybinds).toEqual({ "session.delete": "ctrl+b" })
} finally {
await Bun.$`rm -rf ${directory}`
}
expect(config.keybinds).toEqual({ "session.delete": "ctrl+b" })
expect(parse(await Bun.file(file).text()).keybinds).toEqual({ "session.delete": "ctrl+b" })
})
test("migrates and updates the effective duplicate top-level keybinds", async () => {
const directory = await Bun.$`mktemp -d`.text().then((value) => value.trim())
const file = path.join(directory, "cli.json")
await using directory = await tmpdir()
const file = path.join(directory.path, "cli.json")
await Bun.write(file, `{"keybinds":{"session_delete":"first"},"keybinds":{"session_delete":"last"}}`)
try {
const config = await run(
directory,
Effect.gen(function* () {
const service = yield* Config.Service
expect((yield* service.get()).keybinds).toEqual({ "session.delete": "last" })
return yield* service.update((draft) => {
draft.keybinds = { ...draft.keybinds, "session.delete": "changed" }
})
}),
)
const config = await run(
directory.path,
Effect.gen(function* () {
const service = yield* Config.Service
expect((yield* service.get()).keybinds).toEqual({ "session.delete": "last" })
return yield* service.update((draft) => {
draft.keybinds = { ...draft.keybinds, "session.delete": "changed" }
})
}),
)
expect(config.keybinds).toEqual({ "session.delete": "changed" })
expect(parse(await Bun.file(file).text()).keybinds).toEqual({ "session.delete": "changed" })
} finally {
await Bun.$`rm -rf ${directory}`
}
expect(config.keybinds).toEqual({ "session.delete": "changed" })
expect(parse(await Bun.file(file).text()).keybinds).toEqual({ "session.delete": "changed" })
})
test("serializes migration and updates across processes", async () => {
const directory = await Bun.$`mktemp -d`.text().then((value) => value.trim())
const file = path.join(directory, "cli.json")
const started = path.join(directory, "started")
const release = path.join(directory, "release")
const migrateReady = path.join(directory, "migrate-ready")
const updateReady = path.join(directory, "update-ready")
await using directory = await tmpdir()
const file = path.join(directory.path, "cli.json")
const started = path.join(directory.path, "started")
const release = path.join(directory.path, "release")
const migrateReady = path.join(directory.path, "migrate-ready")
const updateReady = path.join(directory.path, "update-ready")
await Bun.write(file, `{"keybinds":{"session_delete":"ctrl+d"}}`)
const worker = path.join(import.meta.dir, "fixture/config-concurrency.ts")
const migrate = Bun.spawn([process.execPath, worker, "migrate", directory, started, release, migrateReady], {
const migrate = Bun.spawn([process.execPath, worker, "migrate", directory.path, started, release, migrateReady], {
stdout: "ignore",
stderr: "pipe",
})
try {
await waitForFile(started, migrate.exited)
const update = Bun.spawn([process.execPath, worker, "update", directory, started, release, updateReady], {
const update = Bun.spawn([process.execPath, worker, "update", directory.path, started, release, updateReady], {
stdout: "ignore",
stderr: "pipe",
})
@@ -431,21 +397,20 @@ test("serializes migration and updates across processes", async () => {
await Bun.write(release, "")
migrate.kill()
await migrate.exited
await Bun.$`rm -rf ${directory}`
}
})
test("config reads remain interruptible while waiting for the file lock", async () => {
const directory = await Bun.$`mktemp -d`.text().then((value) => value.trim())
const file = path.join(directory, "cli.json")
const locks = path.join(directory, "locks")
await using directory = await tmpdir()
const file = path.join(directory.path, "cli.json")
const locks = path.join(directory.path, "locks")
const held = await Flock.acquire(file, { dir: locks })
try {
const service = await Effect.runPromise(
Config.Service.pipe(
Effect.provide(Config.layer),
Effect.provide(Global.layerWith({ config: directory, state: directory })),
Effect.provide(Global.layerWith({ config: directory.path, state: directory.path })),
Effect.provide(NodeFileSystem.layer),
),
)
@@ -453,43 +418,38 @@ test("config reads remain interruptible while waiting for the file lock", async
expect(await Promise.race([result, Bun.sleep(250).then(() => "blocked" as const)])).toEqual(Option.none())
} finally {
await held.release()
await Bun.$`rm -rf ${directory}`
}
})
test("updates effective duplicate canonical keybinds", async () => {
const directory = await Bun.$`mktemp -d`.text().then((value) => value.trim())
const file = path.join(directory, "cli.json")
await using directory = await tmpdir()
const file = path.join(directory.path, "cli.json")
await Bun.write(
file,
`{"keybinds":{"session.delete":"first","session.delete":"last","permission.mode":"off","permission.mode":"on"}}`,
)
try {
const config = await run(
directory,
Effect.gen(function* () {
const service = yield* Config.Service
expect((yield* service.get()).keybinds).toEqual({ "session.delete": "last", "permission.mode": "on" })
return yield* service.update((draft) => {
draft.keybinds = { ...draft.keybinds, "session.delete": "changed", "permission.mode": "changed" }
})
}),
)
const config = await run(
directory.path,
Effect.gen(function* () {
const service = yield* Config.Service
expect((yield* service.get()).keybinds).toEqual({ "session.delete": "last", "permission.mode": "on" })
return yield* service.update((draft) => {
draft.keybinds = { ...draft.keybinds, "session.delete": "changed", "permission.mode": "changed" }
})
}),
)
expect(config.keybinds).toEqual({ "session.delete": "changed", "permission.mode": "changed" })
expect(parse(await Bun.file(file).text()).keybinds).toEqual({
"session.delete": "changed",
"permission.mode": "changed",
})
} finally {
await Bun.$`rm -rf ${directory}`
}
expect(config.keybinds).toEqual({ "session.delete": "changed", "permission.mode": "changed" })
expect(parse(await Bun.file(file).text()).keybinds).toEqual({
"session.delete": "changed",
"permission.mode": "changed",
})
})
test("removes orphaned keybinds without deleting trailing comments", async () => {
const directory = await Bun.$`mktemp -d`.text().then((value) => value.trim())
const file = path.join(directory, "cli.json")
await using directory = await tmpdir()
const file = path.join(directory.path, "cli.json")
await Bun.write(
file,
`{
@@ -501,50 +461,42 @@ test("removes orphaned keybinds without deleting trailing comments", async () =>
`,
)
try {
const config = await run(
directory,
Effect.gen(function* () {
const service = yield* Config.Service
return yield* service.get()
}),
)
const config = await run(
directory.path,
Effect.gen(function* () {
const service = yield* Config.Service
return yield* service.get()
}),
)
expect(config.keybinds).toEqual({})
const text = await Bun.file(file).text()
expect(text).toContain("/* Keep legacy explanation */")
expect(text).toContain("/* Keep canonical explanation */")
expect(parse(text).keybinds).toEqual({})
} finally {
await Bun.$`rm -rf ${directory}`
}
expect(config.keybinds).toEqual({})
const text = await Bun.file(file).text()
expect(text).toContain("/* Keep legacy explanation */")
expect(text).toContain("/* Keep canonical explanation */")
expect(parse(text).keybinds).toEqual({})
})
test("updates a config draft while preserving JSONC comments", async () => {
const directory = await Bun.$`mktemp -d`.text().then((value) => value.trim())
await Bun.write(path.join(directory, "cli.json"), '{\n // Keep this comment\n "animations": true\n}\n')
await using directory = await tmpdir()
await Bun.write(path.join(directory.path, "cli.json"), '{\n // Keep this comment\n "animations": true\n}\n')
try {
const config = await run(
directory,
Effect.gen(function* () {
const service = yield* Config.Service
return yield* service.update((draft) => {
draft.prompt = { paste: "compact" }
draft.mini = { thinking: "hide", shell_output: "hide", turn_summary: "hide", splash: "hide", mono: true }
})
}),
)
const config = await run(
directory.path,
Effect.gen(function* () {
const service = yield* Config.Service
return yield* service.update((draft) => {
draft.prompt = { paste: "compact" }
draft.mini = { thinking: "hide", shell_output: "hide", turn_summary: "hide", splash: "hide", mono: true }
})
}),
)
expect(config).toEqual({
animations: true,
prompt: { paste: "compact" },
mini: { thinking: "hide", shell_output: "hide", turn_summary: "hide", splash: "hide", mono: true },
})
expect(await Bun.file(path.join(directory, "cli.json")).text()).toContain("// Keep this comment")
} finally {
await Bun.$`rm -rf ${directory}`
}
expect(config).toEqual({
animations: true,
prompt: { paste: "compact" },
mini: { thinking: "hide", shell_output: "hide", turn_summary: "hide", splash: "hide", mono: true },
})
expect(await Bun.file(path.join(directory.path, "cli.json")).text()).toContain("// Keep this comment")
})
async function waitForFile(file: string, exited: Promise<number>) {
+13
View File
@@ -0,0 +1,13 @@
import { mkdtemp, rm } from "node:fs/promises"
import os from "node:os"
import path from "node:path"
export async function tmpdir() {
const directory = await mkdtemp(path.join(os.tmpdir(), "opencode-cli-test-"))
return {
path: directory,
async [Symbol.asyncDispose]() {
await rm(directory, { recursive: true, force: true })
},
}
}
+24 -29
View File
@@ -1,5 +1,4 @@
import { afterEach, describe, expect, test } from "bun:test"
import { mkdtemp, rm } from "node:fs/promises"
import { describe, expect, test } from "bun:test"
import path from "node:path"
import { Readable } from "node:stream"
import { pathToFileURL } from "node:url"
@@ -10,20 +9,14 @@ import {
type InteractiveStdin,
usingInteractiveStdin,
} from "../src/mini-host"
import { tmpdir } from "./fixture/tmpdir"
const temporary: string[] = []
const model = { providerID: "openai", modelID: "gpt-5" }
function stream(isTTY: boolean) {
return Object.assign(new Readable({ read() {} }), { isTTY }) as NodeJS.ReadStream
}
async function root() {
const directory = await mkdtemp(path.join(import.meta.dir, ".mini-host-"))
temporary.push(directory)
return directory
}
function host(terminal: InteractiveStdin, directory: string) {
return createMiniHost({
terminal,
@@ -32,10 +25,6 @@ function host(terminal: InteractiveStdin, directory: string) {
})
}
afterEach(async () => {
await Promise.all(temporary.splice(0).map((directory) => rm(directory, { recursive: true, force: true })))
})
describe("Mini CLI host", () => {
test("reuses tty stdin without taking ownership", () => {
const stdin = stream(true)
@@ -129,30 +118,36 @@ describe("Mini CLI host", () => {
})
test("subscribes and unsubscribes process signals through host capabilities", async () => {
const input = host({ stdin: stream(true), cleanup() {} }, await root())
await using directory = await tmpdir()
const input = host({ stdin: stream(true), cleanup() {} }, directory.path)
const sigint = process.listenerCount("SIGINT")
const sigusr2 = process.listenerCount("SIGUSR2")
const offInt = input.signals.sigint.subscribe(() => {})
const offTheme = input.signals.sigusr2.subscribe(() => {})
expect(process.listenerCount("SIGINT")).toBe(sigint + 1)
expect(process.listenerCount("SIGUSR2")).toBe(sigusr2 + 1)
offInt()
offInt()
offTheme()
offTheme()
expect(process.listenerCount("SIGINT")).toBe(sigint)
expect(process.listenerCount("SIGUSR2")).toBe(sigusr2)
try {
expect(process.listenerCount("SIGINT")).toBe(sigint + 1)
expect(process.listenerCount("SIGUSR2")).toBe(sigusr2 + 1)
offInt()
offInt()
offTheme()
offTheme()
expect(process.listenerCount("SIGINT")).toBe(sigint)
expect(process.listenerCount("SIGUSR2")).toBe(sigusr2)
} finally {
offInt()
offTheme()
}
})
test("passes frontend host capabilities", async () => {
const directory = await root()
const input = host({ stdin: stream(true), cleanup() {} }, directory)
await using directory = await tmpdir()
const input = host({ stdin: stream(true), cleanup() {} }, directory.path)
expect(input.paths).toEqual({ home: directory })
expect(input.paths).toEqual({ home: directory.path })
expect(input.platform).toBe(process.platform)
expect(typeof input.files.readText).toBe("function")
const file = path.join(directory, "attachment.txt")
const file = path.join(directory.path, "attachment.txt")
await Bun.write(file, "attachment contents")
expect(await input.files.readText(pathToFileURL(file).href)).toBe("attachment contents")
expect(typeof input.startup.showTiming).toBe("boolean")
@@ -160,9 +155,9 @@ describe("Mini CLI host", () => {
})
test("delegates model variant preferences", async () => {
const directory = await root()
const input = host({ stdin: stream(true), cleanup() {} }, directory)
const file = path.join(directory, "model.json")
await using directory = await tmpdir()
const input = host({ stdin: stream(true), cleanup() {} }, directory.path)
const file = path.join(directory.path, "model.json")
await input.preferences.saveVariant(model, "high")
expect(await input.preferences.resolveVariant(model)).toBe("high")
+11 -14
View File
@@ -2,6 +2,7 @@ import { expect, test } from "bun:test"
import path from "node:path"
import { parse } from "jsonc-parser"
import { configurationTarget, writePluginConfig } from "../src/commands/handlers/plugin/add"
import { tmpdir } from "./fixture/tmpdir"
test("routes packages according to their exported runtimes", () => {
expect(configurationTarget("server.js", "tui.js")).toBe("server")
@@ -11,20 +12,16 @@ test("routes packages according to their exported runtimes", () => {
})
test("adds a package to global plugin config without replacing unrelated settings", async () => {
const directory = await Bun.$`mktemp -d`.text().then((value) => value.trim())
const file = path.join(directory, "opencode.jsonc")
await using directory = await tmpdir()
const file = path.join(directory.path, "opencode.jsonc")
await Bun.write(file, '{\n // retained\n "model": "provider/model",\n "plugins": ["first"]\n}\n')
try {
expect(await writePluginConfig(file, "second@1.0.0")).toBe(true)
expect(await writePluginConfig(file, "second@1.0.0")).toBe(false)
const text = await Bun.file(file).text()
expect(text).toContain("// retained")
expect(parse(text)).toEqual({
model: "provider/model",
plugins: ["first", "second@1.0.0"],
})
} finally {
await Bun.$`rm -rf ${directory}`
}
expect(await writePluginConfig(file, "second@1.0.0")).toBe(true)
expect(await writePluginConfig(file, "second@1.0.0")).toBe(false)
const text = await Bun.file(file).text()
expect(text).toContain("// retained")
expect(parse(text)).toEqual({
model: "provider/model",
plugins: ["first", "second@1.0.0"],
})
})
+8 -11
View File
@@ -2,22 +2,19 @@ import { expect, test } from "bun:test"
import path from "node:path"
import { parse } from "jsonc-parser"
import { removePluginConfig } from "../src/commands/handlers/plugin/remove"
import { tmpdir } from "./fixture/tmpdir"
test("removes string and object package entries without replacing unrelated settings", async () => {
const directory = await Bun.$`mktemp -d`.text().then((value) => value.trim())
const file = path.join(directory, "opencode.jsonc")
await using directory = await tmpdir()
const file = path.join(directory.path, "opencode.jsonc")
await Bun.write(
file,
'{\n // retained\n "model": "provider/model",\n "plugins": ["remove-me", { "package": "remove-me", "options": {} }, "keep-me"]\n}\n',
)
try {
expect(await removePluginConfig(file, "remove-me")).toBe(true)
expect(await removePluginConfig(file, "remove-me")).toBe(false)
const text = await Bun.file(file).text()
expect(text).toContain("// retained")
expect(parse(text)).toEqual({ model: "provider/model", plugins: ["keep-me"] })
} finally {
await Bun.$`rm -rf ${directory}`
}
expect(await removePluginConfig(file, "remove-me")).toBe(true)
expect(await removePluginConfig(file, "remove-me")).toBe(false)
const text = await Bun.file(file).text()
expect(text).toContain("// retained")
expect(parse(text)).toEqual({ model: "provider/model", plugins: ["keep-me"] })
})
+2 -2
View File
@@ -1658,9 +1658,9 @@ export type ExperimentalPersistentPtyListOperation<E = never> = (
export type ExperimentalPersistentPtyCreateInput = {
readonly sessionID: Session.ID
readonly command: string
readonly command?: string | undefined
readonly args: ReadonlyArray<string>
readonly cwd: string
readonly cwd?: string | undefined
readonly title: string
readonly env: { readonly [x: string]: string }
readonly size?: { readonly cols: number; readonly rows: number } | undefined
@@ -526,7 +526,7 @@ export function make(options: ClientOptions) {
path: `/api/session/import`,
body: { info: input["info"], messages: input["messages"], location: input["location"] },
successStatus: 200,
declaredStatuses: [409, 401, 400],
declaredStatuses: [409, 404, 401, 400],
empty: false,
},
requestOptions,
+14 -14
View File
@@ -5753,50 +5753,50 @@ export type ExperimentalPersistentPtyListOutput = { data: Array<PersistentPtyInf
export type ExperimentalPersistentPtyCreateInput = {
readonly sessionID: { readonly sessionID: string }["sessionID"]
readonly command: {
readonly command: string
readonly command?: {
readonly command?: string
readonly args: ReadonlyArray<string>
readonly cwd: string
readonly cwd?: string
readonly title: string
readonly env: { readonly [x: string]: string }
readonly size?: { readonly cols: number; readonly rows: number }
}["command"]
readonly args: {
readonly command: string
readonly command?: string
readonly args: ReadonlyArray<string>
readonly cwd: string
readonly cwd?: string
readonly title: string
readonly env: { readonly [x: string]: string }
readonly size?: { readonly cols: number; readonly rows: number }
}["args"]
readonly cwd: {
readonly command: string
readonly cwd?: {
readonly command?: string
readonly args: ReadonlyArray<string>
readonly cwd: string
readonly cwd?: string
readonly title: string
readonly env: { readonly [x: string]: string }
readonly size?: { readonly cols: number; readonly rows: number }
}["cwd"]
readonly title: {
readonly command: string
readonly command?: string
readonly args: ReadonlyArray<string>
readonly cwd: string
readonly cwd?: string
readonly title: string
readonly env: { readonly [x: string]: string }
readonly size?: { readonly cols: number; readonly rows: number }
}["title"]
readonly env: {
readonly command: string
readonly command?: string
readonly args: ReadonlyArray<string>
readonly cwd: string
readonly cwd?: string
readonly title: string
readonly env: { readonly [x: string]: string }
readonly size?: { readonly cols: number; readonly rows: number }
}["env"]
readonly size?: {
readonly command: string
readonly command?: string
readonly args: ReadonlyArray<string>
readonly cwd: string
readonly cwd?: string
readonly title: string
readonly env: { readonly [x: string]: string }
readonly size?: { readonly cols: number; readonly rows: number }
@@ -0,0 +1,56 @@
import { mkdtemp, rm } from "node:fs/promises"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { waitForExit } from "./service-timing"
export async function serviceFixture() {
const directory = await mkdtemp(join(tmpdir(), "opencode-client-service-"))
const registration = join(directory, "service.json")
const processes: Bun.Subprocess[] = []
const pids = new Set<number>()
const command = (mode: string, ...args: string[]) => [
process.execPath,
join(import.meta.dir, "service.ts"),
registration,
mode,
...args,
]
return {
directory,
registration,
command,
spawn(mode: string, ...args: string[]) {
const subprocess = Bun.spawn(command(mode, ...args), { stdout: "ignore", stderr: "inherit" })
processes.push(subprocess)
return subprocess
},
// Service.ensure detaches contenders; track the elected process before asserting.
track(pid: number) {
pids.add(pid)
},
async waitForFile(file = registration) {
for (let attempt = 0; attempt < 600; attempt++) {
if (await Bun.file(file).exists()) return
await Bun.sleep(5)
}
throw new Error(`Timed out waiting for ${file}`)
},
async [Symbol.asyncDispose]() {
await Promise.all([
...processes.map(async (subprocess) => {
subprocess.kill("SIGTERM")
await subprocess.exited
}),
...[...pids].map(async (pid) => {
try {
process.kill(pid, "SIGTERM")
} catch (error) {
if (!(error instanceof Error && "code" in error && error.code === "ESRCH")) throw error
}
await waitForExit(pid)
}),
]).finally(() => rm(directory, { recursive: true, force: true }))
},
}
}
@@ -10,7 +10,7 @@ const timing = {
stopPollInterval: 5,
}
export function accelerate<A extends object, B>(ensure: (options: A) => B) {
export function accelerate<A extends object, B>(ensure: (options?: A) => B) {
return (options: A) => ensure(withEnsureTiming(options, timing))
}
+47 -83
View File
@@ -1,23 +1,15 @@
import { afterEach, expect, test } from "bun:test"
import { mkdtemp, rm } from "node:fs/promises"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { expect, test } from "bun:test"
import { Service, type EnsureReason } from "../src/promise/service"
import { accelerate, waitForExit } from "./fixture/service-timing"
import { serviceFixture } from "./fixture/service-fixture"
import { accelerate } from "./fixture/service-timing"
const fixture = join(import.meta.dir, "fixture/service.ts")
const ensure = accelerate(Service.ensure)
const processes: Bun.Subprocess[] = []
const directories: string[] = []
afterEach(async () => {
processes.forEach((process) => process.kill("SIGTERM"))
await Promise.all(processes.splice(0).map((process) => process.exited))
await Promise.all(directories.splice(0).map((directory) => rm(directory, { recursive: true, force: true })))
})
test("discovers a registered service", async () => {
const registration = await setup("graceful")
await using fixture = await serviceFixture()
const registration = fixture.registration
fixture.spawn("graceful")
await fixture.waitForFile()
expect(await Service.discover({ file: registration, version: "test" })).toEqual(
expect.objectContaining({ url: expect.stringMatching(/^http:\/\//) }),
@@ -26,7 +18,10 @@ test("discovers a registered service", async () => {
})
test("discovers a compatible registered service", async () => {
const registration = await setup("compatible")
await using fixture = await serviceFixture()
const registration = fixture.registration
fixture.spawn("compatible")
await fixture.waitForFile()
expect(await Service.discover({ file: registration, version: "2.1.0" })).toBeUndefined()
expect(await Service.discover({ file: registration, version: "2.1.0-next.1" })).toEqual(
@@ -39,66 +34,59 @@ test("discovers a compatible registered service", async () => {
})
test("ensures a missing service with native promises", async () => {
const directory = await temp()
const registration = join(directory, "service.json")
await using fixture = await serviceFixture()
const registration = fixture.registration
const starts: EnsureReason[] = []
const endpoint = await ensure({
file: registration,
version: "test",
command: [process.execPath, fixture, registration, "coordinated"],
command: fixture.command("coordinated"),
onStart: (reason) => starts.push(reason),
})
const info = await Bun.file(registration).json()
try {
expect(endpoint.url).toBe(info.url)
expect(starts).toEqual(["missing"])
} finally {
process.kill(info.pid, "SIGTERM")
await waitForExit(info.pid)
}
fixture.track(info.pid)
expect(endpoint.url).toBe(info.url)
expect(starts).toEqual(["missing"])
})
test("adds configured environment variables with native promises", async () => {
const directory = await temp()
const registration = join(directory, "service.json")
await using fixture = await serviceFixture()
const registration = fixture.registration
const endpoint = await ensure({
file: registration,
version: "test",
command: [process.execPath, fixture, registration, "environment"],
command: fixture.command("environment"),
env: { OPENCODE_SERVICE_ENV_TEST: "configured" },
})
const info = await Bun.file(registration).json()
fixture.track(info.pid)
try {
expect(endpoint.url).toBe(info.url)
expect(await Bun.file(registration + ".environment").text()).toBe("configured")
} finally {
process.kill(info.pid, "SIGTERM")
await waitForExit(info.pid)
}
expect(endpoint.url).toBe(info.url)
expect(await Bun.file(registration + ".environment").text()).toBe("configured")
})
test("waits for a live contender when another native contender fails", async () => {
const directory = await temp()
const registration = join(directory, "service.json")
await using fixture = await serviceFixture()
const registration = fixture.registration
const endpoint = await ensure({
file: registration,
version: "test",
command: [process.execPath, fixture, registration, "coordinated-failed-loser", "300"],
command: fixture.command("coordinated-failed-loser", "300"),
})
const info = await Bun.file(registration).json()
try {
expect(endpoint.url).toBe(info.url)
} finally {
process.kill(info.pid, "SIGTERM")
await waitForExit(info.pid)
}
fixture.track(info.pid)
expect(endpoint.url).toBe(info.url)
})
test("reports a failed registered service", async () => {
const registration = await setup("failed-owner")
await using fixture = await serviceFixture()
const registration = fixture.registration
fixture.spawn("failed-owner")
await fixture.waitForFile()
await expect(ensure({ file: registration, version: "test", command: [] })).rejects.toThrow(
"Background service failed to start",
@@ -106,12 +94,12 @@ test("reports a failed registered service", async () => {
})
test("reports a bounded contender stderr tail with native promises", async () => {
const directory = await temp()
const registration = join(directory, "service.json")
await using fixture = await serviceFixture()
const registration = fixture.registration
const error = await Service.ensure({
file: registration,
version: "test",
command: [process.execPath, fixture, registration, "stderr-failed"],
command: fixture.command("stderr-failed"),
}).catch((error: unknown) => error)
expect(error).toBeInstanceOf(Error)
@@ -121,58 +109,34 @@ test("reports a bounded contender stderr tail with native promises", async () =>
}, 10_000)
test("evicts an unresponsive registered service before starting its replacement", async () => {
const directory = await temp()
const registration = join(directory, "service.json")
const existing = Bun.spawn([process.execPath, fixture, registration, "hanging"], {
stdout: "ignore",
stderr: "inherit",
})
processes.push(existing)
await waitForFile(registration)
await using fixture = await serviceFixture()
const registration = fixture.registration
const existing = fixture.spawn("hanging")
await fixture.waitForFile()
const original = await Bun.file(registration).json()
const endpoint = await ensure({
file: registration,
version: "test",
command: [process.execPath, fixture, registration, "delayed", "10"],
command: fixture.command("delayed", "10"),
})
const replacement = await Bun.file(registration).json()
fixture.track(replacement.pid)
expect((await Bun.file(registration + ".requests").text()).trim().split("\n")).toHaveLength(3)
expect(await existing.exited).toBe(0)
expect(replacement.pid).not.toBe(original.pid)
expect(endpoint.url).toBe(replacement.url)
process.kill(replacement.pid, "SIGTERM")
await waitForExit(replacement.pid)
})
test("signals the registered service process", async () => {
const registration = await setup("graceful")
await using fixture = await serviceFixture()
const registration = fixture.registration
fixture.spawn("graceful")
await fixture.waitForFile()
await Service.stop({ file: registration })
expect(await Bun.file(registration + ".signal").text()).toBe("SIGTERM")
expect(await Bun.file(registration).exists()).toBe(false)
})
async function setup(mode: string) {
const directory = await temp()
const registration = join(directory, "service.json")
processes.push(Bun.spawn([process.execPath, fixture, registration, mode], { stdout: "ignore", stderr: "inherit" }))
await waitForFile(registration)
return registration
}
async function temp() {
const directory = await mkdtemp(join(tmpdir(), "opencode-promise-service-"))
directories.push(directory)
return directory
}
async function waitForFile(file: string) {
for (let attempt = 0; attempt < 600; attempt++) {
if (await Bun.file(file).exists()) return
await Bun.sleep(5)
}
throw new Error(`Timed out waiting for ${file}`)
}
+93 -142
View File
@@ -1,28 +1,18 @@
import { NodeFileSystem } from "@effect/platform-node"
import { afterEach, expect, test } from "bun:test"
import { Effect } from "effect"
import { mkdtemp, rm, writeFile } from "node:fs/promises"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { expect, test } from "bun:test"
import { Effect, FileSystem } from "effect"
import { writeFile } from "node:fs/promises"
import { Service, type EnsureReason } from "../src/effect/service"
import { accelerate, waitForExit } from "./fixture/service-timing"
import { serviceFixture } from "./fixture/service-fixture"
import { accelerate } from "./fixture/service-timing"
const fixture = join(import.meta.dir, "fixture/service.ts")
const ensure = accelerate(Service.ensure)
const processes: Bun.Subprocess[] = []
const directories: string[] = []
afterEach(async () => {
processes.forEach((process) => process.kill("SIGTERM"))
await Promise.all(processes.splice(0).map((process) => process.exited))
await Promise.all(directories.splice(0).map((directory) => rm(directory, { recursive: true, force: true })))
})
test("a concurrent same-version start cannot invalidate a resolved endpoint", async () => {
const directory = await temp()
const registration = join(directory, "service.json")
spawn(registration, "modern")
await waitForFile(registration)
await using fixture = await serviceFixture()
const registration = fixture.registration
fixture.spawn("modern")
await fixture.waitForFile()
const original = await Bun.file(registration).json()
const starts: EnsureReason[] = []
@@ -34,7 +24,7 @@ test("a concurrent same-version start cannot invalidate a resolved endpoint", as
onStart: (reason) => starts.push(reason),
}),
)
await waitForFile(registration + ".first-request")
await fixture.waitForFile(registration + ".first-request")
const resolved = await run(ensure({ file: registration, version: "test" }))
expect(resolved.url).toBe(original.url)
@@ -48,10 +38,10 @@ test("a concurrent same-version start cannot invalidate a resolved endpoint", as
})
test("reuses a compatible registered service", async () => {
const directory = await temp()
const registration = join(directory, "service.json")
const existing = spawn(registration, "compatible")
await waitForFile(registration)
await using fixture = await serviceFixture()
const registration = fixture.registration
const existing = fixture.spawn("compatible")
await fixture.waitForFile()
const starts: EnsureReason[] = []
const endpoint = await run(
@@ -69,70 +59,65 @@ test("reuses a compatible registered service", async () => {
})
test("adds configured environment variables when starting a service", async () => {
const directory = await temp()
const registration = join(directory, "service.json")
await using fixture = await serviceFixture()
const registration = fixture.registration
const endpoint = await run(
ensure({
file: registration,
version: "test",
command: [process.execPath, fixture, registration, "environment"],
command: fixture.command("environment"),
env: { OPENCODE_SERVICE_ENV_TEST: "configured" },
}),
)
const info = await Bun.file(registration).json()
fixture.track(info.pid)
try {
expect(endpoint.url).toBe(info.url)
expect(await Bun.file(registration + ".environment").text()).toBe("configured")
} finally {
process.kill(info.pid, "SIGTERM")
await waitForExit(info.pid)
}
expect(endpoint.url).toBe(info.url)
expect(await Bun.file(registration + ".environment").text()).toBe("configured")
})
test("replaces an incompatible registered service", async () => {
const directory = await temp()
const registration = join(directory, "service.json")
const existing = spawn(registration, "incompatible")
await waitForFile(registration)
await using fixture = await serviceFixture()
const registration = fixture.registration
const existing = fixture.spawn("incompatible")
await fixture.waitForFile()
const starts: EnsureReason[] = []
const endpoint = await run(
ensure({
file: registration,
version: (version) => version.startsWith("2."),
command: [process.execPath, fixture, registration, "delayed-compatible", "10"],
command: fixture.command("delayed-compatible", "10"),
onStart: (reason) => starts.push(reason),
}),
)
const replacement = await Bun.file(registration).json()
fixture.track(replacement.pid)
expect(await existing.exited).toBe(0)
expect(replacement.version).toBe("2.1.0-next.1")
expect(endpoint.url).toBe(replacement.url)
expect(starts).toEqual(["version-mismatch"])
process.kill(replacement.pid, "SIGTERM")
await waitForExit(replacement.pid)
})
test("waits for a registered service to finish starting", async () => {
const directory = await temp()
const registration = join(directory, "service.json")
const process = spawn(registration, "starting")
await waitForFile(registration)
await using fixture = await serviceFixture()
const registration = fixture.registration
const process = fixture.spawn("starting")
await fixture.waitForFile()
const result = run(ensure({ file: registration, version: "test", command: [] }))
await waitForFile(registration + ".health-request")
await fixture.waitForFile(registration + ".health-request")
expect(process.exitCode).toBe(null)
await writeFile(registration + ".release", "")
expect((await result).url).toBe((await Bun.file(registration).json()).url)
})
test("reports a failed registered service without spawning", async () => {
const directory = await temp()
const registration = join(directory, "service.json")
const process = spawn(registration, "failed-owner")
await waitForFile(registration)
await using fixture = await serviceFixture()
const registration = fixture.registration
const process = fixture.spawn("failed-owner")
await fixture.waitForFile()
await expect(run(ensure({ file: registration, version: "test", command: [] }))).rejects.toThrow(
"Background service failed to start",
@@ -141,35 +126,34 @@ test("reports a failed registered service without spawning", async () => {
})
test("evicts an unresponsive registered service before starting its replacement", async () => {
const directory = await temp()
const registration = join(directory, "service.json")
const existing = spawn(registration, "hanging")
await waitForFile(registration)
await using fixture = await serviceFixture()
const registration = fixture.registration
const existing = fixture.spawn("hanging")
await fixture.waitForFile()
const original = await Bun.file(registration).json()
const endpoint = await run(
ensure({
file: registration,
version: "test",
command: [process.execPath, fixture, registration, "delayed", "10"],
command: fixture.command("delayed", "10"),
}),
)
const replacement = await Bun.file(registration).json()
fixture.track(replacement.pid)
expect((await Bun.file(registration + ".requests").text()).trim().split("\n")).toHaveLength(3)
expect(await existing.exited).toBe(0)
expect(replacement.pid).not.toBe(original.pid)
expect(endpoint.url).toBe(replacement.url)
expect(await health(endpoint.url)).toEqual({ healthy: true, version: "test", pid: replacement.pid })
process.kill(replacement.pid, "SIGTERM")
await waitForExit(replacement.pid)
})
test("signals an unresponsive registered service process", async () => {
const directory = await temp()
const registration = join(directory, "service.json")
const process = spawn(registration, "hanging")
await waitForFile(registration)
await using fixture = await serviceFixture()
const registration = fixture.registration
const process = fixture.spawn("hanging")
await fixture.waitForFile()
await run(Service.stop({ file: registration }))
await process.exited
@@ -178,30 +162,29 @@ test("signals an unresponsive registered service process", async () => {
})
test("signals an incompatible service before starting its replacement", async () => {
const directory = await temp()
const registration = join(directory, "service.json")
const existing = spawn(registration, "old")
await waitForFile(registration)
await using fixture = await serviceFixture()
const registration = fixture.registration
const existing = fixture.spawn("old")
await fixture.waitForFile()
const endpoint = await run(
ensure({
file: registration,
version: "test",
command: [process.execPath, fixture, registration, "delayed", "10"],
command: fixture.command("delayed", "10"),
}),
)
const replacement = await Bun.file(registration).json()
fixture.track(replacement.pid)
expect(await existing.exited).toBe(0)
expect(endpoint.url).toBe(replacement.url)
process.kill(replacement.pid, "SIGTERM")
await waitForExit(replacement.pid)
})
test("a legacy health response is still replaced", async () => {
const directory = await temp()
const registration = join(directory, "service.json")
const existing = spawn(registration, "legacy")
await waitForFile(registration)
await using fixture = await serviceFixture()
const registration = fixture.registration
const existing = fixture.spawn("legacy")
await fixture.waitForFile()
const starts: EnsureReason[] = []
const result = run(ensure({ file: registration, command: [], onStart: (reason) => starts.push(reason) }))
@@ -212,67 +195,61 @@ test("a legacy health response is still replaced", async () => {
})
test("waits for a slow winner while bounding lock probes", async () => {
const directory = await temp()
const registration = join(directory, "service.json")
await using fixture = await serviceFixture()
const registration = fixture.registration
const endpoint = await run(
ensure({
file: registration,
version: "test",
command: [process.execPath, fixture, registration, "coordinated"],
command: fixture.command("coordinated"),
}),
)
const info = await Bun.file(registration).json()
try {
expect(endpoint.url).toBe(info.url)
expect(await health(endpoint.url)).toEqual({ healthy: true, version: "test", pid: info.pid })
expect((await Bun.file(registration + ".starts").text()).trim().split("\n")).toHaveLength(2)
} finally {
process.kill(info.pid, "SIGTERM")
await waitForExit(info.pid)
}
fixture.track(info.pid)
expect(endpoint.url).toBe(info.url)
expect(await health(endpoint.url)).toEqual({ healthy: true, version: "test", pid: info.pid })
expect((await Bun.file(registration + ".starts").text()).trim().split("\n")).toHaveLength(2)
})
test("waits for a live contender when another contender fails", async () => {
const directory = await temp()
const registration = join(directory, "service.json")
await using fixture = await serviceFixture()
const registration = fixture.registration
const endpoint = await run(
ensure({
file: registration,
version: "test",
command: [process.execPath, fixture, registration, "coordinated-failed-loser", "300"],
command: fixture.command("coordinated-failed-loser", "300"),
}),
)
const info = await Bun.file(registration).json()
try {
expect(endpoint.url).toBe(info.url)
} finally {
process.kill(info.pid, "SIGTERM")
await waitForExit(info.pid)
}
fixture.track(info.pid)
expect(endpoint.url).toBe(info.url)
})
test("reports a contender that fails to start", async () => {
const directory = await temp()
const registration = join(directory, "service.json")
await using fixture = await serviceFixture()
const registration = fixture.registration
await expect(
run(
ensure({
file: registration,
version: "test",
command: [process.execPath, fixture, registration, "failed"],
command: fixture.command("failed"),
}),
),
).rejects.toThrow("Server process exited with code 1")
})
test("reports a bounded contender stderr tail", async () => {
const directory = await temp()
const registration = join(directory, "service.json")
await using fixture = await serviceFixture()
const registration = fixture.registration
const error = await run(
Service.ensure({
file: registration,
version: "test",
command: [process.execPath, fixture, registration, "stderr-failed"],
command: fixture.command("stderr-failed"),
}),
).catch((error: unknown) => error)
@@ -283,85 +260,59 @@ test("reports a bounded contender stderr tail", async () => {
}, 10_000)
test("reports a contender terminated by a signal", async () => {
const directory = await temp()
const registration = join(directory, "service.json")
await using fixture = await serviceFixture()
const registration = fixture.registration
await expect(
run(
ensure({
file: registration,
version: "test",
command: [process.execPath, fixture, registration, "signal"],
command: fixture.command("signal"),
}),
),
).rejects.toThrow(/Server process (terminated by|exited with code)/)
})
test("reports a slow contender that eventually fails", async () => {
const directory = await temp()
const registration = join(directory, "service.json")
await using fixture = await serviceFixture()
const registration = fixture.registration
await expect(
run(
ensure({
file: registration,
version: "test",
command: [process.execPath, fixture, registration, "delayed-failed", "500"],
command: fixture.command("delayed-failed", "500"),
}),
),
).rejects.toThrow("Server process exited with code 1")
})
test("replaces an incompatible owner that appears during startup", async () => {
const directory = await temp()
const registration = join(directory, "service.json")
await using fixture = await serviceFixture()
const registration = fixture.registration
const starting = run(
ensure({
file: registration,
version: "test",
command: [process.execPath, fixture, registration, "delayed", "500"],
command: fixture.command("delayed", "500"),
}),
)
await waitForFile(registration + ".starts")
const old = spawn(registration, "old")
await waitForFile(registration)
await fixture.waitForFile(registration + ".starts")
const old = fixture.spawn("old")
await fixture.waitForFile()
const endpoint = await starting
const info = await Bun.file(registration).json()
try {
expect(endpoint.url).toBe(info.url)
expect(info.version).toBe("test")
await old.exited
} finally {
process.kill(info.pid, "SIGTERM")
await waitForExit(info.pid)
}
fixture.track(info.pid)
expect(endpoint.url).toBe(info.url)
expect(info.version).toBe("test")
await old.exited
})
function run<A, E>(effect: Effect.Effect<A, E>) {
function run<A, E>(effect: Effect.Effect<A, E, FileSystem.FileSystem>) {
return Effect.runPromise(effect.pipe(Effect.provide(NodeFileSystem.layer)))
}
function spawn(registration: string, mode: string, ...args: string[]) {
const subprocess = Bun.spawn([process.execPath, fixture, registration, mode, ...args], {
stdout: "ignore",
stderr: "inherit",
})
processes.push(subprocess)
return subprocess
}
async function temp() {
const directory = await mkdtemp(join(tmpdir(), "opencode-client-service-"))
directories.push(directory)
return directory
}
async function waitForFile(file: string) {
for (let attempt = 0; attempt < 600; attempt++) {
if (await Bun.file(file).exists()) return
await Bun.sleep(5)
}
throw new Error(`Timed out waiting for ${file}`)
}
async function health(url: string) {
return fetch(new URL("/api/health", url), { signal: AbortSignal.timeout(1_000) }).then((response) => response.json())
}
+1 -8
View File
@@ -402,14 +402,7 @@ export const make = Effect.gen(function* () {
})
const pendingBackground: Interface["pendingBackground"] = Effect.gen(function* () {
const recovered: Background[] = []
let after: string | undefined
do {
const page = yield* kv.scan({ prefix: backgroundPrefix, after })
recovered.push(...Array.filterMap(page.entries, (entry) => decodeBackground(entry.value)))
after = page.next
} while (after)
return recovered
return Array.filterMap(yield* kv.scanAll(backgroundPrefix), (entry) => decodeBackground(entry.value))
}).pipe(Effect.withSpan("Job.pendingBackground"))
const completeBackground: Interface["completeBackground"] = Effect.fn("Job.completeBackground")((notificationID) =>
+33 -20
View File
@@ -29,6 +29,7 @@ export interface Interface {
readonly set: (key: string, value: Value) => Effect.Effect<void>
readonly remove: (key: string) => Effect.Effect<void>
readonly scan: (options: ScanOptions) => Effect.Effect<ScanResult>
readonly scanAll: (prefix: string) => Effect.Effect<readonly Entry[]>
}
export class Service extends Context.Service<Service, Interface>()("@opencode/KV") {}
@@ -37,6 +38,28 @@ const layer = Layer.effect(
Service,
Effect.gen(function* () {
const db = (yield* Database.Service).db
const scan: Interface["scan"] = Effect.fn("KV.scan")(function* (options) {
const limit = Number.isNaN(options.limit) ? 100 : Math.min(Math.max(Math.floor(options.limit ?? 100), 1), 1000)
const end = prefixEnd(options.prefix)
const rows = yield* db
.select({ key: KVTable.key, value: KVTable.value })
.from(KVTable)
.where(
and(
options.prefix === "" ? undefined : gte(KVTable.key, options.prefix),
end === undefined ? undefined : lt(KVTable.key, end),
options.after === undefined ? undefined : gt(KVTable.key, options.after),
),
)
.orderBy(asc(KVTable.key))
.limit(limit + 1)
.all()
.pipe(Effect.orDie)
const entries = rows.slice(0, limit)
if (rows.length <= limit) return { entries }
return { entries, next: entries[entries.length - 1].key }
})
return Service.of({
get: Effect.fn("KV.get")(function* (key) {
return (yield* db
@@ -57,26 +80,16 @@ const layer = Layer.effect(
remove: Effect.fn("KV.remove")(function* (key) {
yield* db.delete(KVTable).where(eq(KVTable.key, key)).run().pipe(Effect.orDie)
}),
scan: Effect.fn("KV.scan")(function* (options) {
const limit = Number.isNaN(options.limit) ? 100 : Math.min(Math.max(Math.floor(options.limit ?? 100), 1), 1000)
const end = prefixEnd(options.prefix)
const rows = yield* db
.select({ key: KVTable.key, value: KVTable.value })
.from(KVTable)
.where(
and(
options.prefix === "" ? undefined : gte(KVTable.key, options.prefix),
end === undefined ? undefined : lt(KVTable.key, end),
options.after === undefined ? undefined : gt(KVTable.key, options.after),
),
)
.orderBy(asc(KVTable.key))
.limit(limit + 1)
.all()
.pipe(Effect.orDie)
const entries = rows.slice(0, limit)
if (rows.length <= limit) return { entries }
return { entries, next: entries[entries.length - 1].key }
scan,
scanAll: Effect.fn("KV.scanAll")(function* (prefix) {
const entries: Entry[] = []
let after: string | undefined
do {
const page = yield* scan({ prefix, after, limit: 1000 })
entries.push(...page.entries)
after = page.next
} while (after !== undefined)
return entries
}),
})
}),
+4 -2
View File
@@ -26,6 +26,7 @@ import { ModelResolver } from "./model-resolver.js"
import { MCP } from "./mcp/index.js"
import { Permission } from "./permission.js"
import { Plugin } from "./plugin.js"
import { PluginHooks } from "./plugin/hooks.js"
import { PluginSupervisor } from "./plugin/supervisor.js"
import { Worktree } from "./worktree.js"
import { Pty } from "./pty.js"
@@ -47,7 +48,7 @@ import { InstructionBuiltIns } from "./instructions/builtins.js"
import { InstructionEntry } from "./session/instruction-entry.js"
import { SessionInstructions } from "./session/instructions.js"
import { SessionGenerateNode } from "./session/generate-node.js"
import { MCPTool } from "./tool/mcp.js"
import { McpTool } from "./tool/mcp.js"
import { ReadToolFileSystem } from "./tool/read-filesystem.js"
import { Tool } from "./tool.js"
import { ToolOutput } from "./tool-output.js"
@@ -69,6 +70,7 @@ const locationServiceNodes = [
ModelResolver.node,
AISDK.node,
Plugin.node,
PluginHooks.node,
PluginSupervisor.node,
Worktree.refreshNode,
FileSystemSearch.node,
@@ -94,7 +96,7 @@ const locationServiceNodes = [
Generate.node,
SessionGenerateNode.node,
ReadToolFileSystem.node,
MCPTool.node,
McpTool.node,
SessionInstructions.node,
SessionRunnerModel.node,
SessionModelTransport.node,
+4 -4
View File
@@ -1,10 +1,10 @@
export * as MCPInstructions from "./instructions.js"
export * as McpInstructions from "./instructions.js"
import { makeLocationNode } from "@opencode-ai/util/effect/app-node"
import { Context, Effect, Layer, Schema } from "effect"
import { Agent } from "../agent.js"
import { Permission } from "../permission.js"
import { MCPTool } from "../tool/mcp.js"
import { McpTool } from "../tool/mcp.js"
import { MCP } from "./index.js"
import { Instructions } from "../instructions/index.js"
@@ -20,7 +20,7 @@ const entries = (servers: ReadonlyArray<Summary>) =>
const result = [` <server name="${server.server}">`]
if (server.codemode !== false)
result.push(
` Use tools from this server through \`execute\` under \`tools[${JSON.stringify(MCPTool.namespace(server.server))}]\`.`,
` Use tools from this server through \`execute\` under \`tools[${JSON.stringify(McpTool.namespace(server.server))}]\`.`,
)
result.push(...server.instructions.split("\n").map((line) => ` ${line}`), " </server>")
return result
@@ -93,7 +93,7 @@ export const layer = Layer.effect(
if (
!owned.some(
(tool) =>
Permission.evaluate(MCPTool.name(tool.server, tool.name), "*", agent.permissions).effect !== "deny",
Permission.evaluate(McpTool.name(tool.server, tool.name), "*", agent.permissions).effect !== "deny",
)
)
return []
+7 -6
View File
@@ -11,6 +11,7 @@ import { Bus } from "../bus.js"
import { Database } from "../database/database.js"
import { Pty } from "@opencode-ai/schema/pty"
import { Global } from "@opencode-ai/util/global"
import { ShellSelect } from "../shell/select.js"
import {
makeDaemonTransport,
type DaemonTransport,
@@ -66,9 +67,9 @@ export interface Interface {
readonly create: (
sessionID: Session.ID,
input: {
readonly command: string
readonly command?: string
readonly args: readonly string[]
readonly cwd: string
readonly cwd?: string
readonly title: string
readonly env: Readonly<Record<string, string>>
readonly cols?: number
@@ -154,9 +155,9 @@ export const layer = Layer.effect(
const create = Effect.fn("PersistentPty.create")(function* (
sessionID: Session.ID,
input: {
readonly command: string
readonly command?: string
readonly args: readonly string[]
readonly cwd: string
readonly cwd?: string
readonly title: string
readonly env: Readonly<Record<string, string>>
readonly cols?: number
@@ -167,9 +168,9 @@ export const layer = Layer.effect(
daemon,
{
op: "create",
program: input.command,
program: input.command ?? ShellSelect.environment(global.bin),
args: input.args,
cwd: input.cwd,
cwd: input.cwd ?? path.resolve("/"),
title: input.title,
group_id: sessionID,
env: input.env,
+58 -41
View File
@@ -41,6 +41,7 @@ import { Session } from "@opencode-ai/schema/session"
import { FSUtil } from "@opencode-ai/util/fs-util"
import { Image } from "./image.js"
import { PluginSupervisor } from "./plugin/supervisor-service.js"
import { PluginHooks } from "./plugin/hooks.js"
import { Mime } from "./mime.js"
import type { EventLog } from "@opencode-ai/schema/event-log"
import { Event } from "@opencode-ai/schema/event"
@@ -640,39 +641,30 @@ const layer = Layer.effect(
),
),
prompt: Effect.fn("Session.prompt")((input) =>
Effect.uninterruptible(
Effect.uninterruptibleMask((restore) =>
Effect.gen(function* () {
const session = yield* result.get(input.sessionID)
// A staged revert must be committed before admitting new input so the prompt
// continues from the reverted boundary rather than stale post-boundary history.
if (session.revert) yield* SessionRevert.commit(session).pipe(Effect.provideService(Bus.Service, bus))
// Resolved lazily so prompt admission only boots location services when an
// image attachment actually needs the resizer.
const image = Effect.gen(function* () {
const plugins = yield* PluginSupervisor.Service
yield* plugins.flush
return yield* Image.Service
}).pipe(Effect.provide(locations.get(session.location)))
const skills = Effect.gen(function* () {
const plugins = yield* PluginSupervisor.Service
yield* plugins.flush
return yield* Skill.Service
}).pipe(Effect.provide(locations.get(session.location)))
const prompt = yield* resolvePrompt(
{ text: input.text, files: input.files, agents: input.agents, skills: input.skills },
image,
skills,
).pipe(Effect.provideService(FSUtil.Service, fs))
const messageID = input.id ?? SessionMessage.ID.create()
const admittedInput = SessionInbox.Item.make({
type: "user",
payload: { ...prompt, metadata: input.metadata },
delivery: input.delivery ?? "steer",
})
const admitted = yield* SessionInbox.admit(db, bus, {
id: messageID,
sessionID: input.sessionID,
item: admittedInput,
const admitted = yield* Effect.gen(function* () {
const existing = yield* SessionInbox.reconcile(db, {
id: messageID,
sessionID: session.id,
delivery: input.delivery ?? "steer",
})
if (existing) return existing
const item = yield* restore(
preparePrompt(input, messageID).pipe(
Effect.provide(locations.get(session.location)),
Effect.provideService(FSUtil.Service, fs),
),
)
// Commit a staged revert only after preparation succeeds, before admitting new work.
if (session.revert) yield* SessionRevert.commit(session).pipe(Effect.provideService(Bus.Service, bus))
return yield* SessionInbox.admit(db, bus, {
id: messageID,
sessionID: session.id,
item,
})
}).pipe(
Effect.catchDefect((defect) =>
defect instanceof SessionInbox.LifecycleConflict
@@ -1018,19 +1010,34 @@ function synthesizeTerminalShellInfo(started: ShellSchema.Info): ShellSchema.Inf
}
}
const resolvePrompt = Effect.fn("Session.resolvePrompt")(function* (
input: PromptInput.Prompt,
image: Effect.Effect<Image.Interface>,
skills: Effect.Effect<Skill.Interface>,
const preparePrompt = Effect.fn("Session.preparePrompt")(function* (
request: Parameters<Interface["prompt"]>[0],
messageID: SessionMessage.ID,
) {
const plugins = yield* PluginSupervisor.Service
yield* plugins.flush
const hooks = yield* PluginHooks.Service
const event = yield* hooks.trigger("session", "prompt", {
sessionID: request.sessionID,
messageID,
prompt: structuredClone({
text: request.text,
files: request.files?.slice(),
agents: request.agents?.slice(),
skills: request.skills?.slice(),
}),
metadata: structuredClone(request.metadata),
delivery: request.delivery ?? "steer",
})
const input = event.prompt
const fs = yield* FSUtil.Service
const files = input.files
? yield* Effect.forEach(input.files, (file) => materializeAttachment(fs, file, image), { concurrency: 8 })
? yield* Effect.forEach(input.files, (file) => materializeAttachment(fs, file), { concurrency: 8 })
: undefined
const requested = input.skills
const selected = yield* Effect.gen(function* () {
if (!requested?.length) return undefined
const skillService = yield* skills
const skillService = yield* Skill.Service
const prepared = new Map<Skill.ID, Skill.Name>()
return yield* Effect.forEach(requested, (attachment) =>
Effect.gen(function* () {
@@ -1048,7 +1055,19 @@ const resolvePrompt = Effect.fn("Session.resolvePrompt")(function* (
}),
)
})
return Prompt.make({ text: input.text, agents: input.agents, files, skills: selected?.length ? selected : undefined })
return SessionInbox.Item.make({
type: "user",
payload: {
...Prompt.make({
text: input.text,
agents: input.agents,
files,
skills: selected?.length ? selected : undefined,
}),
metadata: event.metadata,
},
delivery: event.delivery,
})
})
const MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024
@@ -1056,7 +1075,6 @@ const MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024
const materializeAttachment = Effect.fn("Session.materializeAttachment")(function* (
fs: FSUtil.Interface,
input: PromptInput.FileAttachment,
image: Effect.Effect<Image.Interface>,
) {
const resolved = input.uri.startsWith("data:")
? {
@@ -1085,7 +1103,7 @@ const materializeAttachment = Effect.fn("Session.materializeAttachment")(functio
.join("\n"),
)
: resolved.bytes
const normalized = yield* normalizeImageAttachment(input, Buffer.from(content).toString("base64"), mime, image)
const normalized = yield* normalizeImageAttachment(input, Buffer.from(content).toString("base64"), mime)
return FileAttachment.create({
data: normalized.data,
mime: normalized.mime,
@@ -1100,10 +1118,9 @@ const normalizeImageAttachment = Effect.fn("Session.normalizeImageAttachment")(f
input: PromptInput.FileAttachment,
data: string,
mime: string,
image: Effect.Effect<Image.Interface>,
) {
if (!mime.startsWith("image/")) return { data: Base64.make(data), mime }
const service = yield* image
const service = yield* Image.Service
const label = input.name ?? (input.uri.startsWith("data:") ? "inline attachment" : input.uri)
const content = { uri: label, content: data, encoding: "base64" as const, mime }
const normalized = yield* service.normalize(label, content).pipe(
+14 -10
View File
@@ -8,9 +8,10 @@ import { Bus } from "../bus.js"
import { makeLocationNode } from "@opencode-ai/util/effect/app-node"
import { llmClient } from "../effect/app-node-platform.js"
import { SessionEvent } from "./event.js"
import type { SessionContext } from "./context.js"
import type { SessionMessage } from "./message.js"
import { SessionModelRequest } from "./model-request.js"
import { SessionRunnerModel } from "./runner/model.js"
import type { SessionModelRequest } from "./model-request.js"
import type { SessionRunnerModel } from "./runner/model.js"
import { SessionSchema } from "./schema.js"
import { toSessionError } from "./to-session-error.js"
import { Token } from "../util/token.js"
@@ -69,14 +70,13 @@ type Dependencies = {
readonly llm: {
readonly stream: (request: LLMRequest, options?: StreamOptions) => Stream.Stream<LLMEvent, AIError>
}
readonly models: SessionRunnerModel.Interface
readonly modelRequests: SessionModelRequest.Interface
}
export type AutoInput = {
readonly session: SessionSchema.Info
readonly messages: readonly SessionMessage.Info[]
readonly resolved: SessionRunnerModel.Resolved
readonly prepare: SessionModelRequest.Interface["prepare"]
}
type RequiredInput = Pick<AutoInput, "messages" | "resolved">
@@ -86,6 +86,9 @@ export type ManualInput = {
readonly messages: readonly SessionMessage.Info[]
readonly inputID: SessionMessage.ID
readonly started?: boolean
/** Invoked after content planning, not when the caller captures the operation. */
readonly resolveModel: SessionContext.Interface["resolveModel"]
readonly prepare: SessionModelRequest.Interface["prepare"]
}
type Plan = {
@@ -96,6 +99,7 @@ type Plan = {
readonly recent: string
readonly inputID?: SessionMessage.ID
readonly started?: boolean
readonly prepare: SessionModelRequest.Interface["prepare"]
}
export type Outcome =
@@ -278,7 +282,7 @@ const make = (dependencies: Dependencies) => {
})
: Effect.void,
)
const prepared = yield* dependencies.modelRequests.prepare({
const prepared = yield* plan.prepare({
scope: { session: plan.session, agentID: Agent.ID.make("compaction"), model: plan.resolved },
transcript: { system: [], messages: [Message.user(plan.prompt)] },
contextHooks: false,
@@ -348,6 +352,7 @@ const make = (dependencies: Dependencies) => {
return yield* execute({
session: input.session,
resolved: input.resolved,
prepare: input.prepare,
reason: "auto",
...content,
})
@@ -387,7 +392,7 @@ const make = (dependencies: Dependencies) => {
error: { type: "compaction.unavailable", message: "Nothing to compact yet" },
inputID: input.inputID,
})
const resolved = yield* dependencies.models.resolve(input.session).pipe(
const resolved = yield* input.resolveModel(input.session).pipe(
Effect.catch((cause) =>
failed({
sessionID: input.session.id,
@@ -401,6 +406,7 @@ const make = (dependencies: Dependencies) => {
return yield* execute({
session: input.session,
resolved,
prepare: input.prepare,
reason: "manual",
inputID: input.inputID,
started: input.started,
@@ -422,14 +428,12 @@ export const layer = Layer.effect(
Effect.gen(function* () {
const bus = yield* Bus.Service
const llm = yield* LLMClient.Service
const models = yield* SessionRunnerModel.Service
const modelRequests = yield* SessionModelRequest.Service
return make({ bus, llm, models, modelRequests })
return make({ bus, llm })
}),
)
export const node = makeLocationNode({
service: Service,
layer,
deps: [Bus.node, llmClient, SessionRunnerModel.node, SessionModelRequest.node],
deps: [Bus.node, llmClient],
})
+61 -10
View File
@@ -2,6 +2,7 @@ export * as SessionContext from "./context.js"
import { Context, Effect, Layer } from "effect"
import { Agent } from "../agent.js"
import { Catalog } from "../catalog.js"
import { CodeModeInstructions } from "../codemode/instructions.js"
import { Database } from "../database/database.js"
import { makeLocationNode } from "@opencode-ai/util/effect/app-node"
@@ -9,8 +10,9 @@ import { InstructionDiscovery } from "../instruction-discovery.js"
import { Instructions } from "../instructions/index.js"
import { InstructionBuiltIns } from "../instructions/builtins.js"
import { Location } from "../location.js"
import { MCPInstructions } from "../mcp/instructions.js"
import { MCPTool } from "../tool/mcp.js"
import { McpInstructions } from "../mcp/instructions.js"
import { McpTool } from "../tool/mcp.js"
import { Model } from "../model.js"
import { PluginSupervisor } from "../plugin/supervisor.js"
import { ReferenceInstructions } from "../reference/instructions.js"
import { SkillInstructions } from "../skill/instructions.js"
@@ -19,6 +21,7 @@ import { AgentNotFoundError } from "./error.js"
import { SessionHistory } from "./history.js"
import { InstructionEntry } from "./instruction-entry.js"
import { SessionMessage } from "./message.js"
import { SessionModelRequest } from "./model-request.js"
import { SessionRunnerModel } from "./runner/model.js"
import { SessionSchema } from "./schema.js"
import { SessionStore } from "./store.js"
@@ -42,14 +45,27 @@ export interface Loaded {
/**
* Resolves model-request state in two phases: `select` fixes the Session,
* agent, instruction sources, and tool snapshot; `load` adds the model and
* active history for that selection. This module does not build or execute the
* model request.
* active history for that selection. Auxiliary operations resolve only the
* capabilities they need; request preparation stays separate from selection.
*/
export interface Interface {
/** Selects the Session, agent, instructions, and tools used by subsequent work. */
readonly select: (sessionID: SessionSchema.ID) => Effect.Effect<Selection, AgentNotFoundError>
/** Resolves the model and active history for that selection. */
readonly load: (selection: Selection) => Effect.Effect<Loaded, SessionRunnerModel.Error>
readonly resolveModel: (
session: SessionSchema.Info,
) => Effect.Effect<SessionRunnerModel.Resolved, SessionRunnerModel.Error>
/** Selects auxiliary title capabilities without instruction or tool preflight. */
readonly selectTitle: (session: SessionSchema.Info) => Effect.Effect<
| {
readonly agent: Agent.Info
readonly primary: SessionRunnerModel.Resolved | undefined
readonly selected: SessionRunnerModel.Resolved
}
| undefined
>
readonly prepare: SessionModelRequest.Interface["prepare"]
}
/** Location-scoped model-context loader for durable Session Steps. */
@@ -60,19 +76,49 @@ const layer = Layer.effect(
Effect.gen(function* () {
const agents = yield* Agent.Service
const builtins = yield* InstructionBuiltIns.Service
const catalog = yield* Catalog.Service
const db = (yield* Database.Service).db
const discovery = yield* InstructionDiscovery.Service
const entries = yield* InstructionEntry.Service
const location = yield* Location.Service
const mcpInstructions = yield* MCPInstructions.Service
const mcpTools = yield* MCPTool.Service
const mcpInstructions = yield* McpInstructions.Service
const mcpTools = yield* McpTool.Service
const models = yield* SessionRunnerModel.Service
const modelRequests = yield* SessionModelRequest.Service
const plugins = yield* PluginSupervisor.Service
const referenceInstructions = yield* ReferenceInstructions.Service
const skillInstructions = yield* SkillInstructions.Service
const store = yield* SessionStore.Service
const registry = yield* Tool.Service
const resolveModel = (session: SessionSchema.Info) => models.resolve(session, catalog.model.available)
const selectTitle = Effect.fn("SessionContext.selectTitle")(function* (session: SessionSchema.Info) {
const agent = yield* agents.get(Agent.ID.make("title"))
if (!agent) return
const primary = yield* resolveModel(session).pipe(Effect.orElseSucceed(() => undefined))
const info = yield* Effect.gen(function* () {
if (agent.model) return yield* catalog.model.get(agent.model.providerID, agent.model.id)
if (!primary) return
return yield* catalog.model.small(primary.ref.providerID)
})
const variant =
agent.model?.variant ?? MINIMAL_REASONING_VARIANTS.find((id) => info?.variants.some((item) => item.id === id))
const preferred =
info &&
(yield* resolveModel({
...session,
model: Model.Ref.make({
providerID: info.providerID,
id: info.id,
...(variant ? { variant } : {}),
}),
}).pipe(Effect.orElseSucceed(() => undefined)))
const selected = preferred ?? primary
if (!selected) return
return { agent, primary, selected }
})
const select = Effect.fn("SessionContext.select")(function* (sessionID: SessionSchema.ID) {
const session = yield* store.get(sessionID)
if (!session) return yield* Effect.die(new Error(`Session not found: ${sessionID}`))
@@ -112,7 +158,7 @@ const layer = Layer.effect(
})
const load = Effect.fn("SessionContext.load")(function* (selection: Selection) {
const model = yield* models.resolve(selection.session)
const model = yield* resolveModel(selection.session)
const history = yield* SessionHistory.entriesForRunner(db, selection.session.id, selection.instructions)
return {
session: selection.session,
@@ -124,25 +170,30 @@ const layer = Layer.effect(
}
})
return Service.of({ select, load })
return Service.of({ select, load, resolveModel, selectTitle, prepare: modelRequests.prepare })
}),
)
/** Variant IDs that minimize reasoning output, in preference order. */
const MINIMAL_REASONING_VARIANTS = ["none", "minimal", "low"].map((id) => Model.VariantID.make(id))
export const node = makeLocationNode({
service: Service,
layer,
deps: [
Agent.node,
Catalog.node,
Database.node,
InstructionBuiltIns.node,
InstructionDiscovery.node,
InstructionEntry.node,
Location.node,
MCPInstructions.node,
MCPTool.node,
McpInstructions.node,
McpTool.node,
PluginSupervisor.node,
ReferenceInstructions.node,
SessionRunnerModel.node,
SessionModelRequest.node,
SessionStore.node,
SkillInstructions.node,
Tool.node,
+3 -6
View File
@@ -9,7 +9,6 @@ import { SessionContext } from "./context.js"
import { SessionGenerate } from "./generate.js"
import { SessionHistory } from "./history.js"
import { SessionModelRequest } from "./model-request.js"
import { SessionRunnerModel } from "./runner/model.js"
export const layer = Layer.effect(
SessionGenerate.Service,
@@ -17,13 +16,11 @@ export const layer = Layer.effect(
const context = yield* SessionContext.Service
const database = yield* Database.Service
const llm = yield* LLMClient.Service
const models = yield* SessionRunnerModel.Service
const modelRequests = yield* SessionModelRequest.Service
return SessionGenerate.Service.of({
generate: Effect.fn("SessionGenerate.generate")(function* (input) {
const selection = yield* context.select(input.sessionID)
const model = yield* models.resolve(selection.session)
const model = yield* context.resolveModel(selection.session)
const history = yield* SessionHistory.preview(database.db, selection.session.id, selection.instructions)
const transcript = SessionModelRequest.baseTranscript({
agent: selection.agent.info,
@@ -32,7 +29,7 @@ export const layer = Layer.effect(
initial: history.initial,
messages: history.messages,
})
const prepared = yield* modelRequests.prepare({
const prepared = yield* context.prepare({
scope: { session: selection.session, agentID: selection.agent.id, model, tools: selection.tools },
transcript: {
system: transcript.system,
@@ -59,5 +56,5 @@ export const layer = Layer.effect(
export const node = makeLocationNode({
service: SessionGenerate.Service,
layer,
deps: [SessionContext.node, Database.node, SessionModelRequest.node, SessionRunnerModel.node, llmClient],
deps: [SessionContext.node, Database.node, llmClient],
})
+19 -7
View File
@@ -134,6 +134,23 @@ const promotedFromMessage = Effect.fn("SessionInbox.promotedFromMessage")(functi
return yield* Effect.die(new LifecycleConflict({ id }))
})
/** Reconciles pending or delivered work without preparing a new admission payload. */
export const reconcile = Effect.fn("SessionInbox.reconcile")(function* (
db: DatabaseService,
request: {
readonly id: SessionMessage.ID
readonly sessionID: SessionSchema.ID
readonly delivery: Delivery
},
) {
const existing = yield* find(db, request.id)
if (existing !== undefined) {
if (existing.type === "compaction") return yield* Effect.die(new LifecycleConflict({ id: request.id }))
return existing
}
return yield* promotedFromMessage(db, request.sessionID, request.id, request.delivery)
})
export const admit = Effect.fn("SessionInbox.admit")(function* (
db: DatabaseService,
bus: Bus.Interface,
@@ -143,13 +160,8 @@ export const admit = Effect.fn("SessionInbox.admit")(function* (
readonly item: Item
},
) {
const existing = yield* find(db, request.id)
if (existing !== undefined) {
if (existing.type === "compaction") return yield* Effect.die(new LifecycleConflict({ id: request.id }))
return existing
}
const promoted = yield* promotedFromMessage(db, request.sessionID, request.id, request.item.delivery)
if (promoted !== undefined) return promoted
const existing = yield* reconcile(db, { ...request, delivery: request.item.delivery })
if (existing !== undefined) return existing
return yield* bus
.publish(SessionEvent.InboxEnqueued, {
inboxID: request.id,
+16 -19
View File
@@ -297,17 +297,17 @@ export const layer = Layer.effect(
)
// Hooks mutate this record in place: edit descriptions and schemas, rename, or remove.
const definitions = Object.fromEntries(Array.from(given, ([definition, tool]) => [tool.name, definition]))
const context =
input.contextHooks === false
? { system: input.transcript.system, messages: input.transcript.messages, tools: definitions }
: yield* hooks.trigger("session", "context", {
sessionID: session.id,
agent: input.scope.agentID,
model: resolved.ref,
system: input.transcript.system,
messages: input.transcript.messages,
tools: definitions,
})
const context: PluginHooks.Domains["session"]["context"] = {
sessionID: session.id,
agent: input.scope.agentID,
model: resolved.ref,
system: input.transcript.system,
messages: input.transcript.messages,
tools: definitions,
generation: {},
providerOptions: {},
}
if (input.contextHooks !== false) yield* hooks.trigger("session", "context", context)
// Match each surviving entry back to its tool, by recognizing a moved definition or
// by key. Identity wins so a definition moved onto another tool's name still executes
// the tool it describes. Entries matching neither were invented by a hook and dropped.
@@ -333,6 +333,8 @@ export const layer = Layer.effect(
messages: boundImages(unsupportedParts(context.messages, resolved.capabilities)),
tools: Array.from(hooked, ([name, tool]) => ({ ...tool, name })),
toolChoice: input.toolChoice,
generation: Object.keys(context.generation).length === 0 ? undefined : context.generation,
providerOptions: Object.keys(context.providerOptions).length === 0 ? undefined : context.providerOptions,
}),
)
const hasHttpHooks =
@@ -358,15 +360,10 @@ export const layer = Layer.effect(
? { webSocket: transport.bind(session.id) }
: {}),
}
const executeTool: Prepared["executeTool"] = (input) => {
const tool = hooked.get(input.call.name)
// A registered tool absent from the hooked set was removed or renamed by a hook.
if (!tool && registry.has(input.call.name))
return new Tool.Error({ message: `Tool is not available for this request: ${input.call.name}` })
return tools
.execute(tool ? { ...input, call: { ...input.call, name: tool.name } } : input)
const executeTool: Prepared["executeTool"] = (input) =>
tools
.execute({ ...input, definitions: hooked })
.pipe(Effect.catchCauseFilter(declineDefect, (decline) => Effect.fail(decline)))
}
return {
request,
options,
+9 -4
View File
@@ -36,7 +36,6 @@ const layer = Layer.effect(
const bus = yield* Bus.Service
const store = yield* SessionStore.Service
const context = yield* SessionContext.Service
const modelRequests = yield* SessionModelRequest.Service
const modelTransport = yield* SessionModelTransport.Service
const db = (yield* Database.Service).db
const compaction = yield* SessionCompaction.Service
@@ -142,6 +141,8 @@ const layer = Layer.effect(
Effect.gen(function* () {
return yield* compaction.compactManual({
session,
resolveModel: context.resolveModel,
prepare: context.prepare,
messages: yield* store.context(sessionID),
inputID: pending.id,
started: true,
@@ -215,7 +216,12 @@ const layer = Layer.effect(
// Reuse boundary preparation once; retries refresh context without delivering more input.
const loaded = initial ?? (yield* prepareContext(sessionID).pipe(Effect.flatMap(context.load)))
initial = undefined
const compactionInput = { session: loaded.session, messages: loaded.messages, resolved: loaded.model }
const compactionInput = {
session: loaded.session,
messages: loaded.messages,
resolved: loaded.model,
prepare: context.prepare,
}
if (compaction.required(compactionInput)) {
const compacted = yield* compaction.compact(compactionInput)
if (compacted.status !== "completed") return yield* new StepFailedError({ error: compacted.error })
@@ -230,7 +236,7 @@ const layer = Layer.effect(
initial: loaded.initial,
messages: loaded.messages,
})
const prepared = yield* modelRequests.prepare({
const prepared = yield* context.prepare({
scope: { session: loaded.session, agentID: loaded.agent.id, model: loaded.model, tools: loaded.tools },
transcript: {
system: transcript.system,
@@ -319,7 +325,6 @@ export const node = makeLocationNode({
Bus.node,
llmClient,
SessionContext.node,
SessionModelRequest.node,
SessionModelTransport.node,
SessionStore.node,
SessionCompaction.node,
+8 -6
View File
@@ -3,7 +3,6 @@ export * as SessionRunnerModel from "./model.js"
import { makeLocationNode } from "@opencode-ai/util/effect/app-node"
import { LanguageModel } from "@opencode-ai/ai"
import { Context, Effect, Layer, Schema } from "effect"
import { Catalog } from "../../catalog.js"
import { ModelResolver } from "../../model-resolver.js"
import { Capabilities, ID, Info, Ref, VariantID } from "../../model.js"
import { Provider } from "../../provider.js"
@@ -41,7 +40,11 @@ export type Error = ModelNotSelectedError | ModelUnavailableError | ModelResolve
export type Resolved = ModelResolver.Resolved
export interface Interface {
readonly resolve: (session: SessionSchema.Info) => Effect.Effect<Resolved, Error>
/** Availability is sampled lazily for each explicitly selected model resolution. */
readonly resolve: (
session: SessionSchema.Info,
available: () => Effect.Effect<ReadonlyArray<Info>>,
) => Effect.Effect<Resolved, Error>
}
export class Service extends Context.Service<Service, Interface>()("@opencode/SessionRunnerModel") {}
@@ -70,17 +73,16 @@ export const resolved = (
const layer = Layer.effect(
Service,
Effect.gen(function* () {
const catalog = yield* Catalog.Service
const resolver = yield* ModelResolver.Service
return Service.of({
resolve: Effect.fn("SessionRunnerModel.resolve")(function* (session) {
resolve: Effect.fn("SessionRunnerModel.resolve")(function* (session, available) {
// Location plugins populate and filter the catalog asynchronously during layer startup.
if (!session.model) {
const resolved = yield* resolver.resolve()
if (resolved) return resolved
return yield* new ModelNotSelectedError({ sessionID: session.id })
}
const selected = (yield* catalog.model.available()).find(
const selected = (yield* available()).find(
(model) => model.providerID === session.model?.providerID && model.id === session.model.id,
)
if (!selected)
@@ -94,4 +96,4 @@ const layer = Layer.effect(
}),
)
export const node = makeLocationNode({ service: Service, layer, deps: [Catalog.node, ModelResolver.node] })
export const node = makeLocationNode({ service: Service, layer, deps: [ModelResolver.node] })
+13 -55
View File
@@ -4,18 +4,16 @@ import { isDeepStrictEqual } from "node:util"
import { LLMClient, AIError, LLMEvent, Message, SystemPart, type LLMRequest } from "@opencode-ai/ai"
import type { StreamOptions } from "@opencode-ai/ai/route"
import { Context, DateTime, Effect, Layer, Stream } from "effect"
import { Agent } from "../agent.js"
import { Catalog } from "../catalog.js"
import type { Agent } from "../agent.js"
import { Database } from "../database/database.js"
import { Bus } from "../bus.js"
import { makeLocationNode } from "@opencode-ai/util/effect/app-node"
import { isExactRootFallback } from "@opencode-ai/util/session-title-fallback"
import { llmClient } from "../effect/app-node-platform.js"
import { Model } from "../model.js"
import { SessionContext } from "./context.js"
import { SessionEvent } from "./event.js"
import { SessionHistory } from "./history.js"
import { SessionModelRequest } from "./model-request.js"
import { SessionRunnerModel } from "./runner/model.js"
import type { SessionRunnerModel } from "./runner/model.js"
import { SessionSchema } from "./schema.js"
import { SessionUsage } from "./usage.js"
import { SessionStore } from "./store.js"
@@ -30,10 +28,7 @@ type Dependencies = {
readonly llm: {
readonly stream: (request: LLMRequest, options?: StreamOptions) => Stream.Stream<LLMEvent, AIError>
}
readonly agents: Agent.Interface
readonly catalog: Catalog.Interface
readonly models: SessionRunnerModel.Interface
readonly modelRequests: SessionModelRequest.Interface
readonly context: SessionContext.Interface
readonly store: SessionStore.Interface
}
@@ -72,7 +67,7 @@ const attempt = Effect.fn("SessionTitle.attempt")(function* (
})
: Effect.void,
)
const prepared = yield* dependencies.modelRequests.prepare({
const prepared = yield* dependencies.context.prepare({
scope: { session: input.session, agentID: input.agent.id, model: input.model },
transcript: {
system: input.agent.system ? [SystemPart.make(input.agent.system)] : [],
@@ -106,9 +101,6 @@ const attempt = Effect.fn("SessionTitle.attempt")(function* (
.find((line) => line.length > 0)
})
/** Variant IDs that minimize reasoning output, in preference order. */
const MINIMAL_REASONING_VARIANTS = ["none", "minimal", "low"].map((id) => Model.VariantID.make(id))
const make = (dependencies: Dependencies) => {
const generate = Effect.fn("SessionTitle.generate")(function* (
db: Database.Interface["db"],
@@ -140,34 +132,12 @@ const make = (dependencies: Dependencies) => {
Effect.orElseSucceed(() => firstUser.text),
)
: firstUser.text
const agent = yield* dependencies.agents.get(Agent.ID.make("title"))
if (!agent) return
const primary = yield* dependencies.models.resolve(session).pipe(Effect.orElseSucceed(() => undefined))
const info = yield* Effect.gen(function* () {
if (agent.model) return yield* dependencies.catalog.model.get(agent.model.providerID, agent.model.id)
if (!primary) return
return yield* dependencies.catalog.model.small(primary.ref.providerID)
})
const variant =
agent.model?.variant ?? MINIMAL_REASONING_VARIANTS.find((id) => info?.variants.some((item) => item.id === id))
const preferred =
info &&
(yield* dependencies.models
.resolve({
...session,
model: Model.Ref.make({
providerID: info.providerID,
id: info.id,
...(variant ? { variant } : {}),
}),
})
.pipe(Effect.orElseSucceed(() => undefined)))
const selected = preferred ?? primary
if (!selected) return
const selection = yield* dependencies.context.selectTitle(session)
if (!selection) return
const title =
(yield* attempt(dependencies, { session, agent, text, model: selected })) ??
(primary && !isDeepStrictEqual(selected.ref, primary.ref)
? yield* attempt(dependencies, { session, agent, text, model: primary })
(yield* attempt(dependencies, { session, agent: selection.agent, text, model: selection.selected })) ??
(selection.primary && !isDeepStrictEqual(selection.selected.ref, selection.primary.ref)
? yield* attempt(dependencies, { session, agent: selection.agent, text, model: selection.primary })
: undefined)
if (!title) return
const expectedSequence = (yield* Bus.latestSequence(db, sessionID)) + 1
@@ -192,13 +162,10 @@ export const layer = Layer.effect(
Effect.gen(function* () {
const bus = yield* Bus.Service
const llm = yield* LLMClient.Service
const agents = yield* Agent.Service
const catalog = yield* Catalog.Service
const models = yield* SessionRunnerModel.Service
const modelRequests = yield* SessionModelRequest.Service
const context = yield* SessionContext.Service
const store = yield* SessionStore.Service
const database = yield* Database.Service
const title = make({ bus, llm, agents, catalog, models, modelRequests, store })
const title = make({ bus, llm, context, store })
return Service.of({
generate: (sessionID) => title.generate(database.db, sessionID),
})
@@ -208,14 +175,5 @@ export const layer = Layer.effect(
export const node = makeLocationNode({
service: Service,
layer,
deps: [
Bus.node,
llmClient,
Agent.node,
Catalog.node,
SessionRunnerModel.node,
SessionModelRequest.node,
SessionStore.node,
Database.node,
],
deps: [Bus.node, llmClient, SessionContext.node, SessionStore.node, Database.node],
})
+6 -1
View File
@@ -34,7 +34,10 @@ export interface Interface {
sessionID: Session.ID
sanitize?: boolean
}) => Effect.Effect<Data, Session.NotFoundError | Session.MessageDecodeError>
readonly import: (input: { data: Data; location: Location.Ref }) => Effect.Effect<Session.Info, ImportConflictError>
readonly import: (input: {
data: Data
location: Location.Ref
}) => Effect.Effect<Session.Info, ImportConflictError | Session.NotFoundError>
}
export class Service extends Context.Service<Service, Interface>()("@opencode/SessionTransfer") {}
@@ -66,6 +69,7 @@ const layer = Layer.effect(
.get()
.pipe(Effect.orDie)
if (recorded) return yield* new ImportConflictError({ sessionID })
if (input.data.info.parentID) yield* sessions.get(input.data.info.parentID)
const project = yield* projects.resolve(input.location.directory)
yield* upsertProject(db, project).pipe(Effect.orDie)
const messages = input.data.messages.filter(isSettled).map((message, index) => {
@@ -85,6 +89,7 @@ const layer = Layer.effect(
SessionEvent.Created,
{
sessionID,
parentID: input.data.info.parentID,
slug: Slug.create(),
version: app.version,
projectID: project.id,
+6 -1
View File
@@ -167,6 +167,11 @@ export function args(file: string, command: string) {
return ["-c", command]
}
// Resolve afresh so removing a shell does not leave terminals using a stale cached path.
export function environment(bin?: string, filter?: { compatible?: boolean }) {
return select(process.env.SHELL, undefined, filter, bin) ?? fallback(bin)
}
let defaultConfigured: { bin?: string; value: string } | undefined
let defaultCompatible: { bin?: string; value: string } | undefined
@@ -176,7 +181,7 @@ export function resolve(input: ResolveInput, configShell?: string, options?: Opt
if (options?.gitbash) return select(process.env.SHELL, options, filter, bin)
const cached = input.priority === "compat" ? defaultCompatible : defaultConfigured
if (cached && cached.bin === bin) return cached.value
const value = select(process.env.SHELL, undefined, filter, bin) ?? fallback(bin)
const value = environment(bin, filter)
if (input.priority === "compat") defaultCompatible = { bin, value }
if (input.priority === "config") defaultConfigured = { bin, value }
return value
+32 -26
View File
@@ -49,6 +49,8 @@ export interface Snapshot {
readonly messageID: SessionMessage.ID
readonly call: ToolCall
readonly progress?: (update: Tool.Metadata) => Effect.Effect<void>
/** Surviving request definitions, keyed by the names advertised after session context hooks. */
readonly definitions?: ReadonlyMap<string, ToolDefinition>
}) => Effect.Effect<Tool.Result & { readonly content: ReadonlyArray<Tool.Content> }, Tool.Error>
}
@@ -90,23 +92,23 @@ const layer = Layer.effect(
]
})
const beforeExecute = (name: string, input: unknown, context: Tool.Context) =>
hooks.trigger("tool", "execute.before", {
tool: name,
sessionID: context.sessionID,
agent: context.agent,
messageID: context.messageID,
id: context.id,
input,
})
const executeTool = Effect.fn("Tool.execute")(function* (
tool: Tool.Info,
name: string,
input: unknown,
context: Tool.Context,
) {
const beforeEvent: PluginHooks.Domains["tool"]["execute.before"] = {
tool: name,
inputSchema: definition(tool).inputSchema,
sessionID: context.sessionID,
agent: context.agent,
messageID: context.messageID,
id: context.id,
input,
}
yield* hooks.trigger("tool", "execute.before", beforeEvent)
const execution = yield* execute(tool, beforeEvent.input, context).pipe(
const execution = yield* execute(tool, input, context).pipe(
Effect.map((value) => ({ value })),
Effect.catchTag("Tool.Error", (failure) => Effect.succeed({ failure })),
)
@@ -116,7 +118,7 @@ const layer = Layer.effect(
agent: context.agent,
messageID: context.messageID,
id: context.id,
input: beforeEvent.input,
input,
}
if ("failure" in execution) {
const afterEvent: PluginHooks.Domains["tool"]["execute.after"] = {
@@ -212,7 +214,11 @@ const layer = Layer.effect(
const executeRule = rules.findLast((rule) => Wildcard.match("execute", rule.action))
const codemodeEnabled = executeRule?.resource !== "*" || executeRule.effect !== "deny"
const codemodeTool = codemodeEnabled
? CodeModeTool.create(codemode, (name, tool, input, context) => executeTool(tool, name, input, context))
? CodeModeTool.create(codemode, (name, tool, input, context) =>
beforeExecute(name, input, context).pipe(
Effect.flatMap((event) => executeTool(tool, name, event.input, context)),
),
)
: undefined
const codeModeCatalog = codemodeEnabled ? CodeModeTool.catalog(codemode) : undefined
return {
@@ -223,13 +229,7 @@ const layer = Layer.effect(
.map(([, tool]) => definition(tool)),
...(codemodeTool ? [definition(codemodeTool)] : []),
],
execute: (input: {
readonly sessionID: SessionSchema.ID
readonly agent: Agent.ID
readonly messageID: SessionMessage.ID
readonly call: ToolCall
readonly progress?: (update: Tool.Metadata) => Effect.Effect<void>
}) => {
execute: Effect.fnUntraced(function* (input: Parameters<Snapshot["execute"]>[0]) {
const context: Tool.Context = {
sessionID: input.sessionID,
agent: input.agent,
@@ -237,12 +237,18 @@ const layer = Layer.effect(
id: Tool.CallID.make(input.call.id),
progress: input.progress ?? (() => Effect.void),
}
if (input.call.name === "execute" && codemodeTool)
return executeTool(codemodeTool, input.call.name, input.call.input, context)
const tool = direct.get(input.call.name)
if (tool) return executeTool(tool, input.call.name, input.call.input, context)
return new Tool.Error({ message: `Unknown tool: ${input.call.name}` })
},
const event = yield* beforeExecute(input.call.name, input.call.input, context)
const requested = input.definitions?.get(event.tool)
// Preserve session context removal and alias resolution, now after the repair hook.
if (!requested && input.definitions && (direct.has(event.tool) || codemodeTool?.name === event.tool))
return yield* new Tool.Error({ message: `Tool is not available for this request: ${event.tool}` })
const name = requested?.name ?? event.tool
if (name === "execute" && codemodeTool)
return yield* executeTool(codemodeTool, name, event.input, context)
const tool = direct.get(name)
if (tool) return yield* executeTool(tool, name, event.input, context)
return yield* new Tool.Error({ message: `Unknown tool: ${name}` })
}),
}
}),
),
+1 -1
View File
@@ -1,4 +1,4 @@
export * as MCPTool from "./mcp.js"
export * as McpTool from "./mcp.js"
import { ToolFailure } from "@opencode-ai/ai"
import { McpEvent } from "@opencode-ai/schema/mcp-event"
+5 -6
View File
@@ -19,9 +19,8 @@ import { ToolOutput } from "../../tool-output.js"
export const name = "shell"
export const DEFAULT_TIMEOUT_MS = 2 * 60 * 1_000
const BACKGROUND_STARTED = "The command was moved to the background."
const BACKGROUND_INSTRUCTION =
"You will be notified automatically when the command finishes. DO NOT sleep, poll, or proactively check on its progress."
"You will be notified automatically when the command finishes. Avoid sleep commands or polling for completion; if you need the output before then, read the file directly."
const OS =
process.platform === "darwin"
? "macOS"
@@ -95,8 +94,8 @@ const toolResult = (output: Output) => {
}
}
const backgroundResult = (shellID: string) => ({
output: BACKGROUND_STARTED,
const backgroundResult = (shellID: string, file: string) => ({
output: `Command moved to the background (shell ID: ${shellID}).\nOutput is streaming to: ${file}`,
shellID,
truncated: false,
status: "running" as const,
@@ -295,7 +294,7 @@ export const Plugin = {
if (input.background === true) {
yield* runtime.job.background(job.id)
yield* notifyWhenDone(context.sessionID, context.id, info.id, info.command, settled)
return backgroundResult(info.id)
return backgroundResult(info.id, info.file)
}
const result = yield* runtime.job
@@ -304,7 +303,7 @@ export const Plugin = {
if (result?.type === "backgrounded") {
yield* shell.timeout(info.id, 0)
yield* notifyWhenDone(context.sessionID, context.id, info.id, info.command, settled)
return backgroundResult(info.id)
return backgroundResult(info.id, info.file)
}
if (result?.info.status === "error")
return yield* Effect.fail(new Error(result.info.error ?? "Command failed"))
+5 -7
View File
@@ -9,6 +9,7 @@ import { llmClient } from "@opencode-ai/core/effect/app-node-platform"
import { SessionCompaction } from "@opencode-ai/core/session/compaction"
import { SessionEvent } from "@opencode-ai/core/session/event"
import { SessionMessage } from "@opencode-ai/core/session/message"
import { SessionModelRequest } from "@opencode-ai/core/session/model-request"
import { SessionRunnerModel } from "@opencode-ai/core/session/runner/model"
import { Session } from "@opencode-ai/core/session"
import { Agent } from "@opencode-ai/core/agent"
@@ -38,19 +39,13 @@ const config = Config.testLayer()
const it = testEffect(
Layer.merge(
config,
AppNodeBuilder.build(LayerNode.group([SessionCompaction.node, Config.node, Bus.node]), [
AppNodeBuilder.build(LayerNode.group([SessionCompaction.node, SessionModelRequest.node, Config.node, Bus.node]), [
[
llmClient,
Layer.mock(LLMClient.Service)({
stream: () => Stream.make(LLMEvent.textDelta({ id: "summary", text: "summary" })),
}),
],
[
SessionRunnerModel.node,
Layer.mock(SessionRunnerModel.Service)({
resolve: () => Effect.succeed(resolved),
}),
],
[Config.node, config],
]),
),
@@ -59,6 +54,7 @@ describe("ConfigCompactionPlugin.Plugin", () => {
it.live("merges settings and reloads changed config", () =>
Effect.gen(function* () {
const compaction = yield* SessionCompaction.Service
const modelRequests = yield* SessionModelRequest.Service
const config = yield* Config.Test
const bus = yield* Bus.Service
yield* config.setEntries([
@@ -85,6 +81,8 @@ describe("ConfigCompactionPlugin.Plugin", () => {
expect(
yield* compaction.compactManual({
session,
resolveModel: () => Effect.succeed(resolved),
prepare: modelRequests.prepare,
messages: [
{
id: SessionMessage.ID.create(),
@@ -0,0 +1,18 @@
import { LocationServiceMap } from "@opencode-ai/core/location-service-map"
import type { LocationServices } from "@opencode-ai/core/location-services"
import { PluginHooks } from "@opencode-ai/core/plugin/hooks"
import { PluginSupervisor } from "@opencode-ai/core/plugin/supervisor-service"
import { LayerNode } from "@opencode-ai/util/effect/layer-node"
import { Effect, Layer, LayerMap } from "effect"
// Plain-prompt unit fixtures use virtual directories and need only the admission hook services.
export const promptLocationLayer = Layer.effect(
LocationServiceMap.Service,
LayerMap.make(
() =>
Layer.merge(
LayerNode.compile(PluginHooks.node),
Layer.succeed(PluginSupervisor.Service, { flush: Effect.void }),
) as Layer.Layer<LocationServices>,
),
)
+11
View File
@@ -51,6 +51,8 @@ describe("KV", () => {
entries: [{ key: `${prefix}éclair`, value: { order: 3 } }],
})
expect(yield* kv.scan({ prefix: `${prefix}%_` })).toEqual({ entries: [] })
expect(yield* kv.scanAll(`${prefix}%_`)).toEqual([])
expect(yield* kv.scanAll(prefix)).toEqual([...first.entries, { key: `${prefix}éclair`, value: { order: 3 } }])
}),
)
@@ -76,6 +78,15 @@ describe("KV", () => {
expect((yield* kv.scan({ prefix, limit: 0 })).entries).toHaveLength(1)
expect((yield* kv.scan({ prefix, limit: -10 })).entries).toHaveLength(1)
expect((yield* kv.scan({ prefix, limit: Number.NaN })).entries).toHaveLength(100)
const all = kv.scanAll(prefix)
const entries = Array.from({ length: 1001 }, (_, index) => {
const key = `${prefix}${index.toString().padStart(4, "0")}`
return { key, value: key }
})
expect(yield* all).toEqual(entries)
yield* kv.remove(`${prefix}0000`)
expect(yield* all).toEqual(entries.slice(1))
}),
)
})
+26
View File
@@ -0,0 +1,26 @@
export * as Expected from "./session-message.js"
// Partial expected values, not input fixtures. Keep each assertion's matcher and fields explicit.
export const user = <Text>(text: Text) => ({ type: "user" as const, text })
export const text = <Text>(text: Text) => ({ type: "text" as const, text })
export const reasoning = <Text>(text: Text) => ({ type: "reasoning" as const, text })
export const assistant = <const Fields extends object, Content>(fields: Fields, content: Content) => ({
...fields,
type: "assistant" as const,
content,
})
export const completedTool = <Identity extends object, Fields extends object>(identity: Identity, fields: Fields) => ({
...identity,
type: "tool" as const,
state: { ...fields, status: "completed" as const },
})
export const failedTool = <Identity extends object, Fields extends object>(identity: Identity, fields: Fields) => ({
...identity,
type: "tool" as const,
state: { ...fields, status: "error" as const },
})
+15 -8
View File
@@ -797,8 +797,10 @@ describe("LocationServiceMap", () => {
}),
),
)
const failure = yield* SessionRunnerModel.Service.use((models) =>
models.resolve(
const failure = yield* Effect.gen(function* () {
const catalog = yield* Catalog.Service
const models = yield* SessionRunnerModel.Service
return yield* models.resolve(
Session.Info.make({
id: Session.ID.make("ses_unavailable_model"),
projectID: Project.ID.global,
@@ -812,8 +814,9 @@ describe("LocationServiceMap", () => {
time: { created: DateTime.makeUnsafe(0), updated: DateTime.makeUnsafe(0) },
location,
}),
),
).pipe(Effect.provide(LocationServiceMap.Service.get(location)), Effect.flip)
catalog.model.available,
)
}).pipe(Effect.provide(LocationServiceMap.Service.get(location)), Effect.flip)
expect(failure).toMatchObject({
_tag: "SessionRunnerModel.ModelUnavailableError",
@@ -837,8 +840,10 @@ describe("LocationServiceMap", () => {
["azure-cognitive-services", "azure"],
["google-vertex-anthropic", "google-vertex"],
] as const) {
const failure = yield* SessionRunnerModel.Service.use((models) =>
models.resolve(
const failure = yield* Effect.gen(function* () {
const catalog = yield* Catalog.Service
const models = yield* SessionRunnerModel.Service
return yield* models.resolve(
Session.Info.make({
id: Session.ID.make(`ses_removed_${providerID}`),
projectID: Project.ID.global,
@@ -852,8 +857,9 @@ describe("LocationServiceMap", () => {
time: { created: DateTime.makeUnsafe(0), updated: DateTime.makeUnsafe(0) },
location,
}),
),
).pipe(Effect.provide(LocationServiceMap.Service.get(location)), Effect.flip)
catalog.model.available,
)
}).pipe(Effect.provide(LocationServiceMap.Service.get(location)), Effect.flip)
expect(failure).toMatchObject({
_tag: "SessionRunnerModel.ModelUnavailableError",
@@ -905,6 +911,7 @@ describe("LocationServiceMap", () => {
time: { created: DateTime.makeUnsafe(0), updated: DateTime.makeUnsafe(0) },
location,
}),
catalog.model.available,
)
}).pipe(Effect.provide(LocationServiceMap.Service.get(location)))
+11 -11
View File
@@ -3,9 +3,9 @@ import { Effect, Layer } from "effect"
import { Agent } from "@opencode-ai/core/agent"
import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
import { MCP } from "@opencode-ai/core/mcp/index"
import { MCPInstructions } from "@opencode-ai/core/mcp/instructions"
import { McpInstructions } from "@opencode-ai/core/mcp/instructions"
import { Permission } from "@opencode-ai/core/permission"
import { MCPTool } from "@opencode-ai/core/tool/mcp"
import { McpTool } from "@opencode-ai/core/tool/mcp"
import { it } from "./lib/effect"
import { readInitial, readUpdate } from "./lib/instructions"
@@ -22,7 +22,7 @@ const instructions = (server: string, text: string) =>
const tool = (server: string, name = "search") => new MCP.Tool({ server: MCP.ServerName.make(server), name })
const layer = (catalog: () => MCP.ServerInstructions[], tools: () => MCP.Tool[]) =>
AppNodeBuilder.build(MCPInstructions.node, [
AppNodeBuilder.build(McpInstructions.node, [
[
MCP.node,
Layer.mock(MCP.Service, {
@@ -32,15 +32,15 @@ const layer = (catalog: () => MCP.ServerInstructions[], tools: () => MCP.Tool[])
],
])
describe("MCPInstructions", () => {
describe("McpInstructions", () => {
it.effect("renders instructions for servers with at least one permitted tool", () =>
Effect.gen(function* () {
const service = yield* MCPInstructions.Service
const service = yield* McpInstructions.Service
const generation = yield* service
.load(
selection([
{ action: MCPTool.name("alpha", "restricted"), resource: "*", effect: "deny" },
{ action: MCPTool.name("hidden", "search"), resource: "*", effect: "deny" },
{ action: McpTool.name("alpha", "restricted"), resource: "*", effect: "deny" },
{ action: McpTool.name("hidden", "search"), resource: "*", effect: "deny" },
]),
)
.pipe(Effect.flatMap(readInitial))
@@ -77,7 +77,7 @@ describe("MCPInstructions", () => {
it.effect("omits instructions when the agent cannot use execute", () =>
Effect.gen(function* () {
const service = yield* MCPInstructions.Service
const service = yield* McpInstructions.Service
const generation = yield* service
.load(selection([{ action: "execute", resource: "*", effect: "deny" }]))
.pipe(Effect.flatMap(readInitial))
@@ -95,7 +95,7 @@ describe("MCPInstructions", () => {
it.effect("keeps MCP instructions when Code Mode is disabled and execute is denied", () =>
Effect.gen(function* () {
const service = yield* MCPInstructions.Service
const service = yield* McpInstructions.Service
const generation = yield* service
.load(selection([{ action: "execute", resource: "*", effect: "deny" }]))
.pipe(Effect.flatMap(readInitial))
@@ -122,7 +122,7 @@ describe("MCPInstructions", () => {
it.effect("restates guidance when Code Mode is disabled for a server", () => {
let tools = [tool("alpha")]
return Effect.gen(function* () {
const service = yield* MCPInstructions.Service
const service = yield* McpInstructions.Service
const initialized = yield* service.load(selection()).pipe(Effect.flatMap(readInitial))
tools = [new MCP.Tool({ server: MCP.ServerName.make("alpha"), name: "search", codemode: false })]
@@ -151,7 +151,7 @@ describe("MCPInstructions", () => {
let catalog = [instructions("alpha", "Alpha instructions")]
const tools = [tool("alpha"), tool("beta")]
return Effect.gen(function* () {
const service = yield* MCPInstructions.Service
const service = yield* McpInstructions.Service
const initialized = yield* service.load(selection()).pipe(Effect.flatMap(readInitial))
catalog = [instructions("alpha", "Alpha instructions"), instructions("beta", "Beta instructions")]
+8 -8
View File
@@ -33,7 +33,7 @@ import { MCPStdio } from "@opencode-ai/core/mcp/stdio"
import { Permission } from "@opencode-ai/core/permission"
import { AbsolutePath } from "@opencode-ai/core/schema"
import { Session } from "@opencode-ai/core/session"
import { MCPTool } from "@opencode-ai/core/tool/mcp"
import { McpTool } from "@opencode-ai/core/tool/mcp"
import { Tool } from "@opencode-ai/core/tool"
import { DateTime, Deferred, Effect, Exit, Fiber, Layer, PubSub, Ref, Schedule, Schema, Sink, Stream } from "effect"
import { TestClock } from "effect/testing"
@@ -351,7 +351,7 @@ const permissions = Layer.mock(Permission.Service, {
})
const events = Layer.mock(Bus.Service, { subscribe: () => Stream.never })
const it = testEffect(
AppNodeBuilder.build(LayerNode.group([Tool.node, MCPTool.node]), [
AppNodeBuilder.build(LayerNode.group([Tool.node, McpTool.node]), [
[MCP.node, mcp],
[Permission.node, permissions],
[Bus.node, events],
@@ -371,8 +371,8 @@ describe("MCP errors", () => {
})
test("MCP tool names match V1 sanitization", () => {
expect(MCPTool.namespace("context 7")).toBe("context_7")
expect(MCPTool.name("context 7", "resolve.library/id")).toBe("context_7_resolve_library_id")
expect(McpTool.namespace("context 7")).toBe("context_7")
expect(McpTool.name("context 7", "resolve.library/id")).toBe("context_7_resolve_library_id")
})
test("preserves output schema validation across paginated tool discovery", async () => {
@@ -1298,7 +1298,7 @@ testEffect(Layer.empty).live("isolates invalid MCP tools and preserves plugin tr
yield* Effect.gen(function* () {
const registry = yield* Tool.Service
const registration = yield* MCPTool.Service
const registration = yield* McpTool.Service
const bus = yield* Bus.Service
yield* registration.flush
expect((yield* toolDefinitions(registry)).map((tool) => tool.name)).toEqual([
@@ -1408,7 +1408,7 @@ testEffect(Layer.empty).live("isolates invalid MCP tools and preserves plugin tr
}).pipe(
Effect.provide(
Layer.fresh(
AppNodeBuilder.build(LayerNode.group([Tool.node, MCPTool.node, Bus.node]), [
AppNodeBuilder.build(LayerNode.group([Tool.node, McpTool.node, Bus.node]), [
[
MCP.node,
Layer.mock(MCP.Service, {
@@ -1437,7 +1437,7 @@ testEffect(Layer.empty).effect("coalesces queued MCP tool notifications after in
let reads = 0
return Effect.gen(function* () {
const registry = yield* Tool.Service
const registration = yield* MCPTool.Service
const registration = yield* McpTool.Service
const bus = yield* Bus.Service
yield* registration.flush
expect(reads).toBe(1)
@@ -1451,7 +1451,7 @@ testEffect(Layer.empty).effect("coalesces queued MCP tool notifications after in
expect((yield* toolDefinitions(registry)).map((tool) => tool.name)).toEqual(["demo_read_3", "execute"])
}).pipe(
Effect.provide(
AppNodeBuilder.build(LayerNode.group([Tool.node, MCPTool.node, Bus.node]), [
AppNodeBuilder.build(LayerNode.group([Tool.node, McpTool.node, Bus.node]), [
[
MCP.node,
Layer.mock(MCP.Service, {
+2
View File
@@ -35,6 +35,8 @@ describe("PluginHooks", () => {
system: [SystemPart.make("first")],
messages: [Message.user("original")],
tools: {},
generation: {},
providerOptions: {},
}
expect(yield* hooks.trigger("session", "context", event)).toBe(event)
@@ -0,0 +1,32 @@
import type { Context } from "@opencode-ai/plugin/effect/plugin"
import type { SessionDomain } from "@opencode-ai/plugin/promise/session"
import { Session } from "@opencode-ai/schema/session"
import { SessionMessage } from "@opencode-ai/schema/session-message"
import { Effect } from "effect"
export function effectPrompt(context: Context) {
context.session.hook("prompt", (event) =>
Effect.sync(() => {
event.prompt.files ??= []
event.prompt.files.push({ uri: "file:///policy.md" })
event.delivery = "queue"
// @ts-expect-error Admission identity cannot be rewritten.
event.sessionID = Session.ID.make("ses_other")
}),
)
// @ts-expect-error Prompt admission has no resolved model to filter by provider.
context.session.hook("prompt", () => Effect.void, { providerID: "openai" })
context.session.hook("context", () => Effect.void, { providerID: "openai" })
}
export function promisePrompt(session: SessionDomain) {
session.hook("prompt", (event) => {
event.prompt.text = "Prepared"
event.metadata = { source: "plugin" }
// @ts-expect-error Admission identity cannot be rewritten.
event.messageID = SessionMessage.ID.make("msg_other")
})
// @ts-expect-error Prompt admission has no resolved model to filter by provider.
session.hook("prompt", () => {}, { providerID: "openai" })
session.hook("context", () => {}, { providerID: "openai" })
}
+7 -10
View File
@@ -580,7 +580,7 @@ describe("Plugin", () => {
const registry = yield* Tool.Service
const executed: unknown[] = []
const seen: {
before?: { input: unknown; inputSchema: unknown }
before?: { input: unknown; tool: string }
after?: { input: unknown; status: string; content: unknown; metadata: unknown }
} = {}
@@ -605,7 +605,9 @@ describe("Plugin", () => {
yield* ctx.tool
.hook("execute.before", (event) =>
Effect.sync(() => {
seen.before = { input: event.input, inputSchema: event.inputSchema }
expect(event).not.toHaveProperty("inputSchema")
seen.before = { input: event.input, tool: event.tool }
event.tool = "echo"
event.input = { text: "before-mutated" }
}),
)
@@ -648,17 +650,12 @@ describe("Plugin", () => {
sessionID: Session.ID.make("ses_hooks"),
agent: Agent.ID.make("build"),
messageID: SessionMessage.ID.make("msg_hooks"),
call: { type: "tool-call", id: "call-hooks", name: "echo", input: { text: "original" } },
call: { type: "tool-call", id: "call-hooks", name: "misspelled", input: { text: "original" } },
})
expect(seen.before).toEqual({
input: { text: "original" },
inputSchema: {
type: "object",
properties: { text: { type: "string" } },
required: ["text"],
additionalProperties: false,
},
tool: "misspelled",
})
expect(executed).toEqual([{ text: "before-mutated" }])
expect(seen.after).toEqual({
@@ -712,7 +709,7 @@ describe("Plugin", () => {
sessionID: Session.ID.make("ses_hook_reject"),
agent: Agent.ID.make("build"),
messageID: SessionMessage.ID.make("msg_hook_reject"),
call: { type: "tool-call", id: "call-hook-reject", name: "echo", input: { text: "original" } },
call: { type: "tool-call", id: "call-hook-reject", name: "missing", input: { text: "original" } },
})
.pipe(Effect.flip)
+2
View File
@@ -124,6 +124,8 @@ const request = (agent: Agent.ID, messages: Array<Message>): SessionContext => (
system: [],
messages,
tools: {},
generation: {},
providerOptions: {},
})
type ToolErrorEvent = Extract<ToolHooks["execute.after"], { readonly status: "error" }>
+138 -1
View File
@@ -20,6 +20,7 @@ import { Project } from "@opencode-ai/core/project"
import { Workspace } from "@opencode-ai/core/workspace"
import { AbsolutePath } from "@opencode-ai/core/schema"
import { define } from "@opencode-ai/plugin/promise/plugin"
import type { Info } from "@opencode-ai/plugin/promise/tool"
import { Money } from "@opencode-ai/schema/money"
import type { SessionHooks } from "@opencode-ai/plugin/effect/session"
import { testEffect } from "../lib/effect"
@@ -381,6 +382,8 @@ describe("fromPromise", () => {
await ctx.session.hook("context", (event) => {
event.system.push(SystemPart.make("Promise hook"))
delete event.tools.echo
event.generation.temperature = 0.4
event.providerOptions.reasoningEffort = "medium"
})
},
}),
@@ -392,12 +395,16 @@ describe("fromPromise", () => {
system: [SystemPart.make("Initial")],
messages: [Message.user("Hello")],
tools: { echo: { description: "Echo", input: { type: "object" } } },
generation: {},
providerOptions: {},
}
yield* hooks.trigger("session", "context", event)
expect(event.system.map((part) => part.text)).toEqual(["Initial", "Promise hook"])
expect(event.tools).toEqual({})
expect(event.generation).toEqual({ temperature: 0.4 })
expect(event.providerOptions).toEqual({ reasoningEffort: "medium" })
}),
)
@@ -611,6 +618,11 @@ describe("fromPromise", () => {
},
})
})
await ctx.tool.hook("execute.before", (event) => {
expect(event.tool).toBe("helllo")
expect(event).not.toHaveProperty("inputSchema")
event.tool = "hello"
})
},
})
@@ -624,7 +636,7 @@ describe("fromPromise", () => {
agent: Agent.ID.make("build"),
messageID: SessionMessage.ID.make("msg_promise_tool"),
progress: (update) => Effect.sync(() => progress.push(update)),
call: { type: "tool-call", id: "call_promise_tool", name: "hello", input: { name: "world" } },
call: { type: "tool-call", id: "call_promise_tool", name: "helllo", input: { name: "world" } },
}),
).toMatchObject({
output: "Hello, world!",
@@ -634,6 +646,76 @@ describe("fromPromise", () => {
}),
)
it.live("adapts listed and retrieved tool executors without invoking them eagerly", () =>
Effect.gen(function* () {
const plugins = yield* Plugin.Service
const host = yield* PluginHost.make(plugins)
const calls: string[] = []
const failure = new Tool.Error({ message: "executor failed" })
yield* host.tool.transform((draft) => {
draft.add({
name: "hello",
description: "Hello",
options: { namespace: "acme", codemode: false },
input: Schema.Struct({ name: Schema.String }),
output: Schema.String,
execute: ({ name }, context) => {
calls.push(name)
if (name === "failure") return Effect.fail(failure)
return context.progress({ name }).pipe(Effect.as({ output: name }))
},
})
})
yield* PluginPromise.fromPromise(
define({
id: "promise-tool-reads",
setup: async (ctx) => {
const tools: Info[] = []
await ctx.tool.transform((draft) => {
expect(draft.list().map((tool) => tool.id)).toEqual(["acme_hello"])
tools.push(...draft.list())
const tool = draft.get("acme_hello")
if (!tool) throw new Error("Tool was not found")
expect(tool.id).toBe("acme_hello")
tools.push(tool)
})
expect(tools).toHaveLength(2)
expect(calls).toEqual([])
await Promise.all(
tools.map(async (tool) => {
const progress: Tool.Metadata[] = []
const context = {
sessionID: Session.ID.make("ses_promise_tool_reads"),
agent: Agent.ID.make("build"),
messageID: SessionMessage.ID.make("msg_promise_tool_reads"),
id: Tool.CallID.make("call_reads"),
progress: async (update: Tool.Metadata) => {
progress.push(update)
},
}
expect(await tool.execute({ name: "world" }, context)).toEqual({ output: "world" })
expect(progress).toEqual([{ name: "world" }])
await expect(tool.execute({ name: "failure" }, context)).rejects.toBe(failure)
const error = new Error("progress failed")
await expect(
tool.execute(
{ name: "world" },
{
...context,
progress: async () => {
throw error
},
},
),
).rejects.toBe(error)
}),
)
},
}),
).effect(host)
}),
)
it.live("reloads and disposes Promise tools while preserving older snapshots", () =>
Effect.gen(function* () {
const plugins = yield* Plugin.Service
@@ -778,6 +860,61 @@ describe("fromPromise", () => {
}),
)
it.live("clears deleted tool options while retaining the namespace", () =>
Effect.gen(function* () {
const plugins = yield* Plugin.Service
const registry = yield* Tool.Service
const host = yield* PluginHost.make(plugins)
yield* host.tool.transform((draft) => {
draft.add({
name: "hello",
description: "Hello",
options: { namespace: "acme", codemode: false },
input: Schema.Struct({}),
output: Schema.String,
execute: () => Effect.succeed({ output: "Hello" }),
})
})
const original = yield* registry.snapshot()
expect(original.definitions.map((tool) => tool.name)).toEqual(["acme_hello", "execute"])
expect(original.codeModeCatalog).toEqual([])
yield* PluginPromise.fromPromise(
define({
id: "promise-tool-options",
setup: async (ctx) => {
await ctx.tool.transform((draft) => {
draft.update("acme_hello", (tool) => {
delete tool.options
})
expect(draft.get("acme_hello")?.options).toEqual({ namespace: "acme" })
})
},
}),
).effect(host)
const snapshot = yield* registry.snapshot()
expect(snapshot.definitions.map((tool) => tool.name)).toEqual(["execute"])
expect(snapshot.codeModeCatalog?.map((tool) => tool.path)).toEqual(["acme.hello"])
expect(original.definitions.map((tool) => tool.name)).toEqual(["acme_hello", "execute"])
expect(
yield* snapshot.execute({
sessionID: Session.ID.make("ses_promise_tool_options"),
agent: Agent.ID.make("build"),
messageID: SessionMessage.ID.make("msg_promise_tool_options"),
call: {
type: "tool-call",
id: "call_options",
name: "execute",
input: { code: "return await tools.acme.hello({})" },
},
}),
).toMatchObject({
output: { output: "Hello", toolCalls: [{ tool: "acme.hello", status: "completed" }] },
})
}),
)
it.effect("returns content-only plugin results through Code Mode", () =>
Effect.gen(function* () {
const plugins = yield* Plugin.Service
@@ -32,6 +32,8 @@ const context = (id: string, system = fallback): SessionHooks["context"] => ({
system: [SystemPart.make(system)],
messages: [],
tools: {},
generation: {},
providerOptions: {},
})
describe("SystemPromptPlugin", () => {
+11 -4
View File
@@ -10,6 +10,7 @@ import { EventTable } from "@opencode-ai/core/event/sql"
import { SessionCompaction } from "@opencode-ai/core/session/compaction"
import { SessionEvent } from "@opencode-ai/core/session/event"
import { SessionMessage } from "@opencode-ai/core/session/message"
import { SessionModelRequest } from "@opencode-ai/core/session/model-request"
import { SessionProjector } from "@opencode-ai/core/session/projector"
import { SessionRunnerModel } from "@opencode-ai/core/session/runner/model"
import { SessionTable } from "@opencode-ai/core/session/sql"
@@ -73,9 +74,6 @@ const resolved = SessionRunnerModel.resolved(model, {
cost,
limit: { context: 200_000, output: 32_000 },
})
const models = Layer.mock(SessionRunnerModel.Service)({
resolve: () => Effect.succeed(resolved),
})
const it = testEffect(
AppNodeBuilder.build(
LayerNode.group([
@@ -85,11 +83,11 @@ const it = testEffect(
SessionStore.node,
PluginHooks.node,
SessionCompaction.node,
SessionModelRequest.node,
]),
[
[Bus.node, Bus.configured({ persist: true })],
[llmClient, client],
[SessionRunnerModel.node, models],
],
),
)
@@ -242,6 +240,7 @@ it.effect("manual compaction summarizes short context instead of no-op", () =>
time: { created: DateTime.makeUnsafe(0) },
}
const session = yield* insertSession(sessionID, { parent_id: parentID })
const modelRequests = yield* SessionModelRequest.Service
const delta = yield* bus
.subscribe(SessionEvent.Compaction.Delta)
@@ -250,6 +249,8 @@ it.effect("manual compaction summarizes short context instead of no-op", () =>
expect(
yield* compaction.compactManual({
session,
resolveModel: () => Effect.succeed(resolved),
prepare: modelRequests.prepare,
messages: [userMessage],
inputID: SessionMessage.ID.make("msg_manual_compaction"),
}),
@@ -303,9 +304,12 @@ it.effect("forked session compaction reuses the fork root prompt cache key", ()
fork_session_id: rootID,
fork_boundary: { type: "before", messageID: SessionMessage.ID.create() },
})
const modelRequests = yield* SessionModelRequest.Service
expect(
yield* compaction.compactManual({
session,
resolveModel: () => Effect.succeed(resolved),
prepare: modelRequests.prepare,
messages: [
{
id: SessionMessage.ID.create(),
@@ -336,9 +340,12 @@ it.effect("keeps session context hooks away from compaction requests", () =>
}),
)
const session = yield* insertSession(Session.ID.make("ses_hook_compaction"))
const modelRequests = yield* SessionModelRequest.Service
expect(
yield* compaction.compactManual({
session,
resolveModel: () => Effect.succeed(resolved),
prepare: modelRequests.prepare,
messages: [
{
id: SessionMessage.ID.create(),
+20 -24
View File
@@ -32,7 +32,10 @@ import { SessionTable } from "@opencode-ai/core/session/sql"
import { SessionStore } from "@opencode-ai/core/session/store"
import { SessionTransfer } from "@opencode-ai/core/session/transfer"
import { Workspace } from "@opencode-ai/core/workspace"
import { Expected } from "./lib/session-message"
import { testEffect } from "./lib/effect"
import { LocationServiceMap } from "@opencode-ai/core/location-service-map"
import { promptLocationLayer } from "./fixture/prompt-location"
import { globalProjectLayer } from "./lib/project"
import { tmpdir } from "./fixture/tmpdir"
@@ -50,6 +53,7 @@ const it = testEffect(
[
[Bus.node, Bus.configured({ persist: true })],
[Project.node, globalProjectLayer],
[LocationServiceMap.node, promptLocationLayer],
[SessionExecution.node, SessionExecution.noopLayer],
],
),
@@ -183,7 +187,7 @@ describe("Session.create", () => {
"session.inbox.enqueued",
])
expect(yield* session.messages({ sessionID: created.id })).toMatchObject([
{ id: expect.any(String), type: "user", text: "Preserved history" },
{ id: expect.any(String), ...Expected.user("Preserved history") },
])
expect(yield* SessionInbox.find(db, pending.id)).toMatchObject({ payload: { text: "Preserved inbox" } })
expect(
@@ -446,10 +450,7 @@ describe("Session.create", () => {
expect(forked).toMatchObject({ title: "Parent (fork #1)", fork: { sessionID: parent.id } })
expect(forked.parentID).toBeUndefined()
expect(forkContext).toMatchObject([
{ type: "user", text: "First" },
{ type: "synthetic", text: "parent note" },
])
expect(forkContext).toMatchObject([Expected.user("First"), { type: "synthetic", text: "parent note" }])
expect(forkContext.map((message) => message.id)).not.toEqual(parentContext.map((message) => message.id))
expect(history).toHaveLength(1)
expect(history[0]).toMatchObject({
@@ -634,13 +635,10 @@ describe("Session.create", () => {
const forked = yield* session.fork({ sessionID: parent.id, boundary: { type: "through" } })
expect(yield* session.context(parent.id)).toMatchObject([
{ type: "user", text: "Run both tools" },
{
type: "assistant",
content: [{ type: "tool", id: "call_running", state: { status: "running" } }],
},
Expected.user("Run both tools"),
Expected.assistant({}, [{ type: "tool", id: "call_running", state: { status: "running" } }]),
])
expect(yield* session.context(forked.id)).toMatchObject([{ type: "user", text: "Run both tools" }])
expect(yield* session.context(forked.id)).toMatchObject([Expected.user("Run both tools")])
}),
)
@@ -667,10 +665,10 @@ describe("Session.create", () => {
const running = yield* session.fork({ sessionID: parent.id, boundary: { type: "through" } })
expect(yield* session.context(parent.id)).toMatchObject([
{ type: "user", text: "Run a shell" },
Expected.user("Run a shell"),
{ type: "shell", command: "sleep 10", status: "running" },
])
expect(yield* session.context(running.id)).toMatchObject([{ type: "user", text: "Run a shell" }])
expect(yield* session.context(running.id)).toMatchObject([Expected.user("Run a shell")])
yield* bus.publish(SessionEvent.Shell.Ended, {
sessionID: parent.id,
@@ -679,9 +677,9 @@ describe("Session.create", () => {
})
const completed = yield* session.fork({ sessionID: parent.id, boundary: { type: "through" } })
expect(yield* session.context(running.id)).toMatchObject([{ type: "user", text: "Run a shell" }])
expect(yield* session.context(running.id)).toMatchObject([Expected.user("Run a shell")])
expect(yield* session.context(completed.id)).toMatchObject([
{ type: "user", text: "Run a shell" },
Expected.user("Run a shell"),
{ type: "shell", command: "sleep 10", status: "exited", output: { output: "complete" } },
])
}),
@@ -757,8 +755,8 @@ describe("Session.create", () => {
expect(yield* session.context(beforeFirst.id)).toEqual([])
expect(beforeFirst).toMatchObject({ cost: 0, tokens: { input: 0, output: 0, reasoning: 0 } })
expect(yield* session.context(complete.id)).toMatchObject([
{ type: "user", text: "First" },
{ type: "user", text: "Second" },
Expected.user("First"),
Expected.user("Second"),
{ type: "assistant", finish: "stop" },
])
expect(complete).toMatchObject({
@@ -933,7 +931,7 @@ describe("Session.create", () => {
yield* Effect.forEach(serialized.slice(2), (event) => bus.replay(event), { discard: true })
expect(yield* SessionInbox.find(db, admitted.id)).toBeUndefined()
expect(yield* store.context(created.id)).toMatchObject([
{ id: admitted.id, type: "user", text: "Replay lifecycle" },
{ id: admitted.id, ...Expected.user("Replay lifecycle") },
])
expect(
(yield* db
@@ -963,7 +961,7 @@ describe("Session.create", () => {
}),
)
it.live("runs a shell command and projects the started/ended shell message", () =>
liveIt.live("runs a shell command and projects the started/ended shell message", () =>
withTmp((directory) =>
Effect.gen(function* () {
const session = yield* Session.Service
@@ -988,7 +986,7 @@ describe("Session.create", () => {
),
)
it.live("still emits shell ended for a failing command", () =>
liveIt.live("still emits shell ended for a failing command", () =>
withTmp((directory) =>
Effect.gen(function* () {
const session = yield* Session.Service
@@ -1157,9 +1155,7 @@ describe("SessionTransfer", () => {
recent: "pending",
})
expect((yield* transfer.export({ sessionID: source.id })).messages).toMatchObject([
{ type: "user", text: "Settled" },
])
expect((yield* transfer.export({ sessionID: source.id })).messages).toMatchObject([Expected.user("Settled")])
}),
)
@@ -1304,7 +1300,7 @@ describe("SessionTransfer", () => {
expect(imported).toMatchObject({ id: sessionID, title: "Exported", location })
expect(imported.time).toMatchObject({ idle: DateTime.makeUnsafe(200), viewed: DateTime.makeUnsafe(150) })
expect(messages).toMatchObject([
{ id: sourceMessageID, type: "user", text: "Imported message" },
{ id: sourceMessageID, ...Expected.user("Imported message") },
{ id: errorMessageID, type: "compaction", error: { type: "test_error", message: "Original error" } },
])
expect(yield* Bus.latestSequence(db, sessionID)).toBe(2)
+3 -3
View File
@@ -21,7 +21,7 @@ import { InstructionDiscovery } from "@opencode-ai/core/instruction-discovery"
import { Instructions } from "@opencode-ai/core/instructions/index"
import { InstructionBuiltIns } from "@opencode-ai/core/instructions/builtins"
import { Location } from "@opencode-ai/core/location"
import { MCPInstructions } from "@opencode-ai/core/mcp/instructions"
import { McpInstructions } from "@opencode-ai/core/mcp/instructions"
import { ID } from "@opencode-ai/core/model"
import { Project } from "@opencode-ai/core/project"
import { Provider } from "@opencode-ai/core/provider"
@@ -109,7 +109,7 @@ const discovery = Layer.mock(InstructionDiscovery.Service, {
})
const skills = Layer.mock(SkillInstructions.Service, { load: () => Effect.succeed(Instructions.empty) })
const references = Layer.mock(ReferenceInstructions.Service, { load: () => Effect.succeed(Instructions.empty) })
const mcp = Layer.mock(MCPInstructions.Service, { load: () => Effect.succeed(Instructions.empty) })
const mcp = Layer.mock(McpInstructions.Service, { load: () => Effect.succeed(Instructions.empty) })
const plugins = Layer.mock(PluginSupervisor.Service, { flush: Effect.void })
const tools = Layer.mock(Tool.Service, {
snapshot: () =>
@@ -148,7 +148,7 @@ const it = testEffect(
[InstructionDiscovery.node, discovery],
[SkillInstructions.node, skills],
[ReferenceInstructions.node, references],
[MCPInstructions.node, mcp],
[McpInstructions.node, mcp],
[PluginSupervisor.node, plugins],
[Tool.node, tools],
[Location.node, Location.boundNode({ directory: AbsolutePath.make("/project") })],
@@ -1,9 +1,165 @@
import { describe, expect, test } from "bun:test"
import { Message, ToolResultPart } from "@opencode-ai/ai"
import { boundImages, unsupportedParts } from "@opencode-ai/core/session/model-request"
import { LanguageModel, Message, ToolResultPart } from "@opencode-ai/ai"
import { Gemini } from "@opencode-ai/ai/protocols/gemini"
import { OpenAIResponses } from "@opencode-ai/ai/protocols/openai-responses"
import { compileRequest } from "@opencode-ai/ai/route/client"
import { PluginHooks } from "@opencode-ai/core/plugin/hooks"
import { SessionModelRequest, boundImages, unsupportedParts } from "@opencode-ai/core/session/model-request"
import { SessionModelTransport } from "@opencode-ai/core/session/model-transport"
import { SessionRunnerModel } from "@opencode-ai/core/session/runner/model"
import { Agent } from "@opencode-ai/schema/agent"
import { Location } from "@opencode-ai/schema/location"
import { Money } from "@opencode-ai/schema/money"
import { Project } from "@opencode-ai/schema/project"
import { AbsolutePath } from "@opencode-ai/schema/schema"
import { Session } from "@opencode-ai/schema/session"
import { LayerNode } from "@opencode-ai/util/effect/layer-node"
import { ConfigProvider, DateTime, Effect } from "effect"
import { testEffect } from "./lib/effect"
const capabilities = (input: string[]) => ({ tools: true, input, output: ["text"] })
const it = testEffect(
LayerNode.compile(LayerNode.group([SessionModelRequest.node, PluginHooks.node]), [
[SessionModelTransport.node, SessionModelTransport.makeLayer({ open: () => Effect.die("Unexpected connection") })],
]),
)
const requestInput = (model: LanguageModel) => ({
scope: {
session: Session.Info.make({
id: Session.ID.make("ses_request_options"),
projectID: Project.ID.global,
cost: Money.USD.zero,
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
time: { created: DateTime.makeUnsafe(0), updated: DateTime.makeUnsafe(0) },
location: Location.Ref.make({ directory: AbsolutePath.make("/project") }),
}),
agentID: Agent.ID.make("build"),
model: SessionRunnerModel.resolved(model, {
capabilities: { ...capabilities(["text"]), responsesWebsockets: model.provider === "openai" },
cost: [],
limit: { context: 200_000, output: 32_000 },
}),
},
transcript: { system: [], messages: [Message.user("Hello")] },
})
describe("SessionModelRequest.context options", () => {
it.effect("compiles ordered generation and provider overrides without mutating defaults", () =>
Effect.gen(function* () {
const requests = yield* SessionModelRequest.Service
const hooks = yield* PluginHooks.Service
const model = Gemini.route
.with({
generation: { maxTokens: 100, topP: 0.7 },
providerOptions: { thinkingConfig: { includeThoughts: true, thinkingBudget: 256 } },
})
.model({
id: "gemini-2.5-flash",
defaults: {
generation: { temperature: 0.8 },
providerOptions: { thinkingConfig: { thinkingBudget: 512 } },
},
})
const baseline = yield* requests.prepare(requestInput(model))
expect(baseline.request.generation).toBeUndefined()
expect(baseline.request.providerOptions).toBeUndefined()
const first = yield* hooks.register("session", "context", (event) =>
Effect.sync(() => {
expect(event.generation).toEqual({})
expect(event.providerOptions).toEqual({})
event.generation = {
maxTokens: 2048,
temperature: 0.2,
topK: 40,
frequencyPenalty: 0.1,
presencePenalty: 0.3,
seed: 42,
stop: ["END"],
}
event.providerOptions = { thinkingConfig: { thinkingBudget: 1024 } }
}),
)
const second = yield* hooks.register("session", "context", (event) =>
Effect.sync(() => {
expect(event.generation.temperature).toBe(0.2)
expect(event.providerOptions.thinkingConfig).toEqual({ thinkingBudget: 1024 })
event.generation.temperature = 0
event.generation.stop?.push("STOP")
}),
)
const prepared = yield* requests.prepare(requestInput(model))
expect((yield* compileRequest(prepared.request)).body).toMatchObject({
generationConfig: {
maxOutputTokens: 2048,
temperature: 0,
topP: 0.7,
topK: 40,
frequencyPenalty: 0.1,
presencePenalty: 0.3,
seed: 42,
stopSequences: ["END", "STOP"],
thinkingConfig: { includeThoughts: true, thinkingBudget: 1024 },
},
})
// Each new request starts with fresh override objects, even while hooks remain registered.
expect((yield* requests.prepare(requestInput(model))).request.generation).toEqual(prepared.request.generation)
yield* first.dispose
yield* second.dispose
const unhooked = yield* requests.prepare(requestInput(model))
expect(unhooked.request.generation).toBeUndefined()
expect(unhooked.request.providerOptions).toBeUndefined()
expect((yield* compileRequest(unhooked.request)).body).toEqual((yield* compileRequest(baseline.request)).body)
expect(model.defaults?.generation).toEqual({ temperature: 0.8 })
expect(model.route.defaults.generation).toEqual({ maxTokens: 100, topP: 0.7 })
expect(model.defaults?.providerOptions).toEqual({ thinkingConfig: { thinkingBudget: 512 } })
expect(model.route.defaults.providerOptions).toEqual({
thinkingConfig: { includeThoughts: true, thinkingBudget: 256 },
})
}),
)
it.effect("compiles OpenAI semantic reasoning options without revoking WebSocket transport", () =>
Effect.gen(function* () {
const requests = yield* SessionModelRequest.Service
const hooks = yield* PluginHooks.Service
yield* hooks.register("session", "context", () => Effect.die("Other-provider hook must not run"), {
providerID: "google",
})
yield* hooks.register(
"session",
"context",
(event) =>
Effect.sync(() => {
event.generation.maxTokens = 8000
event.providerOptions.reasoningEffort = "high"
}),
{ providerID: "openai" },
)
const input = requestInput(OpenAIResponses.route.model({ id: "gpt-5.5" }))
const prepared = yield* requests.prepare({ ...input, webSocket: "session" })
expect(prepared.options.webSocket).toBeDefined()
expect(prepared.options.http).toBeUndefined()
expect((yield* compileRequest(prepared.request)).body).toMatchObject({
max_output_tokens: 8000,
reasoning: { effort: "high" },
store: false,
include: ["reasoning.encrypted_content"],
})
const excluded = yield* requests.prepare({ ...input, contextHooks: false })
expect(excluded.request.generation).toBeUndefined()
expect(excluded.request.providerOptions).toBeUndefined()
}).pipe(
Effect.provide(
ConfigProvider.layer(
ConfigProvider.fromEnv({ env: { OPENCODE_EXPERIMENTAL_OPENAI_RESPONSES_WEBSOCKET: "true" } }),
),
),
),
)
})
describe("SessionModelRequest.unsupportedParts", () => {
test("replaces unsupported user media with a visible error", () => {
const messages = unsupportedParts(
@@ -0,0 +1,347 @@
import { describe, expect } from "bun:test"
import path from "path"
import { Deferred, Effect, Fiber, Stream } from "effect"
import { Bus } from "@opencode-ai/core/bus"
import { Database } from "@opencode-ai/core/database/database"
import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
import { LocationServiceMap } from "@opencode-ai/core/location-service-map"
import { PluginHooks } from "@opencode-ai/core/plugin/hooks"
import { PluginRuntime } from "@opencode-ai/core/plugin/runtime"
import { PluginSupervisor } from "@opencode-ai/core/plugin/supervisor"
import { AbsolutePath } from "@opencode-ai/core/schema"
import { Session } from "@opencode-ai/core/session"
import { SessionExecution } from "@opencode-ai/core/session/execution"
import { SessionEvent } from "@opencode-ai/core/session/event"
import { SessionInbox } from "@opencode-ai/core/session/inbox"
import { SessionMessage } from "@opencode-ai/core/session/message"
import { SessionProjector } from "@opencode-ai/core/session/projector"
import { Skill } from "@opencode-ai/core/skill"
import { LayerNode } from "@opencode-ai/util/effect/layer-node"
import { Global } from "@opencode-ai/util/global"
import { tempGlobalLayer } from "./fixture/global"
import { tmpdir } from "./fixture/tmpdir"
import { testEffect } from "./lib/effect"
const runtime = PluginRuntime.makeCell()
const it = testEffect(
AppNodeBuilder.build(
LayerNode.group([
Database.node,
Bus.node,
SessionProjector.node,
Session.node,
LocationServiceMap.node,
PluginRuntime.providerNodeWithCell(runtime),
]),
[
[Bus.node, Bus.configured({ persist: true })],
[Global.node, tempGlobalLayer],
[SessionExecution.node, SessionExecution.noopLayer],
[PluginRuntime.node, PluginRuntime.layerWithCell(runtime)],
],
),
)
const project = Effect.acquireRelease(
Effect.promise(() => tmpdir()),
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
)
const setup = Effect.gen(function* () {
const tmp = yield* project
const sessions = yield* Session.Service
const session = yield* sessions.create({ location: { directory: AbsolutePath.make(tmp.path) } })
const locations = yield* LocationServiceMap.Service
const services = locations.get(session.location)
const hooks = yield* Effect.gen(function* () {
const plugins = yield* PluginSupervisor.Service
yield* plugins.flush
return yield* PluginHooks.Service
}).pipe(Effect.provide(services))
return { sessions, session, hooks, services }
})
describe("Session prompt hooks", () => {
it.live("waits for local plugin setup before admitting even a plain-text prompt", () =>
Effect.gen(function* () {
const tmp = yield* project
yield* Effect.promise(() =>
Bun.write(
path.join(tmp.path, ".opencode/plugins/prompt.ts"),
`export default {
id: "prompt-readiness",
async setup(ctx) {
await ctx.session.hook("prompt", (event) => {
event.prompt.text = "Prepared by plugin"
})
},
}`,
),
)
const sessions = yield* Session.Service
const session = yield* sessions.create({ location: { directory: AbsolutePath.make(tmp.path) } })
const admitted = yield* sessions.prompt({ sessionID: session.id, text: "Original", resume: false })
expect(admitted.payload.text).toBe("Prepared by plugin")
}),
)
it.live("persists ordered draft edits and resolves added files and skills without mutating the caller", () =>
Effect.gen(function* () {
const fixture = yield* setup
const skills = yield* Skill.Service.pipe(Effect.provide(fixture.services))
const skill = Skill.Info.make({
id: Skill.ID.make("policy"),
name: Skill.Name.make("Policy"),
description: "Company policy",
location: AbsolutePath.make(path.join(fixture.session.location.directory, "policy.md")),
content: "Follow company policy.",
})
yield* skills.transform((draft) => draft.add(skill))
const input = {
sessionID: fixture.session.id,
id: SessionMessage.ID.create(),
text: "secret",
files: [
{
uri: "data:text/plain;base64,b3JpZ2luYWw=",
name: "original.txt",
mention: { start: 0, end: 6, text: "secret" },
},
],
metadata: { source: "api" },
resume: false,
}
yield* fixture.hooks.register("session", "prompt", (event) =>
Effect.sync(() => {
expect(event.sessionID).toBe(input.sessionID)
expect(event.messageID).toBe(input.id)
event.prompt.text = "Redacted"
const file = event.prompt.files?.[0]
if (file) {
file.uri = "data:text/plain;base64,cG9saWN5"
file.name = "policy.txt"
delete file.mention
}
event.prompt.skills = [{ id: skill.id }]
event.prompt.agents = [{ name: "reviewer" }]
event.metadata ??= {}
event.metadata.source = "plugin"
event.delivery = "queue"
}),
)
yield* fixture.hooks.register("session", "prompt", (event) =>
Effect.sync(() => {
expect(event.prompt.text).toBe("Redacted")
event.prompt.text += " with policy"
}),
)
const admitted = yield* fixture.sessions.prompt(input)
expect(admitted).toMatchObject({
id: input.id,
delivery: "queue",
payload: {
text: "Redacted with policy",
metadata: { source: "plugin" },
files: [{ name: "policy.txt", data: "cG9saWN5", mime: "text/plain" }],
agents: [{ name: "reviewer" }],
skills: [{ id: skill.id, name: skill.name, text: Skill.toModelOutput(skill, []) }],
},
})
expect(input.text).toBe("secret")
expect(input.files).toEqual([
{
uri: "data:text/plain;base64,b3JpZ2luYWw=",
name: "original.txt",
mention: { start: 0, end: 6, text: "secret" },
},
])
expect(input.metadata).toEqual({ source: "api" })
const database = yield* Database.Service
const bus = yield* Bus.Service
expect(yield* SessionInbox.find(database.db, input.id)).toEqual(admitted)
const log = yield* fixture.sessions.log({ sessionID: input.sessionID }).pipe(Stream.runCollect)
expect(JSON.stringify(log)).not.toContain("secret")
yield* SessionInbox.promote(database.db, bus, input.sessionID, "input")
expect(yield* fixture.sessions.messages({ sessionID: input.sessionID })).toMatchObject([
{ id: input.id, type: "user", text: "Redacted with policy", metadata: { source: "plugin" } },
])
}),
)
it.live("skips hooks and payload resolution on pending and delivered retries, including conflicts", () =>
Effect.gen(function* () {
const fixture = yield* setup
const calls: string[] = []
yield* fixture.hooks.register("session", "prompt", (event) =>
Effect.sync(() => {
calls.push(event.prompt.text)
event.prompt.text = "First admission"
}),
)
const input = { sessionID: fixture.session.id, id: SessionMessage.ID.create(), text: "Original", resume: false }
const first = yield* fixture.sessions.prompt(input)
const retry = { ...input, text: "Ignored", files: [{ uri: "file:///missing-retry-file" }] }
expect(yield* fixture.sessions.prompt(retry)).toEqual(first)
const database = yield* Database.Service
const bus = yield* Bus.Service
yield* SessionInbox.promote(database.db, bus, input.sessionID, "steer")
expect((yield* fixture.sessions.prompt(retry)).payload).toEqual(first.payload)
const other = yield* fixture.sessions.create({ location: fixture.session.location })
expect((yield* fixture.sessions.prompt({ ...retry, sessionID: other.id }).pipe(Effect.flip))._tag).toBe(
"Session.PromptConflictError",
)
const synthetic = yield* fixture.sessions.synthetic({
sessionID: input.sessionID,
text: "Synthetic",
resume: false,
})
expect((yield* fixture.sessions.prompt({ ...retry, id: synthetic.id }).pipe(Effect.flip))._tag).toBe(
"Session.PromptConflictError",
)
expect(calls).toEqual(["Original"])
}),
)
it.live("leaves a staged revert untouched on retries and failed preparation", () =>
Effect.gen(function* () {
const fixture = yield* setup
const database = yield* Database.Service
const bus = yield* Bus.Service
const first = yield* fixture.sessions.prompt({ sessionID: fixture.session.id, text: "Boundary", resume: false })
yield* SessionInbox.promote(database.db, bus, fixture.session.id, "steer")
yield* bus.publish(SessionEvent.RevertEvent.Staged, {
sessionID: fixture.session.id,
revert: { messageID: first.id, files: [] },
})
const failing = yield* fixture.hooks.register("session", "prompt", () => Effect.die(new Error("Broken hook")))
expect(
(yield* fixture.sessions.prompt({
sessionID: fixture.session.id,
id: first.id,
text: "Ignored",
resume: false,
})).payload,
).toEqual(first.payload)
expect(
(yield* fixture.sessions
.prompt({ sessionID: fixture.session.id, text: "Fail", resume: false })
.pipe(Effect.exit))._tag,
).toBe("Failure")
expect((yield* fixture.sessions.get(fixture.session.id)).revert?.messageID).toBe(first.id)
expect(yield* fixture.sessions.messages({ sessionID: fixture.session.id })).toMatchObject([{ id: first.id }])
yield* failing.dispose
const next = yield* fixture.sessions.prompt({
sessionID: fixture.session.id,
text: "After revert",
resume: false,
})
expect((yield* fixture.sessions.get(fixture.session.id)).revert).toBeUndefined()
expect(yield* fixture.sessions.messages({ sessionID: fixture.session.id })).toEqual([])
expect(yield* fixture.sessions.inbox(fixture.session.id)).toEqual([next])
}),
)
it.live("keeps first-admission-wins for concurrent transformed submissions", () =>
Effect.gen(function* () {
const fixture = yield* setup
const entered = yield* Deferred.make<void>()
const release = yield* Deferred.make<void>()
const calls: string[] = []
yield* fixture.hooks.register("session", "prompt", (event) =>
Effect.gen(function* () {
calls.push(event.prompt.text)
event.prompt.text += " transformed"
if (calls.length === 2) yield* Deferred.succeed(entered, undefined)
yield* Deferred.await(release)
}),
)
const input = { sessionID: fixture.session.id, id: SessionMessage.ID.create(), text: "First", resume: false }
const submissions = yield* Effect.all(
[fixture.sessions.prompt(input), fixture.sessions.prompt({ ...input, text: "Second" })],
{ concurrency: "unbounded" },
).pipe(Effect.forkChild)
yield* Deferred.await(entered)
expect(yield* fixture.sessions.inbox(input.sessionID)).toEqual([])
yield* Deferred.succeed(release, undefined)
const results = yield* Fiber.join(submissions)
expect(results[0]).toEqual(results[1])
expect(["First transformed", "Second transformed"]).toContain(results[0]?.payload.text)
expect(yield* fixture.sessions.inbox(input.sessionID)).toHaveLength(1)
expect(yield* fixture.sessions.prompt(input)).toEqual(results[0])
expect(calls).toHaveLength(2)
}),
)
it.live("does not admit failed attachment preparation or an interrupted hook", () =>
Effect.gen(function* () {
const fixture = yield* setup
const registration = yield* fixture.hooks.register("session", "prompt", (event) =>
Effect.sync(() => {
event.prompt.files = [{ uri: "file:///missing-hook-file" }]
}),
)
expect(
(yield* fixture.sessions
.prompt({ sessionID: fixture.session.id, text: "Original", resume: false })
.pipe(Effect.flip))._tag,
).toBe("Session.AttachmentError")
yield* registration.dispose
const failing = yield* fixture.hooks.register("session", "prompt", () => Effect.die(new Error("Broken hook")))
expect(
(yield* fixture.sessions
.prompt({ sessionID: fixture.session.id, text: "Fail", resume: false })
.pipe(Effect.exit))._tag,
).toBe("Failure")
yield* failing.dispose
const started = yield* Deferred.make<void>()
yield* fixture.hooks.register("session", "prompt", () =>
Deferred.succeed(started, undefined).pipe(Effect.andThen(Effect.never)),
)
const submission = yield* fixture.sessions
.prompt({ sessionID: fixture.session.id, text: "Interrupt", resume: false })
.pipe(Effect.forkChild)
yield* Deferred.await(started)
yield* Fiber.interrupt(submission)
expect(yield* fixture.sessions.inbox(fixture.session.id)).toEqual([])
expect(yield* fixture.sessions.messages({ sessionID: fixture.session.id })).toEqual([])
}),
)
it.live("applies a Promise plugin to command-generated prompts only in its own location", () =>
Effect.gen(function* () {
const tmp = yield* project
yield* Effect.promise(() =>
Bun.write(
path.join(tmp.path, ".opencode/plugins/command.ts"),
`export default {
id: "prompt-command",
async setup(ctx) {
await ctx.session.hook("prompt", (event) => {
event.prompt.text += " with plugin"
})
await ctx.command.transform((draft) => {
draft.add({
name: "review",
async execute(input) {
await ctx.session.prompt({ sessionID: input.sessionID, text: "Review", resume: false })
},
})
})
},
}`,
),
)
const sessions = yield* Session.Service
const session = yield* sessions.create({ location: { directory: AbsolutePath.make(tmp.path) } })
const other = yield* setup
yield* sessions.command({ sessionID: session.id, command: "review", text: "" })
expect(yield* sessions.inbox(session.id)).toMatchObject([{ payload: { text: "Review with plugin" } }])
const untouched = yield* other.sessions.prompt({
sessionID: other.session.id,
text: "Other location",
resume: false,
})
expect(untouched.payload.text).toBe("Other location")
}),
)
})

Some files were not shown because too many files have changed in this diff Show More