Compare commits

..
4 Commits
106 changed files with 966 additions and 4366 deletions
@@ -1,79 +0,0 @@
import { expect, story } from "../../storybook/playwright/story"
story("enables Any only after confirmation and supports resetting the preview", async ({ mount }) => {
const component = await mount("app-current-session-surface--web-search-request")
const card = component.getByRole("region", { name: "Third-party web search" })
await expect(card.getByRole("button", { name: "Enable", exact: true })).toBeEnabled()
await expect(card.getByRole("button", { name: "Search provider Any", exact: true })).toBeVisible()
await card.getByRole("button", { name: "Enable", exact: true }).click()
await expect(component.getByRole("status")).toHaveText("Web search selection (local only): random")
await expect(card).toHaveCount(0)
await component.getByRole("button", { name: "Reset", exact: true }).click()
await expect(card.getByRole("button", { name: "Enable", exact: true })).toBeEnabled()
})
story("declining search is an explicit disabled selection", async ({ mount }) => {
const component = await mount("app-current-session-surface--web-search-request")
const card = component.getByRole("region", { name: "Third-party web search" })
await card.getByRole("button", { name: "Dont use search", exact: true }).click()
await expect(component.getByRole("status")).toHaveText("Web search selection (local only): false")
await expect(card).toHaveCount(0)
})
story("sizes provider options to their content", async ({ mount, page }) => {
const component = await mount("app-current-session-surface--web-search-request")
await component.getByRole("button", { name: "Search provider Any", exact: true }).click()
const menu = page.getByRole("listbox", { name: "Search provider", exact: true })
await expect(menu).toBeVisible()
const metrics = await menu.evaluate((listbox) => {
const items = Array.from(listbox.querySelectorAll('[data-component="menu-v2-item"]'))
const longest = items
.flatMap((item) => {
const label = item.querySelector('[data-slot="menu-v2-item-content"]')?.getBoundingClientRect()
const check = item.querySelector('[data-slot="menu-v2-item-indicator"]')?.getBoundingClientRect()
return label && check ? [{ label, check }] : []
})
.toSorted((a, b) => b.label.width - a.label.width)[0]
return {
width: listbox.getBoundingClientRect().width,
gap: longest ? longest.check.left - longest.label.right : 0,
}
})
expect(metrics.width).toBeLessThan(160)
expect(metrics.gap).toBe(24)
})
for (const width of [360, 1200]) {
for (const direction of ["ltr", "rtl"]) {
for (const theme of ["light", "dark"]) {
story(`selects and confirms a provider at ${width}px in ${direction} ${theme}`, async ({ mount, page }) => {
await page.setViewportSize({ width, height: 900 })
const component = await mount("app-current-session-surface--web-search-request", {
globals: { theme, direction },
})
const card = component.getByRole("region", { name: "Third-party web search" })
const select = card.getByRole("button", { name: /^Search provider/ })
await expect(select).toBeEnabled()
await expect(card).toHaveCSS("direction", direction)
expect(await card.evaluate((node) => node.scrollWidth <= node.clientWidth)).toBe(true)
await select.focus()
await select.press("Enter")
const list = page.getByRole("listbox", { name: "Search provider", exact: true })
await expect(list).toHaveCSS("direction", direction)
await list.getByRole("option", { name: "Parallel", exact: true }).click()
await expect(select).toHaveText("Parallel")
await expect(card).toBeVisible()
await expect(component.getByRole("status")).toHaveText("Ready")
await expect(select).toBeFocused()
await select.press("Tab")
await expect(card.getByRole("button", { name: "Dont use search", exact: true })).toBeFocused()
await page.keyboard.press("Tab")
const enable = card.getByRole("button", { name: "Enable", exact: true })
await expect(enable).toBeFocused()
await enable.press("Enter")
await expect(component.getByRole("status")).toHaveText("Web search selection (local only): parallel")
await expect(card).toHaveCount(0)
})
}
}
}
-1
View File
@@ -43,7 +43,6 @@ The suite contains:
- home-session click timing split between content and titlebar-tab paint
- single-session tab close timing through stable home restoration
- cached session repaint and mutation tracing
- large-session search scan, first-result reveal, and highlight stabilization
- streaming timeline throughput, RAF-gap, long-task, geometry, and remount diagnostics
- retained renderer heap with a large model catalog across repeated session navigation
@@ -1,69 +0,0 @@
import { benchmark, expect } from "../benchmark"
import { buildInitialStreamEvent, setupTimelineBenchmark, textPartID } from "./session-timeline-benchmark.fixture"
import {
collectTimelineSearchMetrics,
installTimelineSearchProbe,
waitForStableTimelineSearch,
} from "./session-timeline-search-probe"
benchmark("searches a large virtualized session and reveals the first result", async ({ page, report }) => {
benchmark.setTimeout(180_000)
const historyTurns = Number(process.env.TIMELINE_SEARCH_HISTORY_TURNS ?? 320)
const completionTimeout = Number(process.env.TIMELINE_SEARCH_COMPLETION_TIMEOUT_MS ?? 60_000)
const query = "Historical prompt"
const targetPartID = "msg_0000_0000_a_user:text:0"
const expectedCounter = `1/${historyTurns}`
const fixture = await setupTimelineBenchmark(page, {
historyTurns,
eventBatch: 1,
})
fixture.transport.enqueue(buildInitialStreamEvent(1))
await expect(fixture.text).toContainText("Implementation plan")
await fixture.scrollToBottom()
await fixture.waitForStableGeometry()
// Chromium reserves the physical shortcut for its native find overlay, so request the same controller path directly.
await page.evaluate(() => document.dispatchEvent(new Event("opencode:timeline-search-open")))
const search = page.locator('[data-component="timeline-search-bar"]')
const field = search.getByRole("searchbox", { name: "Find..." })
const count = search.locator('[data-slot="timeline-search-count"]')
const target = page.locator(`[data-timeline-part-id="${targetPartID}"]`)
await expect(field).toBeVisible()
await expect(field).toBeFocused()
await installTimelineSearchProbe(page, { targetPartID })
await field.fill(query)
await expect(count).toHaveText(expectedCounter)
await expect(target).toBeVisible({ timeout: completionTimeout })
await waitForStableTimelineSearch(page, { counter: expectedCounter, targetPartID, timeout: completionTimeout })
const metrics = await collectTimelineSearchMetrics(page, { counter: expectedCounter, targetPartID })
expect(metrics.summary.handlerDurationMs).toBeDefined()
expect(metrics.summary.firstCountObservedMs).toBeDefined()
expect(metrics.summary.firstTargetVisibleMs).toBeDefined()
expect(metrics.summary.firstActiveHighlightObservedMs).toBeDefined()
expect(metrics.summary.stableResultObservedMs).toBeDefined()
expect(metrics.summary.activeHighlightRanges).toBe(1)
report(metrics, { historyTurns, query, expectedMatches: historyTurns })
// Check navigation and the V2 assistant content IDs outside the measured interval.
await field.press("Enter")
await expect(count).toHaveText(`2/${historyTurns}`)
await field.press("Shift+Enter")
await expect(count).toHaveText(expectedCounter)
await field.fill("Implementation plan")
await expect(count).toHaveText("1/1")
await expect(fixture.text).toBeInViewport()
await expect
.poll(() =>
page.evaluate(() => {
const range = [...(CSS.highlights.get("timeline-search-hit-active") ?? [])][0]
return range?.startContainer.parentElement?.closest<HTMLElement>("[data-timeline-part-id]")?.dataset
.timelinePartId
}),
)
.toBe(textPartID)
await field.press("Escape")
await expect(search).toBeHidden()
})
@@ -1,176 +0,0 @@
import type { Page } from "@playwright/test"
export type TimelineSearchSample = {
observedAtMs: number
counter: string
targetMounted: boolean
targetVisible: boolean
targetTopPx?: number
activeRanges: number
activePartID?: string
activeVisible: boolean
scrollTopPx: number
}
type TimelineSearchProbe = {
samples: TimelineSearchSample[]
handlerDurationMs?: number
initialScrollTopPx: number
stop: () => void
}
export async function installTimelineSearchProbe(page: Page, input: { targetPartID: string }) {
await page.evaluate(({ targetPartID }) => {
const search = document.querySelector<HTMLElement>('[data-component="timeline-search-bar"]')
const field = search?.querySelector<HTMLInputElement>('[data-slot="text-input-v2-input"]')
const root = [...document.querySelectorAll<HTMLElement>(".scroll-view__viewport")].find((element) =>
element.querySelector("[data-timeline-row]"),
)
if (!search || !field || !root) throw new Error("missing timeline search benchmark nodes")
const samples: TimelineSearchSample[] = []
const initialScrollTopPx = root.scrollTop
let startedAt: number | undefined
let handlerDurationMs: number | undefined
let frame: number | undefined
let running = true
const visibleInRoot = (rect: DOMRect) => {
const viewport = root.getBoundingClientRect()
return rect.width > 0 && rect.height > 0 && rect.bottom > viewport.top && rect.top < viewport.bottom
}
const sample = () => {
if (!running || startedAt === undefined) return
frame = requestAnimationFrame(() => {
frame = undefined
setTimeout(() => {
if (!running || startedAt === undefined) return
const target = root.querySelector<HTMLElement>(`[data-timeline-part-id="${targetPartID}"]`)
const targetRect = target?.getBoundingClientRect()
const highlight = CSS.highlights.get("timeline-search-hit-active")
const ranges = highlight ? [...highlight] : []
const active = ranges.find((range): range is Range => range instanceof Range)
const activeRect = active?.getBoundingClientRect()
const activeElement =
active?.startContainer instanceof Element ? active.startContainer : active?.startContainer.parentElement
samples.push({
observedAtMs: performance.now() - startedAt,
counter:
search.querySelector<HTMLElement>('[data-slot="timeline-search-count"]')?.textContent?.trim() ?? "",
targetMounted: !!target,
targetVisible: !!targetRect && visibleInRoot(targetRect),
targetTopPx: targetRect?.top,
activeRanges: ranges.length,
activePartID: activeElement?.closest<HTMLElement>("[data-timeline-part-id]")?.dataset.timelinePartId,
activeVisible: !!activeRect && visibleInRoot(activeRect),
scrollTopPx: root.scrollTop,
})
sample()
}, 0)
})
}
const onInputCapture = (event: Event) => {
if (event.target !== field || startedAt !== undefined) return
startedAt = performance.now()
sample()
}
const onInput = (event: Event) => {
if (event.target !== field || startedAt === undefined || handlerDurationMs !== undefined) return
handlerDurationMs = performance.now() - startedAt
}
document.addEventListener("input", onInputCapture, { capture: true })
document.addEventListener("input", onInput)
;(window as Window & { __timelineSearchBenchmark?: TimelineSearchProbe }).__timelineSearchBenchmark = {
samples,
initialScrollTopPx,
get handlerDurationMs() {
return handlerDurationMs
},
stop: () => {
running = false
document.removeEventListener("input", onInputCapture, { capture: true })
document.removeEventListener("input", onInput)
if (frame !== undefined) cancelAnimationFrame(frame)
},
}
}, input)
}
export async function waitForStableTimelineSearch(
page: Page,
input: { counter: string; targetPartID: string; timeout: number },
) {
await page.waitForFunction(
({ counter, targetPartID }) => {
const samples = (window as Window & { __timelineSearchBenchmark?: TimelineSearchProbe }).__timelineSearchBenchmark
?.samples
if (!samples) return false
return samples.some((_, index) => {
const stable = samples.slice(index, index + 3)
if (stable.length !== 3) return false
return stable.every(
(sample, sampleIndex) =>
sample.counter === counter &&
sample.targetVisible &&
sample.activeRanges === 1 &&
sample.activePartID === targetPartID &&
sample.activeVisible &&
(sampleIndex === 0 ||
(Math.abs(sample.scrollTopPx - stable[sampleIndex - 1]!.scrollTopPx) <= 1 &&
Math.abs((sample.targetTopPx ?? Infinity) - (stable[sampleIndex - 1]!.targetTopPx ?? -Infinity)) <= 1)),
)
})
},
{ counter: input.counter, targetPartID: input.targetPartID },
{ timeout: input.timeout },
)
}
export async function collectTimelineSearchMetrics(page: Page, input: { counter: string; targetPartID: string }) {
const result = await page.evaluate(() => {
const probe = (window as Window & { __timelineSearchBenchmark?: TimelineSearchProbe }).__timelineSearchBenchmark
if (!probe) throw new Error("missing timeline search benchmark probe")
probe.stop()
return {
samples: probe.samples,
handlerDurationMs: probe.handlerDurationMs,
initialScrollTopPx: probe.initialScrollTopPx,
}
})
const first = (predicate: (sample: TimelineSearchSample) => boolean) => result.samples.find(predicate)?.observedAtMs
const stable = result.samples.findIndex((_, index) => {
const samples = result.samples.slice(index, index + 3)
if (samples.length !== 3) return false
return samples.every(
(sample, sampleIndex) =>
sample.counter === input.counter &&
sample.targetVisible &&
sample.activeRanges === 1 &&
sample.activePartID === input.targetPartID &&
sample.activeVisible &&
(sampleIndex === 0 ||
(Math.abs(sample.scrollTopPx - samples[sampleIndex - 1]!.scrollTopPx) <= 1 &&
Math.abs((sample.targetTopPx ?? Infinity) - (samples[sampleIndex - 1]!.targetTopPx ?? -Infinity)) <= 1)),
)
})
const final = result.samples.at(-1)
return {
summary: {
handlerDurationMs: result.handlerDurationMs,
firstCountObservedMs: first((sample) => sample.counter === input.counter),
firstTargetMountedMs: first((sample) => sample.targetMounted),
firstTargetVisibleMs: first((sample) => sample.targetVisible),
firstActiveHighlightObservedMs: first(
(sample) => sample.activeRanges === 1 && sample.activePartID === input.targetPartID && sample.activeVisible,
),
stableResultObservedMs: stable >= 0 ? result.samples[stable + 2]?.observedAtMs : undefined,
initialScrollTopPx: result.initialScrollTopPx,
finalScrollTopPx: final?.scrollTopPx,
scrollDistancePx: final === undefined ? undefined : Math.abs(result.initialScrollTopPx - final.scrollTopPx),
activeHighlightRanges: final?.activeRanges,
},
samples: result.samples,
}
}
@@ -7,13 +7,11 @@ const directory = "C:/OpenCode/OpenFileExpand"
const projectID = "proj_open_file_expand"
const sessionID = "ses_open_file_expand"
const title = "Open file expand"
const longFilename = "a-very-long-file-name-that-must-overflow-the-file-sidebar-instead-of-being-truncated.ts"
const longPath = `frontend/${longFilename}`
const server = `http://${process.env.PLAYWRIGHT_SERVER_HOST ?? "127.0.0.1"}:${process.env.PLAYWRIGHT_SERVER_PORT ?? "4096"}`
test.use({ viewport: { width: 1440, height: 900 } })
test("expands Windows paths and horizontally scrolls long filenames", async ({ page }) => {
test("expands a folder whose path has a trailing Windows separator", async ({ page }) => {
await mockOpenCodeServer(page, {
directory,
project: {
@@ -46,17 +44,7 @@ test("expands Windows paths and horizontally scrolls long filenames", async ({ p
time: { created: 1700000000000, updated: 1700000000000 },
},
],
vcsDiff: [
{
file: longPath,
before: "",
after: "export const added = true\n",
additions: 1,
deletions: 0,
status: "added",
patch: "@@ -0,0 +1 @@\n+export const added = true\n",
},
],
vcsDiff: [],
fileList: (path) => {
if (path === "frontend\\" || path === "frontend") {
return [
@@ -67,13 +55,6 @@ test("expands Windows paths and horizontally scrolls long filenames", async ({ p
type: "file" as const,
ignored: false,
},
{
name: longFilename,
path: `frontend\\${longFilename}`,
absolute: `${directory}/${longPath}`,
type: "file" as const,
ignored: false,
},
]
}
if (path) return []
@@ -94,7 +75,6 @@ test("expands Windows paths and horizontally scrolls long filenames", async ({ p
},
]
},
findFiles: ({ query }) => (longPath.includes(query) ? [longPath] : []),
fileContent: (path) => ({ type: "text", content: `contents:${path}` }),
pageMessages: () => ({ items: [] }),
})
@@ -139,93 +119,6 @@ test("expands Windows paths and horizontally scrolls long filenames", async ({ p
await frontendRow.click()
await expect(frontendRow).toHaveAttribute("aria-expanded", "true")
const viewport = sidebar.locator('[data-slot="session-review-v2-sidebar-tree"] .scroll-view__viewport')
const longRow = panel.getByRole("button", { name: longFilename })
await expect(longRow).toBeVisible()
await expect.poll(() => viewport.evaluate((element) => element.scrollWidth - element.clientWidth)).toBeGreaterThan(0)
expect(
await longRow.evaluate((element) => getComputedStyle(element.querySelector("bdi")!.parentElement!).textOverflow),
).toBe("clip")
expect(await longRow.evaluate((element) => element.getBoundingClientRect().width)).toBeGreaterThanOrEqual(
await viewport.evaluate((element) => element.clientWidth),
)
await expect
.poll(() =>
panel.locator('[data-slot="file-tree-v2-row"]').evaluateAll((rows) => {
const widths = rows.map((row) => row.getBoundingClientRect().width)
return Math.max(...widths) - Math.min(...widths)
}),
)
.toBeLessThanOrEqual(0.5)
await expect(longRow.locator('[data-slot="file-tree-v2-label"]')).toHaveCSS("margin-inline-end", "12px")
const status = longRow.locator('[data-slot="file-tree-v2-change"]')
await expect(status).toHaveText("A")
const statusBox = await status.boundingBox()
if (!statusBox) throw new Error("File status has no bounding box")
const viewportBox = await viewport.boundingBox()
if (!viewportBox) throw new Error("File tree viewport has no bounding box")
expect(viewportBox.x + viewportBox.width - statusBox.x - statusBox.width).toBeLessThanOrEqual(24)
await viewport.hover()
const horizontalThumb = sidebar.locator('.scroll-view__thumb[data-orientation="horizontal"]')
await expect(horizontalThumb).toHaveCSS("opacity", "1")
await page.mouse.wheel(1_000, 0)
await expect.poll(() => viewport.evaluate((element) => Math.abs(element.scrollLeft))).toBeGreaterThan(0)
await expect(horizontalThumb).toHaveAttribute("data-visible", "true")
await expect
.poll(() =>
status.evaluate((element) => {
const viewport = element.closest<HTMLElement>(".scroll-view__viewport")!.getBoundingClientRect()
return viewport.right - element.getBoundingClientRect().right
}),
)
.toBeLessThanOrEqual(24)
const beforeDrag = await viewport.evaluate((element) => Math.abs(element.scrollLeft))
const thumbBox = await horizontalThumb.boundingBox()
if (!thumbBox) throw new Error("Horizontal scrollbar thumb has no bounding box")
await page.mouse.move(thumbBox.x + thumbBox.width / 2, thumbBox.y + thumbBox.height / 2)
await page.mouse.down()
await page.mouse.move(thumbBox.x + thumbBox.width / 2 - 40, thumbBox.y + thumbBox.height / 2)
await page.mouse.up()
await expect.poll(() => viewport.evaluate((element) => Math.abs(element.scrollLeft))).toBeLessThan(beforeDrag)
const filter = panel.getByRole("combobox", { name: "Filter files" })
await filter.fill(longFilename)
const filteredRow = panel.getByRole("option", { name: longFilename })
await expect(filteredRow).toBeVisible()
const filteredStatus = filteredRow.locator('[data-slot="file-tree-v2-change"]')
await expect(filteredStatus).toHaveText("A")
await expect.poll(() => viewport.evaluate((element) => element.scrollWidth - element.clientWidth)).toBeGreaterThan(0)
await viewport.evaluate((element) => {
element.setAttribute("dir", "rtl")
element.scrollLeft = 0
element.dispatchEvent(new Event("scroll"))
})
await expect
.poll(() =>
filteredStatus.evaluate((element) => {
const viewport = element.closest<HTMLElement>(".scroll-view__viewport")!.getBoundingClientRect()
return element.getBoundingClientRect().left - viewport.left
}),
)
.toBeLessThanOrEqual(24)
const rtlThumbBox = await horizontalThumb.boundingBox()
if (!rtlThumbBox) throw new Error("RTL horizontal scrollbar thumb has no bounding box")
await page.mouse.move(rtlThumbBox.x + rtlThumbBox.width / 2, rtlThumbBox.y + rtlThumbBox.height / 2)
await page.mouse.down()
await page.mouse.move(rtlThumbBox.x + rtlThumbBox.width / 2 - 40, rtlThumbBox.y + rtlThumbBox.height / 2)
await page.mouse.up()
await expect.poll(() => viewport.evaluate((element) => element.scrollLeft)).toBeLessThan(0)
await viewport.evaluate((element) => {
element.removeAttribute("dir")
element.scrollLeft = 0
element.dispatchEvent(new Event("scroll"))
})
await filter.fill("")
const appRow = panel.locator('[data-slot="file-tree-v2-row"][data-path="frontend/app.ts"]')
await expect(appRow).toBeVisible()
await appRow.click()
-9
View File
@@ -165,15 +165,6 @@
}
}
::highlight(timeline-search-hit) {
background-color: color-mix(in srgb, var(--v2-icon-icon-accent) 28%, transparent);
}
::highlight(timeline-search-hit-active) {
background-color: var(--v2-icon-icon-accent);
color: var(--v2-background-bg-deep);
}
[data-component="getting-started"] {
container-type: inline-size;
container-name: getting-started;
+1 -13
View File
@@ -676,7 +676,7 @@ export const dict = {
"session.error.incompatible.description":
"{{server}} is running OpenCode {{version}}, which isn't compatible with this app. Upgrade the server to OpenCode V2 to continue.",
"session.background.moveTasks": "Move {{tasks}} to background",
"session.background.moveRunning": "Move to background",
"session.background.moveRunning": "Move running work to background",
"session.background.inBackground": "Running {{tasks}} in background",
"session.background.moveInline": "Press {{keybind}} to move running work to the background",
"session.background.running": "Running work in background",
@@ -736,16 +736,6 @@ export const dict = {
"session.todo.expand": "Expand",
"session.todo.progress": "{{done}} of {{total}} todos completed",
"session.question.progress": "{{current}} of {{total}} questions",
"session.websearch.title": "Third-party web search",
"session.websearch.description": "Select the search provider agents use to search the web",
"session.websearch.provider": "Search provider",
"session.websearch.any": "Any",
"session.websearch.disable": "Dont use search",
"session.websearch.enable": "Enable",
"session.websearch.loadFailed": "Could not load search providers.",
"session.websearch.empty": "No search providers available.",
"session.websearch.failed": "Could not save your choice. Please try again.",
"session.websearch.retry": "Retry",
"session.question.minimize": "Minimize question",
"session.question.restore": "Restore question",
"session.question.pending.one": "{{count}} pending question",
@@ -769,8 +759,6 @@ export const dict = {
"session.header.search.placeholder": "Search {{project}}",
"session.header.searchFiles": "Search files",
"session.search.placeholder": "Find...",
"session.search.noResults": "No matches",
"session.header.openIn": "Open in",
"session.header.open.action": "Open {{app}}",
"session.header.open.ariaLabel": "Open in {{app}}",
@@ -1,23 +1,19 @@
import { describe, expect, test } from "bun:test"
import { createRequestQueue, isSlowRequest } from "./request-queue"
import { createRequestQueue } from "./request-queue"
function setup(input?: { limit?: number; slowLimit?: number; stallMs?: number; headersTimeoutMs?: number }) {
const pending: Array<{ url: string; signal: AbortSignal; resolve: () => void }> = []
function setup(input?: { limit?: number; stallMs?: number }) {
const pending: Array<{ url: string; resolve: () => void }> = []
const logs: Array<{ message: string; data: Record<string, unknown> }> = []
let clock = 0
const queue = createRequestQueue({
limit: input?.limit ?? 2,
slowLimit: input?.slowLimit,
stallMs: input?.stallMs,
headersTimeoutMs: input?.headersTimeoutMs,
now: () => clock,
log: (message, data) => logs.push({ message, data }),
fetch: Object.assign(
(resource: RequestInfo | URL) =>
new Promise<Response>((resolve, reject) => {
const request = new Request(resource)
request.signal.addEventListener("abort", () => reject(request.signal.reason), { once: true })
pending.push({ url: request.url, signal: request.signal, resolve: () => resolve(new Response("ok")) })
new Promise<Response>((resolve) => {
pending.push({ url: new Request(resource).url, resolve: () => resolve(new Response("ok")) })
}),
{ preconnect() {} },
),
@@ -41,36 +37,6 @@ describe("createRequestQueue", () => {
expect(input.queue.inflight()).toBe(0)
})
test("slow endpoints hold at most their share of slots so small reads go first", async () => {
const input = setup({ limit: 4, slowLimit: 2 })
const paths = ["/api/vcs?location[directory]=%2Fa", "/api/vcs/diff?location[directory]=%2Fa", "/api/worktree", "/api/session/ses_1"]
const responses = paths.map((path) => input.queue.fetch(`http://server${path}`))
await input.settle()
const started = () => input.pending.map((item) => new URL(item.url).pathname)
// Two slow requests fill the slow share; the worktree read waits while the session read jumps ahead.
expect(started()).toEqual(["/api/vcs", "/api/vcs/diff", "/api/session/ses_1"])
expect(input.queue.inflight()).toBe(3)
expect(input.queue.queued()).toBe(1)
// A fast request finishing does not free a slow slot.
input.pending[2]!.resolve()
await input.settle()
expect(started()).toEqual(["/api/vcs", "/api/vcs/diff", "/api/session/ses_1"])
input.pending[0]!.resolve()
await input.settle()
expect(started()).toEqual(["/api/vcs", "/api/vcs/diff", "/api/session/ses_1", "/api/worktree"])
input.pending.forEach((item) => item.resolve())
await Promise.all(responses)
expect(input.queue.inflight()).toBe(0)
})
test("classifies git and worktree endpoints as slow", () => {
expect(isSlowRequest("/api/vcs")).toBe(true)
expect(isSlowRequest("/api/vcs/branches")).toBe(true)
expect(isSlowRequest("/api/worktree")).toBe(true)
expect(isSlowRequest("/api/vcsx")).toBe(false)
expect(isSlowRequest("/api/session")).toBe(false)
})
test("never counts the event stream against the budget", async () => {
const input = setup({ limit: 1 })
void input.queue.fetch("http://server/api/session")
@@ -93,34 +59,6 @@ describe("createRequestQueue", () => {
expect(input.queue.inflight()).toBe(0)
})
test("a request the server never answers times out and frees its slot", async () => {
const input = setup({ limit: 1, headersTimeoutMs: 10 })
const dead = input.queue.fetch("http://server/api/dead")
const next = input.queue.fetch("http://server/api/next")
await input.settle()
expect(input.queue.queued()).toBe(1)
const error = await dead.catch((cause: unknown) => cause)
expect(error).toBeInstanceOf(DOMException)
expect((error as DOMException).name).toBe("TimeoutError")
await input.settle()
expect(input.pending.map((item) => new URL(item.url).pathname)).toEqual(["/api/dead", "/api/next"])
input.pending[1]!.resolve()
await expect(next).resolves.toBeInstanceOf(Response)
expect(input.queue.inflight()).toBe(0)
})
test("caller aborts still reach the underlying request", async () => {
const input = setup({ limit: 1 })
const controller = new AbortController()
const request = input.queue.fetch("http://server/api/slow", { signal: controller.signal })
await input.settle()
expect(input.pending[0]!.signal.aborted).toBe(false)
controller.abort()
expect(input.pending[0]!.signal.aborted).toBe(true)
await expect(request).rejects.toBeInstanceOf(DOMException)
expect(input.queue.inflight()).toBe(0)
})
test("a burst that drains promptly is not thrashing", async () => {
const input = setup({ stallMs: 5 })
const responses = Array.from({ length: 12 }, (_, index) => input.queue.fetch(`http://server/api/${index}`))
@@ -1,41 +1,23 @@
type Entry = { method: string; url: string; at: number; slow: boolean }
type Entry = { method: string; url: string; at: number }
// Chromium allows six connections per origin. The event stream holds one for the life of the
// connection and health probes use their own fetch, so the app's API calls stay below that or
// a burst stalls probes and user actions inside the browser where nothing can observe it.
export const requestQueueLimit = 4
// Endpoints that shell out to git or walk the filesystem take seconds on a large repository. They
// may hold at most this many slots, so a session mount's small reads never queue behind them.
export const requestQueueSlowLimit = 2
export const slowRequestPaths = ["/api/vcs", "/api/worktree"]
// A mount legitimately fires a dozen requests at once; only a request that has waited this long
// for a slot indicates the server is not keeping up.
export const requestStallMs = 2_000
// A socket that dies while the device sleeps can leave fetch waiting for response headers until the
// OS gives up on TCP retransmits, which takes minutes. Bound that so a dead request frees its slot
// instead of wedging every later API call; the body may still stream for as long as it needs.
export const requestHeadersTimeoutMs = 60_000
export function isSlowRequest(pathname: string) {
return slowRequestPaths.some((path) => pathname === path || pathname.startsWith(`${path}/`))
}
export function createRequestQueue(input: {
fetch: typeof globalThis.fetch
limit?: number
slowLimit?: number
stallMs?: number
headersTimeoutMs?: number
log?: (message: string, data: Record<string, unknown>) => void
now?: () => number
}) {
const limit = input.limit ?? requestQueueLimit
const slowLimit = input.slowLimit ?? requestQueueSlowLimit
const stallMs = input.stallMs ?? requestStallMs
const headersTimeoutMs = input.headersTimeoutMs ?? requestHeadersTimeoutMs
// Call the browser fetch unbound; `input.fetch(...)` would make `this` the options object.
const base = input.fetch
const now = input.now ?? Date.now
@@ -61,17 +43,9 @@ export function createRequestQueue(input: {
}
watcher = setTimeout(watch, stallMs)
}
const canStart = (entry: Entry) => {
if (inflight.size >= limit) return false
if (!entry.slow) return true
return [...inflight].filter((item) => item.slow).length < slowLimit
}
// FIFO, except a slow request waits its turn behind faster ones while the slow slots are full.
const release = (entry: Entry) => {
inflight.delete(entry)
const index = waiting.findIndex((item) => canStart(item.entry))
if (index === -1) return
waiting.splice(index, 1)[0]?.start()
waiting.shift()?.start()
}
const acquire = (entry: Entry) =>
new Promise<void>((resolve) => {
@@ -80,7 +54,7 @@ export function createRequestQueue(input: {
inflight.add(entry)
resolve()
}
if (canStart(entry)) return start()
if (inflight.size < limit) return start()
waiting.push({ entry, start })
watcher ??= setTimeout(watch, stallMs)
})
@@ -88,25 +62,15 @@ export function createRequestQueue(input: {
const fetch: typeof globalThis.fetch = Object.assign(
async (resource: RequestInfo | URL, init?: RequestInit) => {
const request = new Request(resource, init)
const pathname = new URL(request.url).pathname
// The event stream is long-lived; never count it against the request budget.
if (pathname === "/api/event") return base(request)
const entry = { method: request.method, url: request.url, at: now(), slow: isSlowRequest(pathname) }
if (new URL(request.url).pathname === "/api/event") return base(request)
const entry = { method: request.method, url: request.url, at: now() }
await acquire(entry)
if (request.signal.aborted) {
release(entry)
throw request.signal.reason ?? new DOMException("The operation was aborted.", "AbortError")
}
const controller = new AbortController()
request.signal.addEventListener("abort", () => controller.abort(request.signal.reason), { once: true })
const timer = setTimeout(
() => controller.abort(new DOMException("Timed out waiting for the server to respond", "TimeoutError")),
headersTimeoutMs,
)
return base(new Request(request, { signal: controller.signal })).finally(() => {
clearTimeout(timer)
release(entry)
})
return base(request).finally(() => release(entry))
},
// Bun's fetch type carries preconnect; the browser never calls it.
{ preconnect: () => {} },
@@ -1,6 +1,6 @@
import { expect, test } from "bun:test"
import { createRoot, createSignal } from "solid-js"
import { createConnectionSync, reconnectOrder } from "./connection"
import { createConnectionSync } from "./connection"
test("invalidates disconnected data and synchronizes after the handshake", () => {
const calls: string[] = []
@@ -19,9 +19,3 @@ test("invalidates disconnected data and synchronizes after the handshake", () =>
})
dispose()
})
test("held directories refresh before the rest, otherwise keeping their order", () => {
const held = new Set(["/b", "/d"])
expect(reconnectOrder(["/a", "/b", "/c", "/d"], (directory) => held.has(directory))).toEqual(["/b", "/d", "/a", "/c"])
expect(reconnectOrder(["/a", "/c"], (directory) => held.has(directory))).toEqual(["/a", "/c"])
})
@@ -20,8 +20,3 @@ export function createConnectionSync(input: {
return { handleEvent }
}
// Directories a mounted view holds refresh first; the rest keep their existing order behind them.
export function reconnectOrder(directories: string[], held: (directory: string) => boolean) {
return [...directories.filter(held), ...directories.filter((directory) => !held(directory))]
}
+7 -6
View File
@@ -17,7 +17,7 @@ import type { ServerScope } from "@/runtime/server/scope"
import { persisted } from "@/runtime/persistence/storage"
import type { ServerApi } from "@/runtime/server/api"
import { toggleMcp } from "./global-sync/mcp"
import { createConnectionSync, reconnectOrder } from "./server-sync/connection"
import { createConnectionSync } from "./server-sync/connection"
import { usePlatform } from "@/runtime/platform/platform"
import type { Data } from "@opencode-ai/client/solid"
import { createWorktreeInventory, withWorktreeInventory } from "@/workspaces/inventory"
@@ -162,11 +162,12 @@ export function createServerSyncContextInner(serverSDK: ServerSDK, data: Data) {
},
connected: (info) => {
if (bootstrap.data !== undefined && !bootstrap.isFetching) void bootstrap.refetch()
// The refresh queue re-syncs two directories at a time, held ones first. Syncing every active
// directory here as well sent the whole catalog fan-out for all of them at once.
reconnectOrder(Object.keys(children.children).filter(children.active), children.pinned).forEach(
(directory) => queue.push(directory),
)
Object.keys(children.children)
.filter(children.active)
.forEach((directory) => {
queue.push(directory)
void data.location.sync({ directory }).catch(() => undefined)
})
},
})
@@ -2,12 +2,11 @@ import { Show, type JSX } from "solid-js"
import { useLanguage } from "@/runtime/i18n/language"
import { SessionPermissionDock } from "@/session/requests/session-permission-dock"
import { SessionQuestionDock } from "@/session/requests/session-question-dock"
import { SessionWebSearchDock } from "@/session/requests/session-websearch-dock"
import type { SessionComposerRegionController } from "./session-composer-region-controller"
type SessionComposerRegionState = Pick<
SessionComposerRegionController["state"],
"questionRequest" | "websearch" | "permissionRequest" | "permissionResponding" | "decide" | "blocked"
"questionRequest" | "permissionRequest" | "permissionResponding" | "decide" | "blocked"
>
export type SessionComposerRegionViewController = Pick<
@@ -33,9 +32,6 @@ export function SessionComposerRegion(props: {
"md:max-w-[1000px] md:mx-auto": controller.centered(),
}}
>
<Show when={controller.state.websearch.request()}>
<SessionWebSearchDock model={controller.state.websearch} onSubmit={controller.onResponseSubmit} />
</Show>
<Show when={controller.state.questionRequest()} keyed>
{(request) => (
<div>
+23 -62
View File
@@ -24,11 +24,6 @@ import {
type FileTreeV2Node,
} from "@/session/files/file-tree-v2-model"
import { virtualScrollElement } from "@/session/files/virtual-scroll"
import { useWorkspaceLocation } from "@/workspaces/location"
import { useOpenInApp } from "@/session/files/open-in-app"
import { OpenInAppContextMenuV2 } from "@/session/files/open-in-app-button"
import { resolveOpenInAppPath } from "@/session/files/open-in-app-path"
import { usePlatform } from "@/runtime/platform/platform"
export type { Kind } from "@/session/files/file-tree"
@@ -104,7 +99,7 @@ const FileTreeNodeV2 = (
{...rest}
>
{local.children}
<span data-slot="file-tree-v2-label" class="flex-1 shrink-0 text-start text-12-medium whitespace-nowrap">
<span class="flex-1 min-w-0 text-start text-12-medium whitespace-nowrap truncate">
<bdi dir="auto">
{local.node.type === "directory"
? normalizeFileTreeV2Path(local.node.path).split("/").at(-1)
@@ -141,9 +136,6 @@ export default function FileTreeV2(props: {
onFileDoubleClick?: (file: FileNode) => void
}) {
const file = useFile()
const location = useWorkspaceLocation()
const platform = usePlatform()
const openIn = platform.platform === "desktop" ? useOpenInApp({ path: () => location().directory }) : undefined
const live = () => props.allowed === undefined
const draggable = () => props.draggable ?? true
const active = () => normalizeFileTreeV2Path(props.active ?? "")
@@ -225,19 +217,6 @@ export default function FileTreeV2(props: {
)
const virtualRowKeys = createMemo(() => virtualizer.getVirtualItems().map((item) => item.key))
createEffect(() => {
rows()
const element = root()
if (!element) return
element.style.removeProperty("width")
syncFileTreeV2Width(element)
})
createEffect(() => {
virtualRowKeys()
syncFileTreeV2Width(root())
})
return (
<div
ref={setRoot}
@@ -256,7 +235,6 @@ export default function FileTreeV2(props: {
top: "0",
"inset-inline-start": "0",
width: "100%",
"min-width": "max-content",
height: `${item().size}px`,
transform: `translateY(${item().start}px)`,
}}
@@ -266,36 +244,29 @@ export default function FileTreeV2(props: {
<Show
when={row().node.type === "directory"}
fallback={
<OpenInAppContextMenuV2
state={openIn}
path={() =>
resolveOpenInAppPath(location().directory, row().node.absolute || row().node.originalPath)
}
<FileTreeNodeV2
node={row().node}
level={row().level}
active={active()}
draggable={draggable()}
kinds={props.kinds}
as="button"
type="button"
class="relative"
onFocus={() => setFocused(row().node.path)}
onBlur={() => setFocused(undefined)}
onClick={() => selectFile(row().node, props.onFileClick)}
onDblClick={() => selectFile(row().node, props.onFileDoubleClick)}
>
<FileTreeNodeV2
node={row().node}
level={row().level}
active={active()}
draggable={draggable()}
kinds={props.kinds}
as="button"
type="button"
class="relative"
onFocus={() => setFocused(row().node.path)}
onBlur={() => setFocused(undefined)}
onClick={() => selectFile(row().node, props.onFileClick)}
onDblClick={() => selectFile(row().node, props.onFileDoubleClick)}
>
<GuideLines level={row().level} />
<Show when={row().level > 0}>
<div class="w-4 shrink-0" />
</Show>
<span class="filetree-iconpair size-4">
<FileIcon node={row().node} class="size-4 filetree-icon filetree-icon--color" />
<FileIcon node={row().node} class="size-4 filetree-icon filetree-icon--mono" mono />
</span>
</FileTreeNodeV2>
</OpenInAppContextMenuV2>
<GuideLines level={row().level} />
<Show when={row().level > 0}>
<div class="w-4 shrink-0" />
</Show>
<span class="filetree-iconpair size-4">
<FileIcon node={row().node} class="size-4 filetree-icon filetree-icon--color" />
<FileIcon node={row().node} class="size-4 filetree-icon filetree-icon--mono" mono />
</span>
</FileTreeNodeV2>
}
>
<FileTreeNodeV2
@@ -332,13 +303,3 @@ export default function FileTreeV2(props: {
</div>
)
}
export function syncFileTreeV2Width(element?: HTMLDivElement) {
if (!element) return
queueMicrotask(() => {
if (!element.isConnected) return
const width = Math.max(element.clientWidth, ...Array.from(element.children, (child) => child.scrollWidth))
if (width <= element.clientWidth) return
element.style.width = `${width}px`
})
}
+34 -56
View File
@@ -2,15 +2,10 @@ import { FileIcon } from "@opencode-ai/ui/file-icon"
import "@opencode-ai/ui/file-tree.css"
import { getDirectory, getFilename } from "@opencode-ai/util/path"
import { createEffect, createMemo, createSignal, For, Show } from "solid-js"
import { kindChange, kindLabel, syncFileTreeV2Width, type Kind } from "@/session/files/file-tree-v2"
import { kindChange, kindLabel, type Kind } from "@/session/files/file-tree-v2"
import { normalizePath } from "@/session/review/review-diff-kinds"
import { createVirtualizer, defaultRangeExtractor } from "@tanstack/solid-virtual"
import { virtualScrollElement } from "@/session/files/virtual-scroll"
import { useWorkspaceLocation } from "@/workspaces/location"
import { useOpenInApp } from "@/session/files/open-in-app"
import { OpenInAppContextMenuV2 } from "@/session/files/open-in-app-button"
import { resolveOpenInAppPath } from "@/session/files/open-in-app-path"
import { usePlatform } from "@/runtime/platform/platform"
// Drives the highlight/selection of the flat search-result list from the filter
// input's keyboard events.
@@ -54,9 +49,6 @@ export function SessionFileList(props: {
onFileClick: (path: string) => void
onFileDoubleClick?: (path: string) => void
}) {
const location = useWorkspaceLocation()
const platform = usePlatform()
const openIn = platform.platform === "desktop" ? useOpenInApp({ path: () => location().directory }) : undefined
const active = () => normalizePath(props.active ?? "")
const highlighted = () => normalizePath(props.highlighted ?? "")
const normalized = createMemo(() => props.files.map(normalizePath))
@@ -97,19 +89,6 @@ export function SessionFileList(props: {
)
const virtualRowKeys = createMemo(() => virtualizer.getVirtualItems().map((item) => item.key))
createEffect(() => {
normalized()
const element = root()
if (!element) return
element.style.removeProperty("width")
syncFileTreeV2Width(element)
})
createEffect(() => {
virtualRowKeys()
syncFileTreeV2Width(root())
})
return (
<div
ref={setRoot}
@@ -135,48 +114,47 @@ export function SessionFileList(props: {
style={{
position: "absolute",
top: "0",
"inset-inline-start": "0",
left: "0",
width: "100%",
"min-width": "max-content",
height: `${item().size}px`,
transform: `translateY(${item().start}px)`,
}}
>
<OpenInAppContextMenuV2 state={openIn} path={() => resolveOpenInAppPath(location().directory, path)}>
<button
type="button"
id={props.optionID?.(path)}
role={props.role ? "option" : undefined}
aria-selected={props.role ? selected() : undefined}
data-slot="file-tree-v2-row"
data-path={path}
data-selected={selected() ? "" : undefined}
data-highlighted={highlightedRow() ? "" : undefined}
style="padding-inline-start: 8px"
onFocus={() => setFocused(path)}
onBlur={() => setFocused(undefined)}
onClick={() => props.onFileClick(path)}
onDblClick={() => props.onFileDoubleClick?.(path)}
>
<span class="filetree-iconpair size-4">
<FileIcon node={{ path, type: "file" }} class="size-4 filetree-icon filetree-icon--color" />
<FileIcon node={{ path, type: "file" }} class="size-4 filetree-icon filetree-icon--mono" mono />
</span>
<span data-slot="file-tree-v2-label" class="flex flex-1 shrink-0 items-center whitespace-nowrap">
<Show when={directory()}>
{(value) => <span class="text-12-medium text-text-muted shrink-0">{value()}</span>}
</Show>
<span class="text-12-medium text-text-base shrink-0">{filename()}</span>
</span>
<Show when={kind()}>
<button
type="button"
id={props.optionID?.(path)}
role={props.role ? "option" : undefined}
aria-selected={props.role ? selected() : undefined}
data-slot="file-tree-v2-row"
data-path={path}
data-selected={selected() ? "" : undefined}
data-highlighted={highlightedRow() ? "" : undefined}
style="padding-left: 8px"
onFocus={() => setFocused(path)}
onBlur={() => setFocused(undefined)}
onClick={() => props.onFileClick(path)}
onDblClick={() => props.onFileDoubleClick?.(path)}
>
<span class="filetree-iconpair size-4">
<FileIcon node={{ path, type: "file" }} class="size-4 filetree-icon filetree-icon--color" />
<FileIcon node={{ path, type: "file" }} class="size-4 filetree-icon filetree-icon--mono" mono />
</span>
<span class="flex min-w-0 flex-1 items-center overflow-hidden whitespace-nowrap">
<Show when={directory()}>
{(value) => (
<span data-slot="file-tree-v2-change" data-change={kindChange(value())}>
{kindLabel(value())}
</span>
<span class="text-12-medium text-text-muted truncate min-w-0 shrink">{value()}</span>
)}
</Show>
</button>
</OpenInAppContextMenuV2>
<span class="text-12-medium text-text-base truncate min-w-0 shrink-0">{filename()}</span>
</span>
<Show when={kind()}>
{(value) => (
<span data-slot="file-tree-v2-change" data-change={kindChange(value())}>
{kindLabel(value())}
</span>
)}
</Show>
</button>
</div>
)}
</Show>
@@ -1,4 +1,4 @@
import { createSignal, For, Show, type ParentProps } from "solid-js"
import { For, Show } from "solid-js"
import { AppIcon } from "@opencode-ai/ui/app-icon"
import { Icon } from "@opencode-ai/ui/icon"
import { Spinner } from "@opencode-ai/ui/spinner"
@@ -10,7 +10,7 @@ import { type OpenApp, useOpenInApp } from "@/session/files/open-in-app"
export function OpenInAppButton(props: { directory: () => string }) {
const language = useLanguage()
const state = useOpenInApp({ path: props.directory })
const state = useOpenInApp(props)
return (
<Show when={props.directory() && state.canOpen()}>
@@ -25,7 +25,7 @@ export function OpenInAppButton(props: { directory: () => string }) {
onClick={(event) => {
event.stopPropagation()
if (state.opening()) return
state.openPath(state.current().id)
state.openDir(state.current().id)
}}
disabled={state.opening()}
aria-label={language.t("session.header.open.ariaLabel", { app: state.current().label })}
@@ -52,7 +52,42 @@ export function OpenInAppButton(props: { directory: () => string }) {
</Menu.Trigger>
<Menu.Portal>
<Menu.Content class="open-in-app-v2-menu">
<OpenInAppMenuItemsV2 state={state} close={() => state.setMenu("open", false)} />
<Menu.Group>
<Menu.GroupLabel>{language.t("session.header.openIn")}</Menu.GroupLabel>
<Menu.RadioGroup
value={state.current().id}
onChange={(value) => {
state.selectApp(value as OpenApp)
}}
>
<For each={state.options()}>
{(option) => (
<Menu.RadioItem
value={option.id}
disabled={state.opening()}
onSelect={() => {
state.selectApp(option.id)
state.setMenu("open", false)
state.openDir(option.id)
}}
>
<AppIcon id={option.icon} />
{option.label}
</Menu.RadioItem>
)}
</For>
</Menu.RadioGroup>
</Menu.Group>
<Menu.Separator />
<Menu.Item
onSelect={() => {
state.setMenu("open", false)
state.copyPath()
}}
>
<Icon name="copy" size="small" class="text-icon-weak" />
{language.t("session.header.open.copyPath")}
</Menu.Item>
</Menu.Content>
</Menu.Portal>
</Menu>
@@ -60,116 +95,3 @@ export function OpenInAppButton(props: { directory: () => string }) {
</Show>
)
}
type OpenInAppState = ReturnType<typeof useOpenInApp>
function OpenInAppMenuItemsV2(props: {
state: OpenInAppState
path?: () => string
reveal?: boolean
selection?: boolean
close?: () => void
}) {
const language = useLanguage()
const path = () => props.path?.()
return (
<>
<Menu.Group>
<Menu.GroupLabel>{language.t("session.header.openIn")}</Menu.GroupLabel>
<Show
when={props.selection !== false}
fallback={
<For each={props.state.options()}>
{(option) => (
<Menu.Item
disabled={props.state.opening()}
onSelect={() => {
props.state.selectApp(option.id)
props.close?.()
props.state.openPath(option.id, path(), props.reveal)
}}
>
<AppIcon id={option.icon} />
{option.label}
</Menu.Item>
)}
</For>
}
>
<Menu.RadioGroup
value={props.state.current().id}
onChange={(value) => {
props.state.selectApp(value as OpenApp)
}}
>
<For each={props.state.options()}>
{(option) => (
<Menu.RadioItem
value={option.id}
closeOnSelect
disabled={props.state.opening()}
onSelect={() => {
props.state.selectApp(option.id)
props.close?.()
props.state.openPath(option.id, path(), props.reveal)
}}
>
<AppIcon id={option.icon} />
{option.label}
</Menu.RadioItem>
)}
</For>
</Menu.RadioGroup>
</Show>
</Menu.Group>
<Menu.Separator />
<Menu.Item
onSelect={() => {
props.close?.()
props.state.copyPath(path())
}}
>
<Icon name="copy" size="small" class="text-icon-weak" />
{language.t("session.header.open.copyPath")}
</Menu.Item>
</>
)
}
export function OpenInAppContextMenuV2(
props: ParentProps<{
state?: OpenInAppState
path: () => string
}>,
) {
const state = props.state
if (!state) return props.children
const [open, setOpen] = createSignal(false)
return (
<Show when={state.canOpen() && props.path()} fallback={props.children}>
<Menu.Context modal={false} onOpenChange={setOpen}>
<Menu.Context.Trigger
as="div"
class="h-full w-full min-w-max"
data-slot="file-tree-v2-context-trigger"
data-context-menu-open={open() ? "" : undefined}
>
{props.children}
</Menu.Context.Trigger>
<Menu.Context.Portal>
<Menu.Context.Content class="open-in-app-v2-menu">
<OpenInAppMenuItemsV2
state={state}
path={props.path}
reveal
selection={false}
close={() => setOpen(false)}
/>
</Menu.Context.Content>
</Menu.Context.Portal>
</Menu.Context>
</Show>
)
}
@@ -1,36 +0,0 @@
import { describe, expect, test } from "bun:test"
import { openInAppParentPath, resolveOpenInAppPath } from "./open-in-app-path"
describe("resolveOpenInAppPath", () => {
test("joins relative paths using the workspace separator", () => {
expect(resolveOpenInAppPath("/workspace/project", "src/file.ts")).toBe("/workspace/project/src/file.ts")
expect(resolveOpenInAppPath("C:\\workspace\\project", "src/file.ts")).toBe("C:\\workspace\\project\\src\\file.ts")
})
test("does not duplicate root separators", () => {
expect(resolveOpenInAppPath("/workspace/project/", "src/file.ts")).toBe("/workspace/project/src/file.ts")
expect(resolveOpenInAppPath("C:/workspace/project/", "src\\file.ts")).toBe("C:/workspace/project/src/file.ts")
})
test("preserves backslashes in POSIX filenames", () => {
expect(resolveOpenInAppPath("/workspace", "src\\file.ts")).toBe("/workspace/src\\file.ts")
expect(resolveOpenInAppPath("/workspace", "\\file.ts")).toBe("/workspace/\\file.ts")
})
test("preserves absolute POSIX, Windows, and UNC paths", () => {
expect(resolveOpenInAppPath("/workspace", "/tmp/file.ts")).toBe("/tmp/file.ts")
expect(resolveOpenInAppPath("C:/workspace", "D:\\src\\file.ts")).toBe("D:\\src\\file.ts")
expect(resolveOpenInAppPath("C:/workspace", "\\\\server\\share\\file.ts")).toBe("\\\\server\\share\\file.ts")
expect(resolveOpenInAppPath("C:/workspace", "\\src\\file.ts")).toBe("\\src\\file.ts")
})
})
describe("openInAppParentPath", () => {
test("preserves POSIX and Windows roots", () => {
expect(openInAppParentPath("/file.ts")).toBe("/")
expect(openInAppParentPath("/workspace/file.ts")).toBe("/workspace")
expect(openInAppParentPath("C:\\file.ts")).toBe("C:\\")
expect(openInAppParentPath("C:\\workspace\\file.ts")).toBe("C:\\workspace")
expect(openInAppParentPath("\\\\server\\share\\file.ts")).toBe("\\\\server\\share")
})
})
@@ -1,19 +0,0 @@
export function resolveOpenInAppPath(root: string, path: string) {
if (!path) return root
const windowsRoot = root.startsWith("\\\\") || /^[A-Za-z]:[\\/]/.test(root)
if (path.startsWith("/") || (windowsRoot && path.startsWith("\\")) || /^[A-Za-z]:[\\/]/.test(path)) return path
if (!root) return path
const separator = root.includes("\\") ? "\\" : "/"
const relative = windowsRoot ? path.replace(/^[\\/]+/, "") : path
return `${root.replace(/[\\/]+$/, "")}${separator}${windowsRoot ? relative.replaceAll(separator === "\\" ? "/" : "\\", separator) : relative}`
}
export function openInAppParentPath(path: string) {
const value = path.replace(/[\\/]+$/, "")
const index = Math.max(value.lastIndexOf("/"), value.lastIndexOf("\\"))
if (index < 0) return path
if (index === 0) return value.slice(0, 1)
if (index === 2 && /^[A-Za-z]:/.test(value)) return value.slice(0, 3)
return value.slice(0, index)
}
+21 -30
View File
@@ -7,8 +7,6 @@ import { showToast } from "@/shell/notifications/toast"
import { useServer } from "@/runtime/server/current"
import { Schema } from "effect"
import { Persistence } from "@/runtime/persistence/schema"
import { fileManagerApp } from "@/home/projects/file-manager"
import { openInAppParentPath } from "@/session/files/open-in-app-path"
export const OPEN_APPS = [
"vscode",
@@ -34,8 +32,6 @@ export const OpenAppPreferences = Persistence.struct({
app: Schema.Literals(OPEN_APPS),
})
const appExistence = new Map<string, Promise<boolean>>()
export const MAC_OPEN_APPS = [
{
id: "vscode",
@@ -112,7 +108,9 @@ export function detectOpenAppOS(platform: ReturnType<typeof usePlatform>): OpenA
}
export function openAppFileManager(os: OpenAppOS) {
return fileManagerApp(os)
if (os === "macos") return { label: "session.header.open.finder", icon: "finder" as const }
if (os === "windows") return { label: "session.header.open.fileExplorer", icon: "file-explorer" as const }
return { label: "session.header.open.fileManager", icon: "finder" as const }
}
export function openAppsForOS(os: OpenAppOS) {
@@ -129,7 +127,7 @@ const showRequestError = (language: ReturnType<typeof useLanguage>, err: unknown
})
}
export function useOpenInApp(input: { path: () => string }) {
export function useOpenInApp(input: { directory: () => string }) {
const platform = usePlatform()
const server = useServer()
const language = useLanguage()
@@ -151,7 +149,12 @@ export function useOpenInApp(input: { path: () => string }) {
setExists(Object.fromEntries(list.map((app) => [app.id, undefined])) as Partial<Record<OpenApp, boolean>>)
void Promise.all(
list.map((app) => checkAppExists(platform, app.openWith).then((ok) => [app.id, ok] as const)),
list.map((app) =>
Promise.resolve(platform.checkAppExists?.(app.openWith))
.then((value) => Boolean(value))
.catch(() => false)
.then((ok) => [app.id, ok] as const),
),
).then((entries) => {
setExists(Object.fromEntries(entries) as Partial<Record<OpenApp, boolean>>)
})
@@ -186,35 +189,33 @@ export function useOpenInApp(input: { path: () => string }) {
setPrefs("app", app)
}
const openPath = (app: OpenApp | "finder", target = input.path(), reveal = false) => {
const openDir = (app: OpenApp | "finder") => {
if (opening() || !canOpen() || !platform.openPath) return
if (!target) return
const directory = input.directory()
if (!directory) return
const open = (path: string, openWith?: string) => platform.openPath!(path, openWith)
const item = options().find((o) => o.id === app)
const openWith = item && "openWith" in item ? item.openWith : undefined
setOpenRequest("app", app)
const request =
app === "finder" && reveal && platform.revealPath
? platform.revealPath(target).then((revealed) => (revealed ? undefined : open(openInAppParentPath(target))))
: open(target, openWith)
request
platform
.openPath(directory, openWith)
.catch((err: unknown) => showRequestError(language, err))
.finally(() => {
setOpenRequest("app", undefined)
})
}
const copyPath = (target = input.path()) => {
if (!target) return
const copyPath = () => {
const directory = input.directory()
if (!directory) return
navigator.clipboard
.writeText(target)
.writeText(directory)
.then(() => {
showToast({
variant: "success",
icon: "circle-check",
title: language.t("common.copied"),
description: target,
description: directory,
})
})
.catch((err: unknown) => showRequestError(language, err))
@@ -227,18 +228,8 @@ export function useOpenInApp(input: { path: () => string }) {
options,
menu,
setMenu,
openPath,
openDir,
selectApp,
copyPath,
}
}
function checkAppExists(platform: ReturnType<typeof usePlatform>, app: string) {
const cached = appExistence.get(app)
if (cached) return cached
const request = Promise.resolve(platform.checkAppExists?.(app))
.then(Boolean)
.catch(() => false)
appExistence.set(app, request)
return request
}
+5 -35
View File
@@ -7,8 +7,7 @@ import { useServerSDK } from "@/runtime/server/client"
import { useLanguage } from "@/runtime/i18n/language"
import { useSettings } from "@/settings/model"
import { useWorkspaceLocation } from "@/workspaces/location"
import { sessionPermissionRequest, sessionFormRequest, sessionTreeIDs } from "@/session/requests/session-request-tree"
import { createWebSearchRequest } from "./websearch"
import { sessionPermissionRequest, sessionQuestionForm } from "@/session/requests/session-request-tree"
import { createSessionBackground } from "@/session/requests/background"
import { useData } from "@/runtime/server/current"
@@ -25,40 +24,12 @@ export function createSessionRequestModel() {
void Promise.all([
data.shell.sync({ directory: sdk().directory }),
data.session.permission.sync(id),
data.session.form.sync(id),
]).catch(() => undefined)
})
createEffect(() => {
const id = params.id
if (!id || serverSDK.connection.status() !== "connected") return
void Promise.all(
sessionTreeIDs(data.session.list(), id).map((sessionID) => data.session.form.sync(sessionID)),
).catch(() => undefined)
})
const formRequest = createMemo((): FormInfo | undefined => {
return sessionFormRequest(data.session.list(), data.session.form.list, params.id)
})
const websearch = createWebSearchRequest({
owner: () => params.id,
connected: () => serverSDK.connection.status() === "connected",
request: () => {
const form = formRequest()
return form?.metadata?.kind === "websearch.provider" ? form : undefined
},
providers: async (sessionID) => {
const session = data.session.get(sessionID) ?? (await serverSDK.api.session.get({ sessionID }))
const result = await serverSDK.api.websearch.providers({
location: { directory: session.location.directory, workspace: session.location.workspaceID },
})
return result.data.map((provider) => ({ value: provider.id, label: provider.name }))
},
reply: (input) => data.session.form.reply(input),
events: serverSDK.event,
})
const questionRequest = createMemo(() => {
if (websearch.request()) return
const form = formRequest()
return form?.metadata?.kind === "question" ? form : undefined
const questionRequest = createMemo((): FormInfo | undefined => {
return sessionQuestionForm(data.session.list(), data.session.form.list, params.id)
})
const permissionRequest = createMemo((): PermissionRequest | undefined => {
@@ -69,7 +40,7 @@ export function createSessionRequestModel() {
const blocked = createMemo(() => {
const id = params.id
if (!id) return false
return !!permissionRequest() || !!questionRequest() || !!websearch.request()
return !!permissionRequest() || !!questionRequest()
})
const primary = () => {
@@ -125,7 +96,6 @@ export function createSessionRequestModel() {
return {
blocked,
questionRequest,
websearch,
permissionRequest,
permissionResponding,
background: {
@@ -1,6 +1,6 @@
import { describe, expect, test } from "bun:test"
import type { FormInfo, PermissionRequest, SessionInfo } from "@opencode-ai/client/promise"
import { sessionPermissionRequest, sessionFormRequest, sessionTreeIDs } from "@/session/requests/session-request-tree"
import { sessionPermissionRequest, sessionQuestionForm } from "@/session/requests/session-request-tree"
const session = (input: { id: string; parentID?: string }) =>
({
@@ -23,22 +23,6 @@ const question = (id: string, sessionID: string) =>
fields: [{ key: "q0", type: "string" }],
}) as FormInfo
describe("sessionTreeIDs", () => {
test("returns only the current session and its descendants", () => {
const sessions = [
session({ id: "root" }),
session({ id: "child", parentID: "root" }),
session({ id: "grand", parentID: "child" }),
session({ id: "sibling", parentID: "root" }),
session({ id: "other" }),
]
expect(sessionTreeIDs(sessions, "child")).toEqual(["child", "grand"])
expect(sessionTreeIDs(sessions, "root")).toEqual(["root", "child", "sibling", "grand"])
expect(sessionTreeIDs(sessions)).toEqual([])
})
})
describe("sessionPermissionRequest", () => {
test("prefers the current session permission", () => {
const sessions = [session({ id: "root" }), session({ id: "child", parentID: "root" })]
@@ -97,7 +81,7 @@ describe("sessionPermissionRequest", () => {
})
})
describe("sessionFormRequest", () => {
describe("sessionQuestionForm", () => {
test("prefers the current session question", () => {
const sessions = [session({ id: "root" }), session({ id: "child", parentID: "root" })]
const questions = {
@@ -105,7 +89,7 @@ describe("sessionFormRequest", () => {
child: [question("q-child", "child")],
}
expect(sessionFormRequest(sessions, questions, "root")?.id).toBe("q-root")
expect(sessionQuestionForm(sessions, questions, "root")?.id).toBe("q-root")
})
test("returns a nested child question", () => {
@@ -118,29 +102,15 @@ describe("sessionFormRequest", () => {
grand: [question("q-grand", "grand")],
}
expect(sessionFormRequest(sessions, questions, "root")?.id).toBe("q-grand")
expect(sessionQuestionForm(sessions, questions, "root")?.id).toBe("q-grand")
})
test("skips unsupported forms", () => {
test("skips forms that are not questions", () => {
const sessions = [session({ id: "root" })]
const forms = {
root: [{ ...question("form", "root"), metadata: { kind: "integration" } }],
}
expect(sessionFormRequest(sessions, forms, "root")).toBeUndefined()
})
test("finds web search consent in a nested child session", () => {
const sessions = [session({ id: "root" }), session({ id: "child", parentID: "root" })]
const form = { ...question("search", "child"), metadata: { kind: "websearch.provider" } }
expect(sessionFormRequest(sessions, { child: [form] }, "root")).toBe(form)
})
test("preserves request order across questions and web search", () => {
const sessions = [session({ id: "root" }), session({ id: "child", parentID: "root" })]
const form = { ...question("search", "root"), metadata: { kind: "websearch.provider" } }
expect(sessionFormRequest(sessions, { root: [form, question("q", "root")] }, "root")).toBe(form)
expect(sessionFormRequest(sessions, { root: [question("q", "root"), form] }, "root")?.id).toBe("q")
expect(sessionFormRequest(sessions, { root: [form], child: [question("q", "child")] }, "root")).toBe(form)
expect(sessionQuestionForm(sessions, forms, "root")).toBeUndefined()
})
})
@@ -6,16 +6,8 @@ function sessionTreeRequest<T>(
sessionID?: string,
include: (item: T) => boolean = () => true,
) {
const ids = sessionTreeIDs(session, sessionID)
if (!ids.length) return
const list = (id: string) => (typeof request === "function" ? request(id) : request[id])
const id = ids.find((id) => list(id)?.some(include))
if (!id) return
return list(id)?.find(include)
}
if (!sessionID) return
export function sessionTreeIDs(session: SessionInfo[], sessionID?: string) {
if (!sessionID) return []
const map = session.reduce((acc, item) => {
if (!item.parentID) return acc
const list = acc.get(item.parentID)
@@ -35,7 +27,11 @@ export function sessionTreeIDs(session: SessionInfo[], sessionID?: string) {
ids.push(child)
}
}
return ids
const list = (id: string) => (typeof request === "function" ? request(id) : request[id])
const id = ids.find((id) => list(id)?.some(include))
if (!id) return
return list(id)?.find(include)
}
export function sessionPermissionRequest(
@@ -47,15 +43,10 @@ export function sessionPermissionRequest(
return sessionTreeRequest(session, request, sessionID, include)
}
export function sessionFormRequest(
export function sessionQuestionForm(
session: SessionInfo[],
request: Record<string, FormInfo[] | undefined> | ((sessionID: string) => FormInfo[] | undefined),
sessionID?: string,
) {
return sessionTreeRequest(
session,
request,
sessionID,
(item) => item.metadata?.kind === "question" || item.metadata?.kind === "websearch.provider",
)
return sessionTreeRequest(session, request, sessionID, (item) => item.metadata?.kind === "question")
}
@@ -1,58 +0,0 @@
[data-component="session-websearch-dock"] {
width: 100%;
border: 0.5px solid var(--v2-border-border-base);
border-radius: 12px;
.websearch-body {
box-shadow: var(--v2-elevation-raised);
}
.websearch-setting {
padding: 16px;
}
.websearch-setting [data-component="settings-row"] {
column-gap: 24px;
padding-block: 0;
border: 0;
}
.websearch-footer {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 16px;
padding: 24px 16px 12px;
border: 0;
}
.websearch-status {
display: flex;
align-items: center;
gap: 8px;
margin-inline-end: auto;
color: var(--v2-text-text-base);
font-size: 13px;
line-height: var(--line-height-compact);
}
.websearch-status:empty {
display: none;
}
.websearch-actions {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 16px;
}
}
[data-component="menu-v2-content"][data-slot="select-v2-content"].websearch-provider-menu {
width: max-content;
min-width: 0;
[data-component="menu-v2-item"] {
gap: 24px;
}
}
@@ -1,86 +0,0 @@
import { createMemo, Show } from "solid-js"
import { Button } from "@opencode-ai/ui/button"
import { DockShell, DockTray } from "@opencode-ai/ui/dock-surface"
import { Select } from "@opencode-ai/ui/select"
import { useLanguage } from "@/runtime/i18n/language"
import { SettingsRow } from "@/settings/row"
import type { WebSearchRequestModel } from "./websearch"
import "./session-websearch-dock.css"
export function SessionWebSearchDock(props: { model: WebSearchRequestModel; onSubmit: () => void }) {
const language = useLanguage()
const options = createMemo(() => [
...(props.model.specific() ? [] : [{ value: "random", label: language.t("session.websearch.any") }]),
...props.model.options(),
])
const current = createMemo(() => options().find((option) => option.value === props.model.selected()))
const busy = () => props.model.sending() || !props.model.connected()
const status = () => {
if (props.model.loading()) return language.t("common.loading")
if (props.model.failed()) return language.t("session.websearch.failed")
if (!props.model.options().length) return language.t("session.websearch.empty")
}
const unavailable = () => props.model.loading() || props.model.loadFailed() || !props.model.options().length
const submit = (selection: string | false) => {
if (busy()) return
props.onSubmit()
void props.model.submit(selection)
}
return (
<section
data-component="session-websearch-dock"
aria-label={language.t("session.websearch.title")}
aria-busy={props.model.sending()}
>
<DockShell class="websearch-body">
<div class="websearch-setting">
<SettingsRow
title={language.t("session.websearch.title")}
description={language.t("session.websearch.description")}
>
<Select
aria-label={language.t("session.websearch.provider")}
options={options()}
current={current()}
value={(option) => option.value}
label={(option) => option.label}
onSelect={(option) => option && props.model.select(option.value)}
disabled={busy() || unavailable()}
placeholder={language.t("session.websearch.provider")}
contentClass="websearch-provider-menu"
/>
</SettingsRow>
</div>
</DockShell>
<DockTray attach="top" class="websearch-footer">
<div class="websearch-status" aria-live="polite">
<Show when={props.model.loadFailed()} fallback={status()}>
<span>{language.t("session.websearch.loadFailed")}</span>
<Button variant="ghost" size="small" onClick={props.model.retry} disabled={busy()}>
{language.t("session.websearch.retry")}
</Button>
</Show>
</div>
<div class="websearch-actions">
<Show when={!props.model.specific()}>
<Button variant="ghost" size="small" onClick={() => submit(false)} disabled={busy()}>
{language.t("session.websearch.disable")}
</Button>
</Show>
<Button
variant="neutral"
size="small"
onClick={() => {
const selected = props.model.selected()
if (selected) submit(selected)
}}
disabled={busy() || unavailable() || !current()}
>
{language.t("session.websearch.enable")}
</Button>
</div>
</DockTray>
</section>
)
}
@@ -1,171 +0,0 @@
import { describe, expect, test } from "bun:test"
import type { FormAnswer, FormCreated, FormReplyInput, OpenCodeEvent } from "@opencode-ai/client/promise"
import { replyWebSearch } from "./websearch"
const consent: FormCreated["data"]["form"] = {
id: "frm_consent",
sessionID: "ses_child",
title: "Web Search",
metadata: { kind: "websearch.provider" },
fields: [{ key: "choice", type: "string", required: true, custom: false }],
}
const provider: FormCreated["data"]["form"] = {
...consent,
id: "frm_provider",
fields: [
{
key: "provider",
type: "string",
required: true,
custom: false,
options: [
{ value: "exa", label: "Exa" },
{ value: "parallel", label: "Parallel" },
],
},
],
}
function fixture() {
const listeners = new Set<(event: OpenCodeEvent) => void>()
const replies: FormReplyInput[] = []
const abort = new AbortController()
const emit = (event: OpenCodeEvent) => listeners.forEach((listener) => listener(event))
return {
form: consent,
signal: abort.signal,
abort,
listeners,
replies,
events: {
listen(listener: (event: OpenCodeEvent) => void) {
listeners.add(listener)
return () => {
listeners.delete(listener)
}
},
},
reply: async (input: FormReplyInput) => {
replies.push(input)
},
create: (form = provider) => emit({ id: "evt_create", created: 0, type: "form.created", data: { form } }),
cancel: (id: string) =>
emit({
id: "evt_cancel",
created: 0,
type: "form.cancelled",
data: { id, sessionID: consent.sessionID },
}),
answer: (id: string, answer: FormAnswer) =>
emit({
id: "evt_reply",
created: 0,
type: "form.replied",
data: { id, sessionID: consent.sessionID, answer },
}),
}
}
describe("web search desktop consent", () => {
test.each([
["random", "allow"],
[false, "disable"],
] as const)("submits %s without a second form", async (selection, choice) => {
const input = fixture()
await replyWebSearch({ ...input, selection })
expect(input.replies).toEqual([{ sessionID: consent.sessionID, formID: consent.id, answer: { choice } }])
expect(input.listeners.size).toBe(0)
})
test("subscribes before the first reply and answers the owning session's provider form", async () => {
const input = fixture()
await replyWebSearch({
...input,
selection: "parallel",
reply: async (answer) => {
input.replies.push(answer)
if (answer.answer.choice === "choose") input.create()
},
})
expect(input.replies).toEqual([
{ sessionID: consent.sessionID, formID: consent.id, answer: { choice: "choose" } },
{ sessionID: consent.sessionID, formID: provider.id, answer: { provider: "parallel" } },
])
expect(input.listeners.size).toBe(0)
})
test("ignores questions, other sessions, and repeated consent forms during handoff", async () => {
const input = fixture()
const pending = replyWebSearch({ ...input, selection: "exa" })
input.create({ ...provider, sessionID: "ses_other" })
input.create({ ...provider, metadata: { kind: "question" } })
input.create(consent)
input.create()
await pending
expect(input.replies).toHaveLength(2)
expect(input.replies[1]?.formID).toBe(provider.id)
})
test("leaves a changed provider list for explicit confirmation", async () => {
const input = fixture()
const pending = replyWebSearch({ ...input, selection: "removed" })
input.create()
await pending
expect(input.replies).toHaveLength(1)
expect(input.listeners.size).toBe(0)
})
test("supports direct entry into the provider form", async () => {
const input = fixture()
await replyWebSearch({ ...input, form: provider, selection: "exa" })
expect(input.replies).toEqual([{ sessionID: consent.sessionID, formID: provider.id, answer: { provider: "exa" } }])
expect(input.listeners.size).toBe(0)
})
test("does not misrepresent cancelling the provider form as disabling search", async () => {
const input = fixture()
await replyWebSearch({ ...input, form: provider, selection: false })
expect(input.replies).toEqual([])
})
test.each(["cancel", "other-client", "abort"])("ends a pending handoff on %s", async (action) => {
const input = fixture()
const pending = replyWebSearch({ ...input, selection: "exa" })
if (action === "cancel") input.cancel(consent.id)
if (action === "other-client") input.answer(consent.id, { choice: "disable" })
if (action === "abort") input.abort.abort()
await pending
input.create()
expect(input.replies).toHaveLength(1)
expect(input.listeners.size).toBe(0)
})
test("cleans up after a failed consent submission", async () => {
const input = fixture()
await expect(
replyWebSearch({
...input,
selection: "exa",
reply: async () => {
throw new Error("offline")
},
}),
).rejects.toThrow("offline")
expect(input.listeners.size).toBe(0)
})
test("propagates provider submission failures for retry", async () => {
const input = fixture()
await expect(
replyWebSearch({
...input,
selection: "exa",
reply: async (answer) => {
if (answer.formID === provider.id) throw new Error("offline")
input.create()
},
}),
).rejects.toThrow("offline")
expect(input.listeners.size).toBe(0)
})
})
@@ -1,154 +0,0 @@
import type { FormInfo, FormOption, FormReplyInput, FormStringField } from "@opencode-ai/client/promise"
import { createEffect, createMemo, createResource, on, onCleanup } from "solid-js"
import { createStore } from "solid-js/store"
import type { OpenCodeEventStream } from "@/runtime/server/client"
export function webSearchProviderField(form: FormInfo) {
return form.fields.find(
(field): field is FormStringField => field.type === "string" && field.key === "provider" && !!field.options,
)
}
export function createWebSearchRequest(input: {
owner: () => string | undefined
connected: () => boolean
request: () => FormInfo | undefined
providers: (sessionID: string) => Promise<FormOption[]>
reply: (input: FormReplyInput) => Promise<unknown>
events: Pick<OpenCodeEventStream, "listen">
}) {
const [store, setStore] = createStore({
selected: "random",
sending: undefined as { form: FormInfo; abort: AbortController } | undefined,
error: false,
})
const [providers, resource] = createResource(input.request, async (form) => {
const field = webSearchProviderField(form)
if (field) return field.options ?? []
return input.providers(form.sessionID)
})
const request = createMemo(() => store.sending?.form ?? input.request())
const specific = createMemo(() => {
const form = request()
return !!form && !!webSearchProviderField(form)
})
const options = createMemo(() => (providers.error ? [] : (providers() ?? [])))
const selected = createMemo(() => {
if (!specific()) return store.selected
return options().some((option) => option.value === store.selected) ? store.selected : options()[0]?.value
})
createEffect(
on([input.owner, input.connected], () => {
store.sending?.abort.abort()
setStore({ sending: undefined, selected: "random", error: false })
}),
)
createEffect(
on(
() => input.request()?.id,
() => {
const form = input.request()
if (!form || store.sending || webSearchProviderField(form)) return
setStore({ selected: "random", error: false })
},
),
)
onCleanup(() => store.sending?.abort.abort())
const submit = async (selection: string | false) => {
const form = input.request()
if (!form || store.sending || !input.connected()) return
if (selection === false && webSearchProviderField(form)) return
const sending = { form, abort: new AbortController() }
setStore({ sending, error: false })
await replyWebSearch({ ...input, form, selection, signal: sending.abort.signal })
.catch(() => {
if (!sending.abort.signal.aborted) setStore("error", true)
})
.finally(() => {
if (store.sending?.abort === sending.abort) setStore("sending", undefined)
})
}
return {
request,
options,
selected,
specific,
loading: () => providers.loading,
loadFailed: () => !!providers.error,
failed: () => store.error,
sending: () => !!store.sending,
connected: input.connected,
select: (value: string) => setStore({ selected: value, error: false }),
retry: () => void resource.refetch(),
submit,
}
}
export type WebSearchRequestModel = ReturnType<typeof createWebSearchRequest>
export async function replyWebSearch(input: {
form: FormInfo
selection: string | false
signal: AbortSignal
reply: (input: FormReplyInput) => Promise<unknown>
events: Pick<OpenCodeEventStream, "listen">
}) {
if (input.signal.aborted) return
if (webSearchProviderField(input.form)) {
if (input.selection === false) return
return input.reply({
sessionID: input.form.sessionID,
formID: input.form.id,
answer: { provider: input.selection },
})
}
if (input.selection === false || input.selection === "random") {
return input.reply({
sessionID: input.form.sessionID,
formID: input.form.id,
answer: { choice: input.selection === false ? "disable" : "allow" },
})
}
const next = Promise.withResolvers<FormInfo | undefined>()
const stop = input.events.listen((event) => {
if (event.type === "form.created") {
const form = event.data.form
if (
form.sessionID !== input.form.sessionID ||
form.id === input.form.id ||
form.metadata?.kind !== "websearch.provider" ||
!webSearchProviderField(form)
)
return
next.resolve(form)
}
if (event.type === "form.cancelled" && event.data.id === input.form.id) next.resolve(undefined)
if (event.type === "form.replied" && event.data.id === input.form.id && event.data.answer.choice !== "choose")
next.resolve(undefined)
})
const cancel = () => next.resolve(undefined)
input.signal.addEventListener("abort", cancel, { once: true })
return Promise.all([
input.reply({ sessionID: input.form.sessionID, formID: input.form.id, answer: { choice: "choose" } }),
next.promise,
])
.then(([, form]) => {
if (!form || input.signal.aborted) return
const field = webSearchProviderField(form)
if (!field?.options?.some((option) => option.value === input.selection)) return
return input.reply({
sessionID: form.sessionID,
formID: form.id,
answer: { provider: input.selection },
})
})
.finally(() => {
stop()
input.signal.removeEventListener("abort", cancel)
})
}
-9
View File
@@ -27,8 +27,6 @@ import { createSessionReview } from "./review/model"
import { SessionDesktopReview, SessionMobileReview, SessionMobileViewTabs } from "./review/view"
import { SessionContextTab } from "./files/session-context-tab"
import { createSessionTimelineInteraction } from "./timeline/interaction"
import { createTimelineSearchController } from "./timeline/search-controller"
import { TimelineSearchBar } from "./timeline/search-bar"
import { ActiveSessionComposerRegion, createActiveSessionRegion } from "./composer/region"
import { SessionIdentityHeader } from "./session-identity-header"
import { SessionReviewToggle } from "./header/session-header-actions"
@@ -49,12 +47,6 @@ export function SessionScreen(props: { session: SessionModel }) {
const isDesktop = session.isDesktop
const screen = createSessionScreenLayout(session)
const timeline = createSessionTimelineInteraction(session)
const timelineSearch = createTimelineSearchController({
sessionID: session.identity.sessionID,
scrollRef: timeline.scroller,
revealMessage: timeline.actions.revealMessage,
pauseAutoScroll: timeline.view.unpin,
})
const messagesReady = timeline.ready
const [store, setStore] = createStore({
deferRender: false,
@@ -270,7 +262,6 @@ export function SessionScreen(props: { session: SessionModel }) {
anchor={timeline.view.anchor}
setRevealMessage={timeline.view.setRevealMessage}
setScrollToEnd={timeline.view.setScrollToEnd}
search={<TimelineSearchBar controller={timelineSearch} />}
/>
)}
</Show>
@@ -2,54 +2,30 @@ import { describe, expect, test } from "bun:test"
import { createRoot } from "solid-js"
import { createSessionResolution } from "./session-resolution"
function store() {
const syncs = { session: 0, message: 0, pending: 0 }
const sessions = {
get: () => undefined,
sync: () => {
syncs.session++
return Promise.resolve()
},
message: {
sync: () => {
syncs.message++
return Promise.resolve()
},
},
pending: {
sync: () => {
syncs.pending++
return Promise.resolve()
},
},
}
return { syncs, sessions }
}
describe("session resolution", () => {
test("waits for a route session ID", () => {
createRoot((dispose) => {
const input = store()
const syncs = { session: 0, message: 0 }
const sessions = {
get: () => undefined,
sync: () => {
syncs.session++
return Promise.resolve()
},
message: {
sync: () => {
syncs.message++
return Promise.resolve()
},
},
}
const session = createSessionResolution(
() => undefined,
() => input.sessions,
() => sessions,
)
expect(session()).toBeUndefined()
expect(input.syncs).toEqual({ session: 0, message: 0, pending: 0 })
dispose()
})
})
test("starts the transcript and queued input reads with metadata", () => {
createRoot((dispose) => {
const input = store()
createSessionResolution(
() => "ses_open",
() => input.sessions,
{ children: true },
)
expect(input.syncs).toEqual({ session: 1, message: 1, pending: 1 })
expect(syncs).toEqual({ session: 0, message: 0 })
dispose()
})
})
@@ -7,9 +7,6 @@ type SessionStore<T> = {
message: {
sync: (id: string) => Promise<unknown>
}
pending: {
sync: (id: string) => Promise<unknown>
}
}
type Resolution<T> = { id: string; store: SessionStore<T> } & (
@@ -55,11 +52,8 @@ export function createSessionResolution<T>(
onCleanup(() => {
stale = true
})
// The timeline owns message errors; metadata resolution stays independent. Queued inputs
// ride along so a reconnect refreshes them with the transcript instead of leaving the
// pre-disconnect queue on screen.
// The timeline owns message errors; metadata resolution stays independent.
void store.message.sync(id).catch(() => undefined)
void store.pending.sync(id).catch(() => undefined)
if (cached() && !options?.children && !options?.connected) {
setStatus({ id, store, state: "settled" })
return
@@ -138,26 +138,6 @@ export const QuestionRequest = {
),
}
export const WebSearchRequest = {
render: () => (
<SessionPreview
title="Search for current documentation"
description={description}
document={questionPendingDocument}
request={{
type: "websearch",
value: {
id: "frm_websearch_preview",
sessionID: "ses_websearch_preview",
title: "Web Search",
metadata: { kind: "websearch.provider" },
fields: [{ key: "choice", type: "string", required: true, custom: false }],
},
}}
/>
),
}
export const RetryAndInterruption = {
render: () => (
<SessionPreview title="Recover the interrupted run" description={description} document={retryAfterInterruption} />
+1 -25
View File
@@ -23,7 +23,6 @@ import { useLanguage } from "@/runtime/i18n/language"
import { ReviewPanelView } from "@/session/review/panel"
import { createReviewPanelState } from "@/session/review/panel-state"
import { TerminalSurface } from "@/session/terminal/surface"
import type { WebSearchRequestModel } from "./requests/websearch"
const modelReady = Object.assign(() => true, { promise: undefined }) satisfies ModelSelection["ready"]
const storyComposerModel = {
@@ -83,7 +82,7 @@ export type SessionPreviewProps = {
description: string
document: SessionDocument
draft?: string
request?: { type: "permission"; value: PermissionRequest } | { type: "question" | "websearch"; value: FormInfo }
request?: { type: "permission"; value: PermissionRequest } | { type: "question"; value: FormInfo }
reviewOpened?: boolean
child?: { parentID: string }
terminal?: { title: string; lines: string[] }
@@ -174,12 +173,10 @@ function SessionSurfaceState(props: SessionPreviewProps & { onReset: () => void
activity: string
reviewOpened: boolean
request: SessionPreviewProps["request"]
searchProvider: string
}>({
activity: "Ready",
reviewOpened: props.reviewOpened ?? false,
request: props.request,
searchProvider: "random",
})
const prompt = createPromptController({
initial: props.draft ?? "",
@@ -192,27 +189,6 @@ function SessionSurfaceState(props: SessionPreviewProps & { onReset: () => void
const region = {
state: {
questionRequest: () => (state.request?.type === "question" ? state.request.value : undefined),
websearch: {
request: () => (state.request?.type === "websearch" ? state.request.value : undefined),
options: () => [
{ value: "exa", label: "Exa" },
{ value: "parallel", label: "Parallel" },
{ value: "tavily", label: "Tavily" },
],
selected: () => state.searchProvider,
specific: () => false,
loading: () => false,
loadFailed: () => false,
failed: () => false,
sending: () => false,
connected: () => true,
select: (value) => setState("searchProvider", value),
retry() {},
submit: async (value) => {
setState("request", undefined)
setState("activity", `Web search selection (local only): ${value}`)
},
} satisfies WebSearchRequestModel,
permissionRequest: () => (state.request?.type === "permission" ? state.request.value : undefined),
permissionResponding: () => false,
decide: (response) => {
@@ -24,7 +24,6 @@ export function createSessionTimelineInteraction(session: SessionModel) {
pinned: true,
},
refs: {
scroller: undefined as HTMLDivElement | undefined,
content: undefined as HTMLDivElement | undefined,
dock: undefined as HTMLDivElement | undefined,
},
@@ -39,7 +38,7 @@ export function createSessionTimelineInteraction(session: SessionModel) {
}
let scroller: HTMLDivElement | undefined
let dockHeight = 0
let revealMessage = (_id: string, _partID?: string) => {}
let revealMessage = (_id: string) => {}
let scrollToEnd = () => {}
let scrollMark = 0
let messageMark = 0
@@ -158,7 +157,6 @@ export function createSessionTimelineInteraction(session: SessionModel) {
}
const setScrollRef = (element: HTMLDivElement | undefined) => {
scroller = element
setState("refs", "scroller", element)
if (!element) return
scheduleScrollState(element)
fill()
@@ -292,7 +290,6 @@ export function createSessionTimelineInteraction(session: SessionModel) {
return {
actions: {
navigateMessage,
revealMessage: (id: string, partID?: string) => revealMessage(id, partID),
resume,
setActiveMessage,
},
@@ -300,7 +297,7 @@ export function createSessionTimelineInteraction(session: SessionModel) {
resource: timeline.resource,
ready: timeline.ready,
scroll: state.scroll,
scroller: () => state.refs.scroller,
scroller: () => scroller,
view: {
anchor,
markUserScroll,
@@ -316,7 +313,7 @@ export function createSessionTimelineInteraction(session: SessionModel) {
setDockRef: (element: HTMLDivElement | undefined) => {
setState("refs", "dock", element)
},
setRevealMessage: (reveal: (id: string, partID?: string) => void) => {
setRevealMessage: (reveal: (id: string) => void) => {
revealMessage = reveal
},
setScrollRef,
@@ -58,6 +58,7 @@ export function BackgroundMoveHint(props: { keybind?: string[]; onMove?: () => v
type="button"
variant="ghost-faint"
size="small"
icon="outline-arrow-to-corner-top-right"
class="max-w-full"
aria-label={language.t("session.background.moveInline", { keybind: keybind() })}
onClick={() => props.onMove?.()}
@@ -353,9 +354,8 @@ type MessageTimelineProps = {
workspaceMoveEligible: boolean
onSummaryOpenChange: (open: boolean) => void
anchor: (id: string) => string
setRevealMessage?: (fn: (id: string, partID?: string) => void) => void
setRevealMessage?: (fn: (id: string) => void) => void
setScrollToEnd?: (fn: () => void) => void
search?: JSX.Element
}
export function MessageTimeline(props: MessageTimelineProps) {
@@ -790,7 +790,6 @@ function MessageTimelineView(
<Show when={sessionID()} keyed>
{(id) => (
<div class="shrink-0 flex items-center gap-2">
{props.search}
<SessionContextUsage placement="bottom" />
<Show when={!parentID() && project()}>
{(project) => (
@@ -1,14 +0,0 @@
[data-component="timeline-search-bar"] [data-component="text-input-v2"] {
background: var(--v2-background-bg-base);
box-shadow: inset 0 0 0 1px var(--v2-border-border-base);
outline: none;
}
[data-component="timeline-search-bar"] [data-component="text-input-v2"]:hover {
background: var(--v2-background-bg-base);
}
[data-component="timeline-search-bar"] [data-component="text-input-v2"]:focus-within {
box-shadow: inset 0 0 0 1px var(--v2-border-border-focus);
outline: none;
}
@@ -1,72 +0,0 @@
import { Icon } from "@opencode-ai/ui/icon"
import "@opencode-ai/ui/text-input.css"
import { Show } from "solid-js"
import type { TimelineSearchController } from "./search-controller"
import "./search-bar.css"
export function TimelineSearchBar(props: { controller: TimelineSearchController }) {
const c = props.controller
return (
<Show when={c.visible()}>
<div data-component="timeline-search-bar" class="h-7 w-[200px] max-w-[50vw] shrink-0">
<div data-component="text-input-v2" data-appearance="base" data-leading-icon class="!h-7 !w-full max-w-full">
<div data-slot="text-input-v2-value">
<span data-slot="text-input-v2-leading-icon">
<Icon name="magnifying-glass" size="small" />
</span>
<input
ref={c.element.setInput}
data-slot="text-input-v2-input"
type="search"
value={c.query.value()}
placeholder={c.query.placeholder()}
aria-label={c.query.placeholder()}
onInput={(event) => c.query.setValue(event.currentTarget.value)}
onKeyDown={(event) => {
if (event.key === "Escape") {
event.preventDefault()
c.query.close()
return
}
if (event.altKey || event.metaKey || event.ctrlKey) return
if (event.key === "Enter" && !event.isComposing) {
event.preventDefault()
c.result.move(event.shiftKey ? -1 : 1)
return
}
if (event.key === "ArrowDown" && !event.isComposing) {
event.preventDefault()
c.result.move(1)
return
}
if (event.key === "ArrowUp" && !event.isComposing) {
event.preventDefault()
c.result.move(-1)
return
}
}}
/>
</div>
<Show when={c.query.value()}>
<span
data-slot="timeline-search-count"
class="shrink-0 self-center text-[11px] text-v2-text-text-muted [font-weight:440] tabular-nums"
>
{c.result.count() > 0 ? c.result.activeIndex() + 1 : 0}/{c.result.count()}
</span>
</Show>
<button
type="button"
class="-me-1 flex size-5 shrink-0 self-center items-center justify-center rounded-[2px] border-0 bg-transparent p-0 text-v2-icon-icon-muted outline outline-1 outline-transparent hover:bg-v2-overlay-simple-overlay-hover active:bg-v2-overlay-simple-overlay-pressed focus-visible:outline-v2-border-border-focus"
aria-label={c.query.placeholder()}
onMouseDown={(event) => event.preventDefault()}
onClick={() => c.query.close()}
>
<Icon name="xmark-small" />
</button>
</div>
</div>
</Show>
)
}
@@ -1,275 +0,0 @@
import { useCommand } from "@/shell/commands/command"
import { useLanguage } from "@/runtime/i18n/language"
import { useData } from "@/runtime/server/current"
import { Timeline } from "@opencode-ai/session-ui/timeline/projection"
import { createEffect, createMemo, createSignal, on, onCleanup } from "solid-js"
import { createStore } from "solid-js/store"
export type TimelineSearchMatch = {
messageID: string
role: "user" | "assistant"
revealID: string
partID: string
occurrence: number
text: string
}
const HIGHLIGHT_HIT = "timeline-search-hit"
const HIGHLIGHT_ACTIVE = "timeline-search-hit-active"
const TEXT_SELECTORS = '[data-slot="text-part-body"], [data-slot="user-message-text"]'
function supportsHighlights() {
return typeof CSS !== "undefined" && typeof CSS.highlights === "object" && CSS.highlights !== null
}
function clearHighlights() {
if (!supportsHighlights()) return
CSS.highlights.delete(HIGHLIGHT_HIT)
CSS.highlights.delete(HIGHLIGHT_ACTIVE)
}
function collectRanges(
root: HTMLElement,
query: string,
activePartID: string | undefined,
activeOccurrence: number | undefined,
) {
const hits: Range[] = []
const active: Range[] = []
const lower = query.toLowerCase()
const bodies = root.querySelectorAll<HTMLElement>(TEXT_SELECTORS)
for (const body of bodies) {
const part = body.closest("[data-timeline-part-id]")
const partID = part?.getAttribute("data-timeline-part-id")
const isActivePart = activePartID !== undefined && partID === activePartID
let occurrenceInPart = 0
const walker = document.createTreeWalker(body, NodeFilter.SHOW_TEXT)
let node = walker.nextNode() as Text | null
while (node) {
const value = node.nodeValue ?? ""
const lowerValue = value.toLowerCase()
let from = 0
let at = lowerValue.indexOf(lower, from)
while (at !== -1) {
const range = document.createRange()
range.setStart(node, at)
range.setEnd(node, at + query.length)
if (isActivePart && activeOccurrence === occurrenceInPart) active.push(range)
else hits.push(range)
occurrenceInPart += 1
from = at + query.length
at = lowerValue.indexOf(lower, from)
}
node = walker.nextNode() as Text | null
}
}
return { hits, active }
}
function applyHighlights(
root: HTMLElement,
query: string,
activePartID: string | undefined,
activeOccurrence: number | undefined,
) {
if (!supportsHighlights()) return
const { hits, active } = collectRanges(root, query, activePartID, activeOccurrence)
CSS.highlights.set(HIGHLIGHT_HIT, new Highlight(...hits))
CSS.highlights.set(HIGHLIGHT_ACTIVE, new Highlight(...active))
}
export function createTimelineSearchController(input: {
sessionID: () => string | undefined
scrollRef: () => HTMLDivElement | undefined
revealMessage: (id: string, partID?: string) => void
pauseAutoScroll: () => void
}) {
const command = useCommand()
const language = useLanguage()
const data = useData()
const [state, setState] = createStore({ value: "", active: 0, visible: false })
const [focusTick, setFocusTick] = createSignal(0)
let inputEl: HTMLInputElement | undefined
const query = createMemo(() => state.value.trim().toLowerCase())
const matches = createMemo<TimelineSearchMatch[]>(() => {
const value = query()
if (!value) return []
const sessionID = input.sessionID()
if (!sessionID) return []
const messages = data.session.message.list(sessionID)
const result: TimelineSearchMatch[] = []
let revealID = ""
for (const message of messages) {
if (message.type === "user" || message.type === "shell") revealID = message.id
if (message.type !== "user" && message.type !== "assistant") continue
const visibleParts =
message.type === "user"
? [{ id: `${message.id}:text:0`, content: { type: "text" as const, text: message.text } }]
: Timeline.contentEntries(message)
for (const textPart of visibleParts) {
if (textPart.content.type !== "text") continue
const text = textPart.content.text
if (!text) continue
const lower = text.toLowerCase()
let from = 0
let occurrence = 0
let at = lower.indexOf(value, from)
while (at !== -1) {
result.push({
messageID: message.id,
role: message.type,
revealID,
partID: textPart.id,
occurrence,
text,
})
occurrence += 1
from = at + value.length
at = lower.indexOf(value, from)
}
}
}
return result
})
const activeIndex = createMemo(() => {
const list = matches()
if (list.length === 0) return 0
if (state.active >= list.length) return 0
if (state.active < 0) return 0
return state.active
})
const activePartID = createMemo(() => matches()[activeIndex()]?.partID)
const activeOccurrence = createMemo(() => matches()[activeIndex()]?.occurrence)
createEffect(() => {
const root = input.scrollRef()
const q = query()
if (!root || !state.visible || !q) {
clearHighlights()
return
}
applyHighlights(root, q, activePartID(), activeOccurrence())
let frame: number | undefined
const scheduleApply = () => {
if (frame !== undefined) return
frame = requestAnimationFrame(() => {
frame = undefined
if (!state.visible) return
applyHighlights(root, query(), activePartID(), activeOccurrence())
})
}
const observer = new MutationObserver(scheduleApply)
observer.observe(root, { childList: true, subtree: true, characterData: true })
onCleanup(() => {
observer.disconnect()
if (frame !== undefined) cancelAnimationFrame(frame)
clearHighlights()
})
})
createEffect(
on(focusTick, () => {
if (!state.visible) return
requestAnimationFrame(() => {
inputEl?.focus()
inputEl?.select()
})
}),
)
command.register("session.search", () => [
{
id: "session.search",
title: language.t("session.search.placeholder"),
keybind: "mod+f",
hidden: true,
onSelect: () => open(),
},
])
const onOpenRequest = () => open()
document.addEventListener("opencode:timeline-search-open", onOpenRequest)
onCleanup(() => document.removeEventListener("opencode:timeline-search-open", onOpenRequest))
function open() {
setState("visible", true)
setFocusTick((t) => t + 1)
}
function close() {
setState({ value: "", active: 0, visible: false })
inputEl?.blur()
}
function setValue(value: string) {
setState("value", value)
const list = matches()
const match = list[0]
if (!value.trim() || !match) {
setState("active", 0)
return
}
setState("active", 0)
input.pauseAutoScroll()
input.revealMessage(match.revealID, match.partID)
scrollToMatch(match)
}
function scrollToMatch(match: TimelineSearchMatch) {
let attempts = 0
const seek = () => {
if (!state.visible) return
const root = input.scrollRef()
if (!root) return
const { active } = collectRanges(root, query(), match.partID, match.occurrence)
if (active.length === 0) {
if (attempts++ < 12) requestAnimationFrame(seek)
return
}
const rect = active[0].getBoundingClientRect()
const rootRect = root.getBoundingClientRect()
const sticky = root.querySelector("[data-session-title]")
const inset = sticky instanceof HTMLElement ? sticky.offsetHeight : 0
const top = rect.top - rootRect.top + root.scrollTop - inset - (rootRect.height - rect.height) / 2
root.scrollTo({ top: Math.max(0, top), behavior: "auto" })
}
requestAnimationFrame(seek)
}
function move(delta: number) {
const list = matches()
if (list.length === 0) return
const next = (activeIndex() + delta + list.length) % list.length
setState("active", next)
const match = list[next]
if (!match) return
input.pauseAutoScroll()
input.revealMessage(match.revealID, match.partID)
scrollToMatch(match)
}
return {
visible: () => state.visible,
query: {
value: () => state.value,
placeholder: () => language.t("session.search.placeholder"),
noResults: () => language.t("session.search.noResults"),
open,
close,
setValue,
},
result: {
activeIndex,
count: () => matches().length,
move,
},
element: {
setInput: (element: HTMLInputElement) => (inputEl = element),
},
}
}
export type TimelineSearchController = ReturnType<typeof createTimelineSearchController>
@@ -69,7 +69,7 @@ type Input = {
row: TimelineRow.TimelineRow,
disclosure: Readonly<Record<string, boolean | undefined>>,
) => boolean
setRevealMessage?: (fn: (id: string, partID?: string) => void) => void
setRevealMessage?: (fn: (id: string) => void) => void
setScrollToEnd?: (fn: () => void) => void
}
@@ -271,13 +271,8 @@ export function createTimelineVirtualizer(input: Input) {
const virtualRowKeys = createMemo(() => virtualizer.getVirtualItems().map((item) => String(item.key)))
createEffect(() => {
input.setRevealMessage?.((id, partID) => {
const partIndex = partID
? rows().findIndex(
(row) => row._tag === "AssistantPart" && row.group.type === "part" && row.group.ref.partID === partID,
)
: -1
const index = partIndex >= 0 ? partIndex : input.projection.messageRowIndex().get(id)
input.setRevealMessage?.((id) => {
const index = input.projection.messageRowIndex().get(id)
if (index === undefined) return
virtualizer.scrollToIndex(index, { align: "center" })
})
@@ -1,6 +1,6 @@
import { createMemo, type Accessor } from "solid-js"
import { useGlobal, useServerCtx } from "@/runtime/server/runtime"
import { sessionPermissionRequest, sessionFormRequest } from "@/session/requests/session-request-tree"
import { sessionPermissionRequest, sessionQuestionForm } from "@/session/requests/session-request-tree"
import { ServerConnection } from "@/runtime/server/registry"
import { useSettings } from "@/settings/model"
@@ -29,12 +29,12 @@ export function useSessionTabAvatarState(
if (!ctx) return false
return !!sessionPermissionRequest(sessions(), ctx.data.session.permission.list, sessionId())
})
const hasForms = createMemo(() => {
const hasQuestions = createMemo(() => {
const data = serverCtx()?.data
if (!data) return false
return !!sessionFormRequest(sessions(), data.session.form.list, sessionId())
return !!sessionQuestionForm(sessions(), data.session.form.list, sessionId())
})
const needsAttention = createMemo(() => hasPermissions() || hasForms())
const needsAttention = createMemo(() => hasPermissions() || hasQuestions())
const unread = createMemo(
() => needsAttention() || (serverCtx()?.notification.session.unseenCount(sessionId()) ?? 0) > 0,
)
@@ -21,19 +21,6 @@ describe("serverStatusDotClass", () => {
expect(serverStatusDotClass({ ready: true, serverHealth: false, issue: true })).toBe("bg-icon-critical-base")
})
test("pulses the neutral dot while the event stream is reconnecting", () => {
expect(serverStatusDotClass({ ready: true, serverHealth: true, issue: false, connecting: true })).toBe(
"bg-border-weak-base animate-pulse",
)
expect(serverStatusDotClass({ ready: false, serverHealth: undefined, issue: false, connecting: true })).toBe(
"bg-border-weak-base animate-pulse",
)
// A server that is known to be down stays critical rather than looking like a routine reconnect.
expect(serverStatusDotClass({ ready: true, serverHealth: false, issue: false, connecting: true })).toBe(
"bg-icon-critical-base",
)
})
test("stays neutral before status is ready", () => {
expect(serverStatusDotClass({ ready: false, serverHealth: true, issue: false })).toBe("bg-border-weak-base")
expect(serverStatusDotClass({ ready: false, serverHealth: undefined, issue: false })).toBe("bg-border-weak-base")
@@ -20,12 +20,8 @@ export function serverStatusDotClass(input: {
serverHealth: boolean | undefined
attention?: boolean
issue: boolean
connecting?: boolean
}) {
if (input.serverHealth === false) return "bg-icon-critical-base"
// The event stream is (re)connecting: keep the neutral dot but let it breathe so a stale
// session is visibly waiting on the server rather than silently frozen.
if (input.connecting) return "bg-border-weak-base animate-pulse"
if (!input.ready || input.serverHealth === undefined) return "bg-border-weak-base"
if (input.attention) return "bg-v2-background-bg-accent"
if (input.issue) return "bg-icon-warning-base"
@@ -42,7 +42,6 @@ export function StatusPopover() {
serverHealth: serverHealth(),
attention: attention(),
issue: issue(),
connecting: server.ctx.sdk.connection.status() !== "connected",
sidebar: sidebar(),
placement: sidebar() ? "top-start" : "bottom-end",
shift: sidebar() ? 0 : -168,
@@ -64,7 +63,6 @@ type StatusPopoverState = {
serverHealth: boolean | undefined
attention: boolean
issue: boolean
connecting: boolean
sidebar: boolean
placement: "top-start" | "bottom-end"
shift: number
@@ -17,11 +17,9 @@ function createFixture(initial: Record<string, Session> = {}) {
const deferred = new Map<string, PromiseWithResolvers<unknown>>()
const resolves: string[] = []
const messages = { syncs: [] as string[], ...Promise.withResolvers<unknown>() }
const pending = { syncs: [] as string[] }
return {
resolves,
messages,
pending,
sessions: {
get: (id: string) => cache()[id],
sync: (id: string) => {
@@ -36,12 +34,6 @@ function createFixture(initial: Record<string, Session> = {}) {
return messages.promise
},
},
pending: {
sync: (id: string) => {
pending.syncs.push(id)
return Promise.resolve()
},
},
},
settle(id: string, directory = `/dir/${id}`) {
setCache({ ...cache(), [id]: { id, directory } })
@@ -94,7 +86,6 @@ test("refreshes the current session on reconnect while keeping cached content vi
expect(fixture.resolves).toEqual(["ses_a", "ses_a"])
expect(current()).toEqual(sessionOf("ses_a"))
expect(fixture.messages.syncs).toEqual(["ses_a", "ses_a"])
expect(fixture.pending.syncs).toEqual(["ses_a", "ses_a"])
fixture.settle("ses_a", "/worktrees/moved")
await flush()
expect(current()?.directory).toBe("/worktrees/moved")
@@ -1,209 +0,0 @@
import { afterEach, describe, expect, test } from "bun:test"
import type { FormCreated, FormReplyInput, OpenCodeEvent } from "@opencode-ai/client/promise"
import { createEffect, createRoot } from "solid-js"
import { createStore } from "solid-js/store"
import { createWebSearchRequest } from "@/session/requests/websearch"
const consent: FormCreated["data"]["form"] = {
id: "frm_consent",
sessionID: "ses_child",
title: "Web Search",
metadata: { kind: "websearch.provider" },
fields: [{ key: "choice", type: "string", required: true, custom: false }],
}
const options = [
{ value: "exa", label: "Exa" },
{ value: "parallel", label: "Parallel" },
]
const provider: FormCreated["data"]["form"] = {
...consent,
id: "frm_provider",
fields: [{ key: "provider", type: "string", options, required: true, custom: false }],
}
const cleanups: VoidFunction[] = []
afterEach(() => cleanups.splice(0).forEach((dispose) => dispose()))
function ready(condition: () => boolean) {
return new Promise<void>((resolve) => {
createRoot((dispose) => {
cleanups.push(dispose)
createEffect(() => {
if (!condition()) return
dispose()
resolve()
})
})
})
}
function fixture(form: FormCreated["data"]["form"] | null = consent) {
return createRoot((dispose) => {
cleanups.push(dispose)
const listeners = new Set<(event: OpenCodeEvent) => void>()
const replies: FormReplyInput[] = []
const loads: string[] = []
const [state, setState] = createStore({
request: form ?? undefined,
owner: "ses_root",
connected: true,
loadFails: false,
replyFails: false,
})
const model = createWebSearchRequest({
owner: () => state.owner,
connected: () => state.connected,
request: () => state.request,
providers: async (sessionID) => {
loads.push(sessionID)
if (state.loadFails) throw new Error("offline")
return options
},
reply: async (input) => {
replies.push(input)
if (state.replyFails) throw new Error("offline")
setState("request", undefined)
},
events: {
listen(listener) {
listeners.add(listener)
return () => {
listeners.delete(listener)
}
},
},
})
return {
model,
state,
setState,
replies,
loads,
dispose,
listeners,
create(form = provider) {
setState("request", form)
listeners.forEach((listener) =>
listener({
id: "evt_create",
created: 0,
type: "form.created",
data: { form },
}),
)
},
cancel(id: string) {
setState("request", undefined)
listeners.forEach((listener) =>
listener({
id: "evt_cancel",
created: 0,
type: "form.cancelled",
data: { id, sessionID: consent.sessionID },
}),
)
},
}
})
}
describe("web search request state", () => {
test("loads providers for the form owner, not the viewed parent, and waits for consent", async () => {
const input = fixture()
await ready(() => !input.model.loading())
expect(input.loads).toEqual(["ses_child"])
expect(input.model.selected()).toBe("random")
input.model.select("exa")
expect(input.replies).toEqual([])
await input.model.submit(false)
expect(input.replies[0]?.answer).toEqual({ choice: "disable" })
expect(input.model.request()).toBeUndefined()
expect(input.model.sending()).toBe(false)
})
test("does not load providers when there is no consent request", () => {
const input = fixture(null)
expect(input.model.request()).toBeUndefined()
expect(input.loads).toEqual([])
})
test("holds the card across both forms and prevents duplicate submissions", async () => {
const input = fixture()
await ready(() => !input.model.loading())
input.model.select("parallel")
const pending = input.model.submit("parallel")
await input.model.submit("parallel")
expect(input.state.request).toBeUndefined()
expect(input.model.request()?.id).toBe(consent.id)
expect(input.model.sending()).toBe(true)
input.create()
await pending
expect(input.replies.map((reply) => reply.answer)).toEqual([{ choice: "choose" }, { provider: "parallel" }])
expect(input.model.request()).toBeUndefined()
expect(input.model.sending()).toBe(false)
expect(input.listeners.size).toBe(0)
})
test("direct provider requests need confirmation and do not load a different provider list", async () => {
const input = fixture(provider)
await ready(() => !input.model.loading())
expect(input.loads).toEqual([])
expect(input.model.specific()).toBe(true)
expect(input.model.options()).toEqual(options)
expect(input.replies).toEqual([])
await input.model.submit("exa")
expect(input.replies.map((reply) => reply.answer)).toEqual([{ provider: "exa" }])
})
test("keeps the selected provider after failure and retries only the provider form", async () => {
const input = fixture()
await ready(() => !input.model.loading())
input.model.select("parallel")
const pending = input.model.submit("parallel")
input.setState("replyFails", true)
input.create()
await pending
expect(input.model.failed()).toBe(true)
expect(input.model.sending()).toBe(false)
expect(input.model.request()?.id).toBe(provider.id)
expect(input.model.selected()).toBe("parallel")
input.setState("replyFails", false)
await input.model.submit("parallel")
expect(input.replies.map((reply) => reply.answer)).toEqual([
{ choice: "choose" },
{ provider: "parallel" },
{ provider: "parallel" },
])
expect(input.model.request()).toBeUndefined()
})
test("can retry loading providers without submitting consent", async () => {
const input = fixture()
await ready(() => !input.model.loading())
input.setState("loadFails", true)
input.model.retry()
await ready(() => input.model.loadFailed())
expect(input.model.options()).toEqual([])
input.setState("loadFails", false)
input.model.retry()
await ready(() => !input.model.loading())
expect(input.model.options()).toEqual(options)
expect(input.model.loadFailed()).toBe(false)
expect(input.replies).toEqual([])
})
test.each(["navigate", "disconnect", "dispose", "cancel"])("stops automatic replies on %s", async (action) => {
const input = fixture()
await ready(() => !input.model.loading())
const pending = input.model.submit("exa")
if (action === "navigate") input.setState("owner", "ses_other")
if (action === "disconnect") input.setState("connected", false)
if (action === "dispose") input.dispose()
if (action === "cancel") input.cancel(consent.id)
await pending
expect(input.model.sending()).toBe(false)
expect(input.listeners.size).toBe(0)
input.create()
expect(input.replies.map((reply) => reply.answer)).toEqual([{ choice: "choose" }])
})
})
+1 -4
View File
@@ -605,10 +605,7 @@ export type SessionLogOutput =
readonly type: "session.execution.interrupted"
readonly durable: { readonly aggregateID: string; readonly seq: Event.Seq; readonly version: Event.Version }
readonly location?: Location.Ref | undefined
readonly data: {
readonly sessionID: Session.ID
readonly reason: "user" | "shutdown" | "superseded" | "inactivity"
}
readonly data: { readonly sessionID: Session.ID; readonly reason: "user" | "shutdown" | "superseded" }
}
| {
readonly id: Event.ID
+1 -1
View File
@@ -9,7 +9,7 @@ export type { ClientOptions, RequestOptions } from "./generated/client.js"
export function make(options: ClientOptions) {
const raw = OpenCode.make(options)
const events = SharedEvents.make((signal, onActivity) => raw.event.subscribe({ signal, onActivity }))
const events = SharedEvents.make((signal) => raw.event.subscribe({ signal }))
return {
...raw,
rpc: Object.assign(makeRpc(raw, events), raw.rpc),
@@ -278,8 +278,6 @@ export interface ClientOptions {
export interface RequestOptions {
readonly signal?: AbortSignal
readonly headers?: RequestInit["headers"]
/** Reports every chunk a streaming response receives, including keepalive comments that yield no event. */
readonly onActivity?: () => void
}
interface RequestDescriptor {
@@ -371,7 +369,6 @@ export function make(options: ClientOptions) {
} catch (cause) {
throw new ClientError("Transport", { cause })
}
if (!next.done) requestOptions?.onActivity?.()
buffer += decoder.decode(next.value, { stream: !next.done })
if (buffer.length > maxSseEventBytes) throw new ClientError("SseEventTooLarge")
const trailingCarriageReturn = !next.done && buffer.endsWith("\r")
@@ -710,7 +710,7 @@ export type SessionExecutionInterrupted = {
type: "session.execution.interrupted"
durable: { aggregateID: string; seq: number; version: 1 }
location?: LocationRef
data: { sessionID: string; reason: "user" | "shutdown" | "superseded" | "inactivity" }
data: { sessionID: string; reason: "user" | "shutdown" | "superseded" }
}
export type SessionInstructionsUpdated = {
@@ -2045,6 +2045,7 @@ export type ConfigEntry =
experimental?: {
portable_shell_scanner?: boolean
subagent_depth?: number
subagent_fork?: boolean
policies?: Array<{ action: "provider.use"; resource: string; effect: "allow" | "deny" }>
}
}
+3 -15
View File
@@ -1,19 +1,10 @@
export * as SharedEvents from "./shared-events.js"
export type SubscribeOptions = {
readonly signal?: AbortSignal
/** Reports transport activity on the shared stream, including keepalive frames that carry no event. */
readonly onActivity?: () => void
}
export function make<A extends { readonly type: string }>(
connect: (signal: AbortSignal, onActivity: () => void) => AsyncIterable<A>,
) {
export function make<A extends { readonly type: string }>(connect: (signal: AbortSignal) => AsyncIterable<A>) {
type Completion = { readonly error: unknown } | Record<string, never>
type Subscriber = {
push: (value: A) => void
finish: (completion: Completion) => void
activity?: () => void
}
type Connection = {
controller: AbortController
@@ -35,9 +26,7 @@ export function make<A extends { readonly type: string }>(
let completion: Completion = {}
try {
if (connection.controller.signal.aborted) return
iterator = connect(connection.controller.signal, () => {
connection.subscribers.forEach((subscriber) => subscriber.activity?.())
})[Symbol.asyncIterator]()
iterator = connect(connection.controller.signal)[Symbol.asyncIterator]()
while (!connection.controller.signal.aborted) {
const item = await iterator.next()
if (item.done || connection.controller.signal.aborted) break
@@ -58,7 +47,7 @@ export function make<A extends { readonly type: string }>(
}
return {
subscribe(options?: SubscribeOptions): AsyncIterable<A> {
subscribe(options?: { readonly signal?: AbortSignal }): AsyncIterable<A> {
return {
[Symbol.asyncIterator]() {
const pending: ReturnType<typeof Promise.withResolvers<IteratorResult<A>>>[] = []
@@ -83,7 +72,6 @@ export function make<A extends { readonly type: string }>(
}
const subscriber: Subscriber = {
activity: options?.onActivity,
finish(result) {
finish(result, false)
},
+17 -76
View File
@@ -1,4 +1,4 @@
import { batch, onCleanup } from "solid-js"
import { batch, onCleanup, onMount } from "solid-js"
import { createStore } from "solid-js/store"
import type { OpenCodeClient, OpenCodeEvent } from "../promise"
@@ -18,11 +18,6 @@ export type ClientConnectionOptions = {
readonly onEvent: (event: OpenCodeEvent) => void
readonly flushInterval?: number
readonly pageLifecycle?: boolean
/**
* Abort and reconnect a stream that receives no bytes for this long. The server writes a keepalive
* comment every 15 seconds, so a quiet but healthy stream never trips this.
*/
readonly idleTimeout?: number
readonly log?: {
readonly debug?: (message: string, data?: Readonly<Record<string, unknown>>) => void
readonly info?: (message: string, data?: Readonly<Record<string, unknown>>) => void
@@ -32,15 +27,10 @@ export type ClientConnectionOptions = {
const connectTimeout = 2_000
const reconnectDelay = 1_000
const connectionHistoryLimit = 50
export const defaultIdleTimeout = 45_000
// Longer than one server keepalive interval: a stream that is silent this long when the page
// returns to the foreground is probably half-open after the device slept.
export const foregroundIdleThreshold = 20_000
export function createClientConnection(initialApi: OpenCodeClient, options: ClientConnectionOptions) {
const abort = new AbortController()
const history: ClientConnectionEvent[] = []
const idleTimeout = options.idleTimeout ?? defaultIdleTimeout
const [connection, setConnection] = createStore<{
status: ClientConnectionStatus
attempt: number
@@ -50,12 +40,9 @@ export function createClientConnection(initialApi: OpenCodeClient, options: Clie
let pending: OpenCodeEvent[] = []
let flushTimer: ReturnType<typeof setTimeout> | undefined
let stream: AbortController | undefined
let current: AbortController | undefined
let run: Promise<void> | undefined
let started = false
let generation = 0
let lastActivity = 0
let forced = false
function record(status: ClientConnectionEvent["data"]["status"], attempt: number, error?: string) {
history.push({ type: "client.connection", created: Date.now(), data: { status, attempt, error } })
@@ -76,25 +63,14 @@ export function createClientConnection(initialApi: OpenCodeClient, options: Clie
async function connect(signal: AbortSignal, attempt: number) {
let connectedAt: number | undefined
const request = new AbortController()
current = request
const cancel = () => request.abort(signal.reason)
const timeout = setTimeout(() => request.abort(new Error("Timed out connecting to server")), connectTimeout)
signal.addEventListener("abort", cancel, { once: true })
// Any received bytes, including keepalive comments, push the stall deadline out. A timer whose
// deadline passed while the page was suspended fires as soon as the page resumes.
let watchdog: ReturnType<typeof setTimeout> | undefined
const touch = () => {
lastActivity = Date.now()
if (connectedAt === undefined) return
clearTimeout(watchdog)
watchdog = setTimeout(() => request.abort(new Error("Event stream stalled")), idleTimeout)
}
try {
record(attempt === 0 ? "connecting" : "reconnecting", attempt)
options.log?.info?.("event stream connecting", { attempt })
const iterator = api.event.subscribe({ signal: request.signal, onActivity: touch })[Symbol.asyncIterator]()
const iterator = api.event.subscribe({ signal: request.signal })[Symbol.asyncIterator]()
const first = await iterator.next()
if (signal.aborted) return { error: undefined, connectedAt }
if (first.done)
@@ -109,7 +85,6 @@ export function createClientConnection(initialApi: OpenCodeClient, options: Clie
clearTimeout(timeout)
record("connected", attempt)
connectedAt = Date.now()
touch()
options.log?.info?.("event stream connected")
publish(first.value)
setConnection({ status: "connected", attempt: 0, error: undefined })
@@ -117,13 +92,7 @@ export function createClientConnection(initialApi: OpenCodeClient, options: Clie
while (!signal.aborted) {
const event = await iterator.next()
if (signal.aborted) return { error: undefined, connectedAt }
if (event.done)
return {
error:
request.signal.reason instanceof Error ? request.signal.reason : new Error("Event stream disconnected"),
connectedAt,
}
touch()
if (event.done) return { error: new Error("Event stream disconnected"), connectedAt }
if ("durable" in event.value && event.value.durable)
options.log?.debug?.("event", {
type: event.value.type,
@@ -137,9 +106,7 @@ export function createClientConnection(initialApi: OpenCodeClient, options: Clie
return { error, connectedAt }
} finally {
request.abort()
if (current === request) current = undefined
clearTimeout(timeout)
clearTimeout(watchdog)
signal.removeEventListener("abort", cancel)
}
}
@@ -173,11 +140,6 @@ export function createClientConnection(initialApi: OpenCodeClient, options: Clie
if (attempt === 1) continue
}
}
// A deliberate resync already knows the old socket is gone; reconnect without backing off.
if (forced) {
forced = false
continue
}
await wait(reconnectDelay, controller.signal)
}
}
@@ -185,7 +147,6 @@ export function createClientConnection(initialApi: OpenCodeClient, options: Clie
function start() {
if (started) return run
started = true
forced = false
const active = ++generation
const previous = run
const current = (async () => {
@@ -200,45 +161,26 @@ export function createClientConnection(initialApi: OpenCodeClient, options: Clie
}
function stop() {
if (!started) return
started = false
generation += 1
stream?.abort()
// Nothing is listening once stopped, so consumers must treat their data as stale until start() reconnects.
setConnection({ status: "connecting", attempt: 0, error: undefined })
}
// Drop the live request so the reconnect loop replaces it now instead of waiting for the idle watchdog.
function resync(reason: string) {
if (!started || connection.status !== "connected") return
options.log?.info?.("event stream resync", { reason, idle: Date.now() - lastActivity })
forced = true
current?.abort(new Error(reason))
}
if (options.pageLifecycle) {
const pagehide = () => stop()
const pageshow = () => void start()
// Locking a phone or switching apps hides the document without a pagehide; the socket usually
// dies while the page is suspended, and the browser may never report that on the hung read.
const visibility = () => {
if (document.visibilityState !== "visible") return
if (Date.now() - lastActivity < foregroundIdleThreshold) return
resync("Page returned to the foreground after the event stream went quiet")
onMount(() => {
if (options.pageLifecycle) {
const pagehide = () => stop()
const pageshow = (event: PageTransitionEvent) => {
if (event.persisted) void start()
}
window.addEventListener("pagehide", pagehide)
window.addEventListener("pageshow", pageshow)
onCleanup(() => {
window.removeEventListener("pagehide", pagehide)
window.removeEventListener("pageshow", pageshow)
})
}
const online = () => resync("Network connection restored")
window.addEventListener("pagehide", pagehide)
window.addEventListener("pageshow", pageshow)
window.addEventListener("online", online)
document.addEventListener("visibilitychange", visibility)
onCleanup(() => {
window.removeEventListener("pagehide", pagehide)
window.removeEventListener("pageshow", pageshow)
window.removeEventListener("online", online)
document.removeEventListener("visibilitychange", visibility)
})
}
void start()
void start()
})
onCleanup(() => {
stop()
@@ -253,7 +195,6 @@ export function createClientConnection(initialApi: OpenCodeClient, options: Clie
error: () => connection.error,
internal: {
history: () => history.slice(),
resync,
},
}
}
-25
View File
@@ -675,31 +675,6 @@ test("event.subscribe ignores server heartbeat comments", async () => {
expect(received).toEqual([event])
})
test("event.subscribe reports heartbeat comments as stream activity", async () => {
const event = { id: "evt_sentinel", created: 1, type: "server.connected", data: {} }
const encoder = new TextEncoder()
const client = OpenCode.make({
baseUrl: "http://localhost:3000",
fetch: async () =>
new Response(
new ReadableStream({
start(controller) {
controller.enqueue(encoder.encode(": heartbeat\n\n"))
controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`))
controller.enqueue(encoder.encode(": heartbeat\n\n"))
controller.close()
},
}),
{ headers: { "content-type": "text/event-stream" } },
),
})
let activity = 0
const received = []
for await (const item of client.event.subscribe({ onActivity: () => activity++ })) received.push(item)
expect(received).toEqual([event])
expect(activity).toBe(3)
})
// Moved from packages/app/e2e/regression/session-timeline-transport.spec.ts
test("event transport passes through ordinary health requests", async () => {
const requests: string[] = []
@@ -359,24 +359,3 @@ test("synchronous source creation failures reject subscribers without automatic
await expect(shared.subscribe()[Symbol.asyncIterator]().next()).rejects.toBe(failure)
expect(attempts).toHaveLength(2)
})
test("source activity fans out to every subscriber that asked for it", async () => {
const events = source()
let activity: (() => void) | undefined
const shared = SharedEvents.make<Event>((signal, onActivity) => {
activity = onActivity
return events.connect(signal)
})
const counts = { first: 0, second: 0 }
const first = shared.subscribe({ onActivity: () => counts.first++ })[Symbol.asyncIterator]()
const second = shared.subscribe()[Symbol.asyncIterator]()
const reads = Promise.all([first.next(), second.next()])
activity!()
activity!()
events.connections[0].push({ type: "server.connected" })
await reads
expect(counts).toEqual({ first: 2, second: 0 })
await first.return!()
await second.return!()
await events.connections[0].closed
})
@@ -1,153 +0,0 @@
import { expect, test } from "bun:test"
import { createRoot } from "solid-js"
import { createClientConnection } from "../src/solid"
import { OpenCode, type OpenCodeEvent } from "../src/promise"
const connected = { id: "evt_connected", created: 1, type: "server.connected", data: {} }
// One fake server whose event streams stay open until the test writes to them or the client aborts.
function server() {
const encoder = new TextEncoder()
const streams: {
write: (text: string) => void
close: () => void
aborted: boolean
}[] = []
const api = OpenCode.make({
baseUrl: "http://opencode.local",
fetch: async (input, init) => {
const request = input instanceof Request ? input : new Request(input, init)
let controller!: ReadableStreamDefaultController<Uint8Array>
const entry = {
write: (text: string) => controller.enqueue(encoder.encode(text)),
close: () => controller.close(),
aborted: false,
}
const body = new ReadableStream<Uint8Array>({
start(value) {
controller = value
},
cancel() {
entry.aborted = true
},
})
request.signal.addEventListener("abort", () => {
entry.aborted = true
controller.error(request.signal.reason)
})
streams.push(entry)
return new Response(body, { headers: { "content-type": "text/event-stream" } })
},
})
return { api, streams }
}
function setup(input: ReturnType<typeof server>, idleTimeout: number) {
const events: OpenCodeEvent[] = []
return createRoot((dispose) => ({
events,
dispose,
connection: createClientConnection(input.api, {
idleTimeout,
flushInterval: 0,
onEvent: (event) => events.push(event),
}),
}))
}
async function until(check: () => boolean, timeout = 2_000) {
const deadline = Date.now() + timeout
while (!check()) {
if (Date.now() > deadline) throw new Error("Timed out waiting for condition")
await new Promise((resolve) => setTimeout(resolve, 5))
}
}
test("a stream that goes silent past the idle timeout is replaced", async () => {
const fake = server()
const ctx = setup(fake, 60)
try {
await until(() => fake.streams.length === 1)
fake.streams[0].write(`data: ${JSON.stringify(connected)}\n\n`)
await until(() => ctx.connection.status() === "connected")
await until(() => fake.streams.length === 2)
expect(fake.streams[0].aborted).toBe(true)
expect(ctx.connection.internal.history().map((item) => item.data)).toContainEqual({
status: "disconnected",
attempt: 1,
error: "Event stream stalled",
})
fake.streams[1].write(`data: ${JSON.stringify({ ...connected, id: "evt_connected_2" })}\n\n`)
await until(() => ctx.connection.status() === "connected" && ctx.events.length === 2)
expect(ctx.connection.error()).toBeUndefined()
} finally {
ctx.dispose()
}
})
test("keepalive comments hold a quiet stream open", async () => {
const fake = server()
const ctx = setup(fake, 60)
try {
await until(() => fake.streams.length === 1)
fake.streams[0].write(`data: ${JSON.stringify(connected)}\n\n`)
await until(() => ctx.connection.status() === "connected")
const heartbeat = setInterval(() => fake.streams[0].write(": heartbeat\n\n"), 20)
await new Promise((resolve) => setTimeout(resolve, 250))
clearInterval(heartbeat)
expect(fake.streams).toHaveLength(1)
expect(fake.streams[0].aborted).toBe(false)
expect(ctx.connection.status()).toBe("connected")
expect(ctx.events).toHaveLength(1)
} finally {
ctx.dispose()
}
})
test("a forced resync replaces the stream immediately and only while connected", async () => {
const fake = server()
const ctx = setup(fake, 10_000)
try {
ctx.connection.internal.resync("too early")
await until(() => fake.streams.length === 1)
expect(fake.streams[0].aborted).toBe(false)
fake.streams[0].write(`data: ${JSON.stringify(connected)}\n\n`)
await until(() => ctx.connection.status() === "connected")
const started = Date.now()
ctx.connection.internal.resync("Network connection restored")
await until(() => fake.streams.length === 2)
expect(Date.now() - started).toBeLessThan(500)
expect(fake.streams[0].aborted).toBe(true)
expect(ctx.connection.internal.history().map((item) => item.data)).toContainEqual({
status: "disconnected",
attempt: 1,
error: "Network connection restored",
})
fake.streams[1].write(`data: ${JSON.stringify(connected)}\n\n`)
await until(() => ctx.connection.status() === "connected")
} finally {
ctx.dispose()
}
})
test("a stream the server closes reconnects and reports the disconnect", async () => {
const fake = server()
const ctx = setup(fake, 10_000)
try {
await until(() => fake.streams.length === 1)
fake.streams[0].write(`data: ${JSON.stringify(connected)}\n\n`)
await until(() => ctx.connection.status() === "connected")
fake.streams[0].close()
await until(() => ctx.connection.status() === "reconnecting")
expect(ctx.connection.error()).toBe("Event stream disconnected")
await until(() => fake.streams.length === 2)
} finally {
ctx.dispose()
}
})
+9
View File
@@ -426,6 +426,15 @@ function normalizeExperimental(
)
if (value !== undefined) result.subagent_depth = value
}
if (own(experimental, "subagent_fork")) {
const value = decodeEncoded(
ConfigExperimental.Info.fields.subagent_fork,
experimental.subagent_fork,
["experimental", "subagent_fork"],
diagnostics,
)
if (value !== undefined) result.subagent_fork = value
}
native.push(
...decodeList(
experimental.policies,
+11 -83
View File
@@ -1,14 +1,13 @@
export * as Credential from "./credential.js"
import { asc, desc, eq } from "drizzle-orm"
import { Cause, Context, Effect, Layer, Schema } from "effect"
import { Context, Effect, Layer, Schema } from "effect"
import { Credential } from "@opencode-ai/schema/credential"
import { Integration } from "@opencode-ai/schema/integration"
import { Database } from "./database/database.js"
import { Bus } from "./bus.js"
import { makeGlobalNode } from "@opencode-ai/util/effect/app-node"
import { CredentialTable } from "./credential/sql.js"
import { ErrorSummary } from "./util/error-summary.js"
export const ID = Credential.ID
export type ID = Credential.ID
@@ -124,21 +123,7 @@ const layer = Layer.effect(
.run()
}),
)
.pipe(
Effect.onError((cause) =>
Effect.logError("credential create failed", {
credentialID: credential.id,
integrationID: credential.integrationID,
errors: ErrorSummary.from(Cause.squash(cause)),
}),
),
Effect.orDie,
)
yield* Effect.logInfo("credential created", {
credentialID: credential.id,
integrationID: credential.integrationID,
type: credential.value.type,
})
.pipe(Effect.orDie)
yield* bus.publish(Event.Updated, {}, { global: true })
yield* bus.publish(
Event.Switched,
@@ -169,19 +154,8 @@ const layer = Layer.effect(
return credential.integration_id
}),
)
.pipe(
Effect.onError((cause) =>
Effect.logError("credential activate failed", {
credentialID: id,
errors: ErrorSummary.from(Cause.squash(cause)),
}),
),
Effect.orDie,
)
if (integrationID) {
yield* Effect.logInfo("credential activated", { integrationID, credentialID: id })
yield* bus.publish(Event.Switched, { integrationID, credentialID: id }, { global: true })
}
.pipe(Effect.orDie)
if (integrationID) yield* bus.publish(Event.Switched, { integrationID, credentialID: id }, { global: true })
}),
update: Effect.fn("Credential.update")(function* (id, updates) {
if (updates.label === undefined && updates.value === undefined) return
@@ -190,46 +164,15 @@ const layer = Layer.effect(
.from(CredentialTable)
.where(eq(CredentialTable.id, id))
.get()
.pipe(
Effect.onError((cause) =>
Effect.logError("credential update lookup failed", {
credentialID: id,
errors: ErrorSummary.from(Cause.squash(cause)),
}),
),
Effect.orDie,
)
if (!credential?.integrationID) {
yield* Effect.logWarning("credential update skipped", { credentialID: id, reason: "credential_missing" })
return
}
.pipe(Effect.orDie)
if (!credential?.integrationID) return
if (updates.label === credential.label && updates.value === undefined) return
const updated = yield* db
yield* db
.update(CredentialTable)
.set({ label: updates.label, value: updates.value })
.where(eq(CredentialTable.id, id))
.returning({ id: CredentialTable.id })
.get()
.pipe(
Effect.onError((cause) =>
Effect.logError("credential update failed", {
credentialID: id,
integrationID: credential.integrationID,
errors: ErrorSummary.from(Cause.squash(cause)),
}),
),
Effect.orDie,
)
if (!updated) {
yield* Effect.logWarning("credential update skipped", { credentialID: id, reason: "credential_removed" })
return
}
yield* Effect.logInfo("credential updated", {
credentialID: id,
integrationID: credential.integrationID,
valueChanged: updates.value !== undefined,
labelChanged: updates.label !== undefined && updates.label !== credential.label,
})
.run()
.pipe(Effect.orDie)
if (updates.label !== undefined && updates.label !== credential.label)
yield* bus.publish(Event.Updated, {}, { global: true })
}),
@@ -248,8 +191,7 @@ const layer = Layer.effect(
.get()
: undefined
yield* tx.delete(CredentialTable).where(eq(CredentialTable.id, id)).run()
if (!credential.integration_id || active?.id !== id)
return { switched: false as const, integrationID: credential.integration_id }
if (!credential.integration_id || active?.id !== id) return { switched: false as const }
const replacement = yield* tx
.select({ id: CredentialTable.id })
.from(CredentialTable)
@@ -275,22 +217,8 @@ const layer = Layer.effect(
}
}),
)
.pipe(
Effect.onError((cause) =>
Effect.logError("credential remove failed", {
credentialID: id,
errors: ErrorSummary.from(Cause.squash(cause)),
}),
),
Effect.orDie,
)
.pipe(Effect.orDie)
if (!removed) return
yield* Effect.logInfo("credential removed", {
credentialID: id,
integrationID: removed.integrationID,
active: removed.switched,
...(removed.switched ? { replacementID: removed.credentialID } : {}),
})
yield* bus.publish(Event.Updated, {}, { global: true })
if (removed.switched)
yield* bus.publish(
+15 -37
View File
@@ -5,8 +5,6 @@ import { Bus } from "./bus.js"
import { Location } from "./location.js"
import { LocationServiceMap } from "./location-service-map.js"
import { SessionEvent } from "./session/event.js"
import { SessionExecution } from "./session/execution.js"
import { SessionStore } from "./session/store.js"
import { makeGlobalNode } from "@opencode-ai/util/effect/app-node"
const isSessionEvent = Schema.is(SessionEvent.Durable)
@@ -20,11 +18,9 @@ export function layer(options: { readonly timeToLive?: Duration.Input; readonly
const clock = yield* Clock.Clock
const bus = yield* Bus.Service
const locations = yield* LocationServiceMap.Service
const execution = yield* SessionExecution.Service
const sessions = yield* SessionStore.Service
const timeToLive = Duration.toMillis(options.timeToLive ?? "60 minutes")
const entries = new Map<string, { readonly ref: Location.Ref; expiresAt: number }>()
const key = (ref: Location.Ref) => `${LocationServiceMap.canonical(ref).directory}\0${ref.workspaceID ?? ""}`
const key = (ref: Location.Ref) => `${ref.directory}\0${ref.workspaceID ?? ""}`
const touch = (ref: Location.Ref) =>
Effect.sync(() => {
entries.set(key(ref), { ref, expiresAt: clock.currentTimeMillisUnsafe() + timeToLive })
@@ -43,44 +39,26 @@ export function layer(options: { readonly timeToLive?: Duration.Input; readonly
yield* Effect.sleep(options.sweepInterval ?? "1 minute")
const refs = Array.from(yield* RcMap.keys(locations.rcMap))
const cached = new Set(refs.map(key))
yield* Effect.forEach(refs, (ref) => (entries.has(key(ref)) ? Effect.void : touch(ref)), { discard: true })
yield* Effect.forEach(
refs,
(ref) => (entries.has(key(ref)) ? Effect.void : touch(ref)),
{ discard: true },
)
for (const id of entries.keys()) {
if (!cached.has(id)) entries.delete(id)
}
const now = clock.currentTimeMillisUnsafe()
const expired = Array.from(entries.values()).filter((entry) => entry.expiresAt <= now)
if (expired.length === 0) return
const active = yield* Effect.forEach(yield* execution.active, (sessionID) => sessions.get(sessionID))
yield* Effect.forEach(
expired,
(entry) =>
Effect.gen(function* () {
const owners = active.flatMap((session) =>
session && key(session.location) === key(entry.ref) ? [session] : [],
)
// Invalidation only detaches the cache entry; borrowers retain the old
// graph. Stop its executions and settle tool cleanup before detaching it.
yield* Effect.forEach(
owners,
(session) => execution.interrupt(session.id, { reason: "inactivity", awaitSettlement: true }),
{
discard: true,
concurrency: "unbounded",
},
)
const remaining = yield* Effect.forEach(yield* execution.active, (sessionID) => sessions.get(sessionID))
// New work admitted during cleanup may now own the cached graph.
if (remaining.some((session) => session && key(session.location) === key(entry.ref))) {
yield* touch(entry.ref)
return
}
entries.delete(key(entry.ref))
yield* Effect.logInfo("location services evicted", {
directory: entry.ref.directory,
workspaceID: entry.ref.workspaceID,
}).pipe(Effect.andThen(locations.invalidate(entry.ref)))
}),
{ discard: true, concurrency: "unbounded" },
(entry) => {
entries.delete(key(entry.ref))
return Effect.logInfo("location services evicted", {
directory: entry.ref.directory,
workspaceID: entry.ref.workspaceID,
}).pipe(Effect.andThen(locations.invalidate(entry.ref)))
},
{ discard: true },
)
}).pipe(Effect.forever, Effect.forkScoped)
@@ -92,5 +70,5 @@ export function layer(options: { readonly timeToLive?: Duration.Input; readonly
export const node = makeGlobalNode({
service: Service,
layer: layer(),
deps: [Bus.node, LocationServiceMap.node, SessionExecution.node, SessionStore.node],
deps: [Bus.node, LocationServiceMap.node],
})
-3
View File
@@ -231,8 +231,6 @@ export const connect = Effect.fnUntraced(function* (
}
if (!URL.canParse(config.url))
return yield* new ConnectError({ server, message: `Invalid MCP URL for "${server}"` })
const { McpOAuth } = yield* Effect.promise(() => import("./oauth.js"))
const fetch = yield* McpOAuth.loggedFetch({ server, directory })
// Prefer raw tools for our Code Mode without changing the configured URL used for OAuth identity.
const url = new URL(config.url)
const addedCodemode = config.codemode !== false && !url.searchParams.has("codemode")
@@ -242,7 +240,6 @@ export const connect = Effect.fnUntraced(function* (
new StreamableHTTPClientTransport(url, {
requestInit: config.headers ? { headers: config.headers } : undefined,
authProvider,
fetch,
}),
)
+8 -49
View File
@@ -259,41 +259,27 @@ export const layer = (options?: Options) =>
const { McpOAuth } = yield* Effect.promise(() => import("./oauth.js"))
const remote = entry.config
const oauth = remote.oauth || undefined
const run = Effect.runPromiseWith(yield* Effect.context())
const base = {
redirectUrl: oauth?.redirect_uri ?? "http://127.0.0.1/callback",
scope: oauth?.scope,
client: oauth?.client_id ? { id: oauth.client_id, secret: oauth.client_secret } : undefined,
// No browser during connect: an auth-gated server surfaces needs_auth instead of opening a browser.
onRedirect: () => run(Effect.logInfo("mcp oauth authorization required")),
onRedirect: () => {},
}
const found = (yield* credentials.list(entry.integrationID)).at(-1)
if (!found || found.value.type !== "oauth") {
if (!found || found.value.type !== "oauth")
// No stored credential yet: an empty in-memory store still lets the SDK run the auth handshake, which
// ends in UnauthorizedError -> needs_auth. Returning no provider instead would let the transport throw
// a raw HTTP error, hiding the auth requirement behind a generic failed status. Anonymous servers are
// unaffected: tokens() returns undefined, so no auth header is sent and the SDK never calls auth().
yield* Effect.logInfo("mcp oauth credential unavailable", {
integrationID: entry.integrationID,
reason: found ? "not_oauth" : "missing",
})
return McpOAuth.provider({ ...base, store: McpOAuth.memoryStore() })
}
const credentialID = found.id
const methodID = found.value.methodID
const fields = { credentialID, integrationID: entry.integrationID }
yield* Effect.logInfo("mcp oauth credential loaded", {
...fields,
hasRefreshToken: Boolean(found.value.refresh),
hasClientInformation: Boolean(McpOAuth.clientFromCredential(found.value)),
expiresAt: found.value.expires,
expired: found.value.expires !== 0 && found.value.expires <= Date.now(),
})
// Tracks the refresh token this provider last presented, so invalidate can tell whether the SDK
// rejected the currently-stored credential or a snapshot another connection has already rotated past.
let presented = found.value.refresh
const readOAuthCredential = async () => {
const stored = await run(credentials.get(credentialID))
const stored = await Effect.runPromise(credentials.get(credentialID))
return stored?.value.type === "oauth" ? stored.value : undefined
}
return McpOAuth.provider({
@@ -304,25 +290,10 @@ export const layer = (options?: Options) =>
// strand every connection in needs_auth until a manual re-auth. Credential deletion notifies all locations;
// reconnects remain serialized by the server lock.
invalidate: async (scope) => {
if (scope === "verifier" || scope === "discovery") {
await run(
Effect.logDebug("mcp oauth invalidation skipped", { ...fields, scope, reason: "not_credentials" }),
)
return
}
if (scope === "verifier" || scope === "discovery") return
const oauth = await readOAuthCredential()
if (!oauth || oauth.refresh !== presented) {
await run(
Effect.logInfo("mcp oauth invalidation skipped", {
...fields,
scope,
reason: oauth ? "token_rotated" : "credential_missing",
}),
)
return
}
await run(Effect.logWarning("mcp oauth credential invalidation requested", { ...fields, scope }))
await run(credentials.remove(credentialID))
if (!oauth || oauth.refresh !== presented) return
await Effect.runPromise(credentials.remove(credentialID))
},
// Always read the latest stored tokens instead of caching at connect time: with refresh-token rotation,
// a cached snapshot goes stale the moment another connection refreshes, and re-presenting the consumed
@@ -343,16 +314,7 @@ export const layer = (options?: Options) =>
client: previous ? McpOAuth.clientFromCredential(previous) : undefined,
})
presented = value.refresh
await run(
Effect.logInfo("mcp oauth tokens received", {
...fields,
credentialPresent: Boolean(previous),
refreshRotated: Boolean(previous && previous.refresh !== value.refresh),
hasRefreshToken: Boolean(value.refresh),
expiresAt: value.expires,
}),
)
await run(credentials.update(credentialID, { value }))
await Effect.runPromise(credentials.update(credentialID, { value }))
},
clientInformation: async () => {
const oauth = await readOAuthCredential()
@@ -598,10 +560,7 @@ export const layer = (options?: Options) =>
: { status: "failed", error: error instanceof Error ? error.message : String(error) }
yield* Effect.logWarning("mcp connect failed", { server: name, status: entry.status })
yield* bus.publish(McpEvent.StatusChanged, { server: name })
}).pipe(
Effect.ensuring(entry.startup.open),
Effect.annotateLogs({ server: name, directory: location.directory, connectionID: crypto.randomUUID() }),
)
}).pipe(Effect.ensuring(entry.startup.open))
const stopServer = Effect.fnUntraced(function* (name: ServerName, entry: ServerEntry) {
const scope = entry.scope
+9 -90
View File
@@ -1,63 +1,12 @@
export * as McpOAuth from "./oauth.js"
import { auth, parseErrorResponse, type OAuthClientProvider } from "@modelcontextprotocol/sdk/client/auth.js"
import { auth, type OAuthClientProvider } from "@modelcontextprotocol/sdk/client/auth.js"
import type { OAuthClientInformationMixed, OAuthTokens } from "@modelcontextprotocol/sdk/shared/auth.js"
import type { FetchLike } from "@modelcontextprotocol/sdk/shared/transport.js"
import { Cause, Deferred, Effect } from "effect"
import { Deferred, Effect } from "effect"
import { Credential } from "@opencode-ai/schema/credential"
import { ConfigMCP } from "@opencode-ai/schema/config/mcp"
import { OauthCallbackPage } from "../oauth/page.js"
import type { Integration } from "../integration.js"
import { ErrorSummary } from "../util/error-summary.js"
/** Observe OAuth failures before the SDK handles them by invalidating credentials or redirecting. */
export const loggedFetch = (fields: { readonly server: string; readonly directory?: string }) =>
Effect.gen(function* () {
const run = Effect.runPromiseWith(yield* Effect.context())
const request: FetchLike = (url, init) => {
const grant = init?.body instanceof URLSearchParams ? init.body.get("grant_type") : undefined
const operation = grant === "refresh_token" ? "refresh" : grant === "authorization_code" ? "exchange" : undefined
const started = Date.now()
return run(
Effect.gen(function* () {
if (operation) yield* Effect.logInfo("mcp oauth request started")
const response = yield* Effect.tryPromise({ try: () => fetch(url, init), catch: (error) => error })
const result = { status: response.status, durationMs: Date.now() - started }
if (operation && !response.ok) {
// Only retain the SDK's standard error code. Descriptions and raw bodies can echo credentials.
const error = yield* Effect.tryPromise(async () => parseErrorResponse(await response.clone().text())).pipe(
Effect.map((error) => error.errorCode),
Effect.orElseSucceed(() => "unreadable_response"),
)
yield* Effect.logWarning("mcp oauth request rejected", { ...result, error })
}
if (operation && response.ok) {
yield* Effect.logInfo("mcp oauth request succeeded", result)
}
if (!operation && (response.status === 401 || response.status === 403)) {
yield* Effect.logWarning("mcp http authentication rejected", result)
}
return response
}).pipe(
Effect.onError((cause) => {
if (init?.signal?.aborted) return Effect.logDebug("mcp http request aborted")
return Effect.logWarning("mcp http request failed", {
errors: ErrorSummary.from(Cause.squash(cause)),
durationMs: Date.now() - started,
})
}),
Effect.annotateLogs({
...fields,
requestID: crypto.randomUUID(),
origin: new URL(url).origin,
method: init?.method ?? "GET",
...(operation ? { operation } : {}),
}),
),
)
}
return request
})
/** Persists the OAuth artifacts for one MCP server session: DCR client info, PKCE verifier, and tokens. */
export interface Store {
@@ -196,12 +145,6 @@ export const authorize = (input: {
readonly methodID: Integration.MethodID
}) =>
Effect.gen(function* () {
const fields = { server: input.name, methodID: input.methodID, oauthAttemptID: crypto.randomUUID() }
const context = yield* Effect.context()
const run = Effect.runPromiseWith(context)
const runFork = Effect.runForkWith(context)
const fetchFn = yield* loggedFetch({ server: input.name }).pipe(Effect.annotateLogs(fields))
yield* Effect.logInfo("mcp oauth authorization started", fields)
const oauth = input.config.oauth || undefined
const store = memoryStore()
const code = yield* Deferred.make<string, Error>()
@@ -217,20 +160,19 @@ export const authorize = (input: {
response.writeHead(404).end("Not found")
return
}
const fail = (reason: string, failure: string) => {
runFork(Effect.logWarning("mcp oauth callback rejected", { ...fields, reason: failure }))
const fail = (reason: string) => {
Effect.runFork(Deferred.fail(code, new Error(reason)))
response
.writeHead(400, { "Content-Type": "text/html" })
.end(OauthCallbackPage.error(reason, { provider: input.name }))
}
const error = url.searchParams.get("error_description") ?? url.searchParams.get("error")
if (error) return fail(error, "authorization_error")
if (error) return fail(error)
// Reject a redirect whose state does not match what we issued: this is the CSRF defense the
// state parameter exists for, so an attacker can't inject their own authorization code.
if (url.searchParams.get("state") !== state) return fail("OAuth state mismatch", "state_mismatch")
if (url.searchParams.get("state") !== state) return fail("OAuth state mismatch")
const value = url.searchParams.get("code")
if (!value) return fail("Missing authorization code", "missing_code")
if (!value) return fail("Missing authorization code")
Effect.runFork(Deferred.succeed(code, value))
response.writeHead(200, { "Content-Type": "text/html" }).end(OauthCallbackPage.success({ provider: input.name }))
})
@@ -260,7 +202,6 @@ export const authorize = (input: {
client: oauth?.client_id ? { id: oauth.client_id, secret: oauth.client_secret } : undefined,
onRedirect: (url) => {
authorizationUrl = url
return run(Effect.logInfo("mcp oauth awaiting authorization", fields))
},
store,
})
@@ -269,16 +210,11 @@ export const authorize = (input: {
const tokens = yield* Effect.promise(() => store.tokens())
if (!tokens) return yield* Effect.fail(new Error(`MCP server "${input.name}" did not return OAuth tokens`))
const client = yield* Effect.promise(() => store.clientInformation())
yield* Effect.logInfo("mcp oauth authorization completed", {
...fields,
hasRefreshToken: Boolean(tokens.refresh_token),
expiresIn: tokens.expires_in,
})
return toCredential({ methodID: input.methodID, serverUrl: input.config.url, tokens, client })
})
yield* Effect.tryPromise({
try: () => auth(oauthProvider, { serverUrl: input.config.url, scope: oauth?.scope, fetchFn }),
try: () => auth(oauthProvider, { serverUrl: input.config.url, scope: oauth?.scope }),
catch: (error) => (error instanceof Error ? error : new Error(String(error))),
})
@@ -293,28 +229,11 @@ export const authorize = (input: {
Effect.flatMap((value) =>
Effect.tryPromise({
try: () =>
auth(oauthProvider, {
serverUrl: input.config.url,
authorizationCode: value,
scope: oauth?.scope,
fetchFn,
}),
auth(oauthProvider, { serverUrl: input.config.url, authorizationCode: value, scope: oauth?.scope }),
catch: (error) => (error instanceof Error ? error : new Error(String(error))),
}),
),
Effect.flatMap(() => finalize),
Effect.onError((cause) =>
Effect.logWarning("mcp oauth authorization failed", { errors: ErrorSummary.from(Cause.squash(cause)) }),
),
Effect.annotateLogs(fields),
),
}
}).pipe(
Effect.onError((cause) =>
Effect.logWarning("mcp oauth authorization setup failed", {
server: input.name,
methodID: input.methodID,
errors: ErrorSummary.from(Cause.squash(cause)),
}),
),
)
})
+2 -3
View File
@@ -87,7 +87,7 @@ import { ProviderPlugins } from "./provider.js"
import { WebSearchPlugins } from "./websearch/index.js"
import { SkillPlugin } from "./skill.js"
import { VcsHgPlugin } from "./vcs/hg.js"
import { OptimizePlugin } from "./optimize.js"
import { SystemPromptPlugin } from "./system-prompt.js"
import { VariantPlugin } from "./variant.js"
import { VcsGitPlugin } from "./vcs/git.js"
import { WarmingPlugin } from "./warming.js"
@@ -201,12 +201,11 @@ const pre = [
CommandPlugin.Plugin,
SkillPlugin.Plugin,
VcsHgPlugin.Plugin,
...SystemPromptPlugin.Plugins,
ModelsDevPlugin,
...ProviderPlugins,
...WebSearchPlugins,
PatchTool.Plugin,
// Render model prompts after the patch plugin selects the available editing tools.
...OptimizePlugin.Plugins,
EditTool.Plugin,
GlobTool.Plugin,
GrepTool.Plugin,
-74
View File
@@ -1,74 +0,0 @@
export * as OptimizePlugin from "./optimize.js"
import { define } from "@opencode-ai/plugin/effect/plugin"
import type { SessionHooks } from "@opencode-ai/plugin/effect/session"
import { Model } from "@opencode-ai/schema/model"
import { Effect } from "effect"
import { SessionSystemPrompt } from "../session/system-prompt.js"
import PROMPT_GPT from "./system-prompt/gpt.txt"
import PROMPT_ASTRA from "./system-prompt/gpt-astra.txt"
import PROMPT_KIMI from "./system-prompt/kimi.txt"
import PROMPT_META from "./system-prompt/meta.txt"
import PROMPT_TRINITY from "./system-prompt/trinity.txt"
export const OpenAIPlugin = make("opencode.prompt.openai", (model) => {
const id = model.id.toLowerCase()
if (!id.includes("gpt")) return undefined
return id.includes("gpt-6") ? PROMPT_ASTRA : PROMPT_GPT
})
export const OpenAIToolsPlugin = make("opencode.optimize.openai.tools", (model, tools) => {
const ids = [model.id, model.modelID, model.family].join(" ").toLowerCase()
if (!ids.includes("gpt")) return undefined
delete tools.grep
delete tools.glob
return undefined
})
export const AnthropicToolsPlugin = make("opencode.optimize.anthropic.tools", (model, tools) => {
const ids = [model.id, model.modelID, model.family].join(" ").toLowerCase()
if (!ids.includes("claude")) return undefined
delete tools.grep
delete tools.glob
return undefined
})
export const KimiPlugin = make("opencode.prompt.kimi", (model) =>
model.id.toLowerCase().includes("kimi") ? PROMPT_KIMI : undefined,
)
export const ArceePlugin = make("opencode.prompt.arcee", (model) =>
model.id.toLowerCase().includes("trinity") ? PROMPT_TRINITY : undefined,
)
export const MetaPlugin = make("opencode.prompt.meta", (model) => {
if (!model.id.toLowerCase().includes("muse")) return undefined
return PROMPT_META.replaceAll("{{MODEL_NAME}}", model.name)
})
export const Plugins = [OpenAIPlugin, KimiPlugin, ArceePlugin, MetaPlugin] as const
function make(
id: string,
optimize: (model: Model.Info, tools: SessionHooks["context"]["tools"]) => string | undefined,
) {
return define({
id,
effect: Effect.fn(`OptimizePlugin.${id}`)(function* (ctx) {
yield* ctx.session.hook("context", (event) =>
Effect.gen(function* () {
const model =
(yield* ctx.catalog.model.list()).data.find(
(model) => model.providerID === event.model.providerID && model.id === event.model.id,
) ?? Model.Info.default(event.model.providerID, event.model.id)
// Curate tools before rendering their guidance, including for agents with a custom system prompt.
const template = optimize(model, event.tools)
if (!template) return
if ((yield* ctx.agent.get({ agentID: event.agent })).data.system) return
const system = event.system[0]
if (!system) return
event.system[0] = { ...system, text: SessionSystemPrompt.render(template, Object.keys(event.tools)) }
}).pipe(Effect.catch(() => Effect.void)),
)
}),
})
}
+74
View File
@@ -0,0 +1,74 @@
export * as SystemPromptPlugin from "./system-prompt.js"
import { SystemPart } from "@opencode-ai/ai"
import { define } from "@opencode-ai/plugin/effect/plugin"
import { Model } from "@opencode-ai/schema/model"
import { Effect } from "effect"
import { SessionSystemPrompt } from "../session/system-prompt.js"
import PROMPT_GPT from "./system-prompt/gpt.txt"
import PROMPT_ASTRA from "./system-prompt/gpt-astra.txt"
import PROMPT_KIMI from "./system-prompt/kimi.txt"
import PROMPT_META from "./system-prompt/meta.txt"
import PROMPT_TRINITY from "./system-prompt/trinity.txt"
export const OpenAIPlugin = make(
"openai",
(model) => {
if (!model.id.toLowerCase().includes("gpt")) return
if (model.id.toLowerCase().includes("gpt-6")) return PROMPT_ASTRA
return PROMPT_GPT
},
{ operation: "replace" },
)
export const KimiPlugin = make("kimi", (model) => (model.id.toLowerCase().includes("kimi") ? PROMPT_KIMI : undefined), {
operation: "replace",
})
export const ArceePlugin = make(
"arcee",
(model) => (model.id.toLowerCase().includes("trinity") ? PROMPT_TRINITY : undefined),
{ operation: "replace" },
)
export const MetaPlugin = make(
"meta",
(model) => {
if (!model.id.toLowerCase().includes("muse")) return
return PROMPT_META.replaceAll("{{MODEL_NAME}}", model.name)
},
{ operation: "replace" },
)
export const Plugins = [OpenAIPlugin, KimiPlugin, ArceePlugin, MetaPlugin] as const
function make(
id: string,
getPrompt: (model: Model.Info) => string | undefined,
options: { operation: "replace" | "append" },
) {
return define({
id: `opencode.prompt.${id}`,
effect: Effect.fn(`SystemPromptPlugin.${id}`)(function* (ctx) {
yield* ctx.session.hook("context", (event) =>
Effect.gen(function* () {
if ((yield* ctx.agent.get({ agentID: event.agent })).data.system) return
const system = event.system[0]
if (!system) return
const model = (yield* ctx.catalog.model.list()).data.find(
(model) => model.providerID === event.model.providerID && model.id === event.model.id,
)
const template = getPrompt(model ?? Model.Info.default(event.model.providerID, event.model.id))
if (!template) return
const prompt = SessionSystemPrompt.render(template, Object.keys(event.tools))
if (options.operation === "append") {
event.system.splice(1, 0, SystemPart.make(prompt))
return
}
event.system[0] = { ...system, text: prompt }
}).pipe(Effect.catch(() => Effect.void)),
)
}),
})
}
+4 -1
View File
@@ -93,6 +93,7 @@ type CompactInput = Parameters<Session.Handle["compact"]>[0] & { sessionID: Sess
type ForkInput = {
sessionID: SessionSchema.ID
boundary: SessionSchema.ForkRequestBoundary
parentID?: SessionSchema.ID
}
export {
@@ -311,7 +312,9 @@ const layer = Layer.effect(
messageID: input.boundary.messageID,
})
if (!boundary) return yield* new ForkEmptyError({ sessionID: input.sessionID })
const sessionID = SessionSchema.ID.create()
const sessionID = input.parentID
? (yield* result.create({ parentID: input.parentID })).id
: SessionSchema.ID.create()
const inherited = yield* db
.transaction(() =>
Effect.all({
+7 -14
View File
@@ -28,17 +28,9 @@ export interface Interface {
* Interrupt active work owned by this process. Idle interruption is a no-op. Resolves once
* the interruption is accepted; cleanup settles asynchronously in the execution fiber.
* Returns whether an active execution was interrupted. Compose with `awaitIdle` when
* settlement matters. `awaitSettlement` waits only for the interrupted execution,
* rather than fresh work admitted during its cleanup.
* settlement matters.
*/
readonly interrupt: (
sessionID: SessionSchema.ID,
options?: {
readonly continue?: boolean
readonly reason?: "user" | "inactivity"
readonly awaitSettlement?: boolean
},
) => Effect.Effect<boolean>
readonly interrupt: (sessionID: SessionSchema.ID, options?: { readonly continue?: boolean }) => Effect.Effect<boolean>
/** Resolves once this process owns no active execution for the Session. Returns immediately when idle and never starts work. */
readonly awaitIdle: (sessionID: SessionSchema.ID) => Effect.Effect<void>
}
@@ -46,7 +38,7 @@ export interface Interface {
/** Routes execution from a Session ID to its selected instance's runner. */
export class Service extends Context.Service<Service, Interface>()("@opencode/SessionExecution") {}
type InterruptReason = "user" | "shutdown" | "inactivity"
type InterruptReason = "user" | "shutdown"
export function terminal(exit: Exit.Exit<void, SessionRunner.RunError>, reason?: InterruptReason) {
if (Exit.isSuccess(exit)) return { type: "succeeded" as const }
@@ -128,8 +120,9 @@ export const layer = Layer.effect(
return
}
if (outcome.type === "interrupted") {
// Deliberate stops release the claim; shutdown keeps it for restart continuity.
if (outcome.reason !== "shutdown") yield* jobs.cancel(sessionID)
// A user cancel releases the claim: the turn must not resurrect at the next
// boot. Shutdown interruption keeps it for restart continuity.
if (outcome.reason === "user") yield* jobs.cancel(sessionID)
yield* bus.publish(
SessionEvent.Execution.Interrupted,
{ sessionID, reason: outcome.reason },
@@ -154,7 +147,7 @@ export const layer = Layer.effect(
isActive: coordinator.isActive,
interrupt: (sessionID, options) =>
Effect.gen(function* () {
const interrupted = yield* coordinator.interrupt(sessionID, options?.reason ?? "user", options)
const interrupted = yield* coordinator.interrupt(sessionID, "user")
if (!options?.continue) return interrupted
// Resume steering input and between-turn control work from the interrupted
// intent. Queued next-turn prompts stay parked: a steer-scoped drain never
+20 -12
View File
@@ -1,6 +1,6 @@
export * as SessionProjector from "./projector.js"
import { and, asc, desc, eq, gt, gte, inArray, isNull, lt, lte, or, sql } from "drizzle-orm"
import { and, asc, desc, eq, gt, gte, inArray, isNotNull, isNull, lt, lte, or, sql } from "drizzle-orm"
import { DateTime, Effect, Layer, Schema, Stream } from "effect"
import path from "path"
import { Database } from "../database/database.js"
@@ -144,22 +144,25 @@ const projectFork = Effect.fn("SessionProjector.projectFork")(function* (
.pipe(Effect.orDie)
const copiedSeq = copied?.seq
const inherited = {
fork_session_id: event.data.parentID,
fork_boundary: event.data.boundary,
project_id: parent.project_id,
workspace_id: parent.workspace_id,
directory: parent.directory,
path: parent.path,
title: forkTitle(parent.title ?? undefined),
agent: parent.agent,
model: parent.model,
metadata: parent.metadata,
}
const stored = yield* db
.insert(SessionTable)
.values({
id: event.data.sessionID,
parent_id: null,
fork_session_id: event.data.parentID,
fork_boundary: event.data.boundary,
project_id: parent.project_id,
workspace_id: parent.workspace_id,
...inherited,
slug: Slug.create(),
directory: parent.directory,
path: parent.path,
title: forkTitle(parent.title ?? undefined),
agent: parent.agent,
model: parent.model,
metadata: parent.metadata,
version: parent.version,
cost: 0,
tokens_input: 0,
@@ -170,7 +173,12 @@ const projectFork = Effect.fn("SessionProjector.projectFork")(function* (
time_created: event.created,
time_updated: event.created,
})
.onConflictDoNothing()
// Created records optional ownership; Forked supplies the source's history and defaults.
.onConflictDoUpdate({
target: SessionTable.id,
set: { ...inherited, time_updated: event.created },
setWhere: and(isNotNull(SessionTable.parent_id), isNull(SessionTable.fork_session_id)),
})
.returning({ sessionID: SessionTable.id })
.get()
.pipe(Effect.orDie)
+3 -25
View File
@@ -17,14 +17,9 @@ export interface Coordinator<Key, E, Reason = never> {
* Stops the active execution and clears its doorbell. No-op when idle. Resolves once the
* interruption is accepted, not when cleanup settles: the execution fiber finishes its
* finalizers and settled hook on its own time. Returns whether an active execution was
* interrupted. `awaitSettlement` waits for this execution's cleanup and settled hook,
* without following fresh work admitted during cleanup. `awaitIdle` follows successors too.
* interrupted. Compose with `awaitIdle` for settlement.
*/
readonly interrupt: (
key: Key,
reason?: Reason,
options?: { readonly awaitSettlement?: boolean },
) => Effect.Effect<boolean>
readonly interrupt: (key: Key, reason?: Reason) => Effect.Effect<boolean>
/** Resolves once no execution is active for the key. Returns immediately when already idle and never starts work. */
readonly awaitIdle: (key: Key) => Effect.Effect<void>
}
@@ -175,22 +170,5 @@ export const make = <Key, E, Reason = never>(options: {
return Deferred.await(execution.done).pipe(Effect.ignoreCause, Effect.andThen(awaitIdle(key)))
})
return {
active: Effect.sync(() => new Set(executions.keys())),
isActive,
run,
wake,
interrupt: (key, reason, options) =>
Effect.suspend(() => {
const execution = executions.get(key)
return interrupt(key, reason).pipe(
Effect.tap(() =>
options?.awaitSettlement && execution
? Deferred.await(execution.done).pipe(Effect.ignoreCause)
: Effect.void,
),
)
}),
awaitIdle,
}
return { active: Effect.sync(() => new Set(executions.keys())), isActive, run, wake, interrupt, awaitIdle }
})
+63 -19
View File
@@ -5,6 +5,7 @@ import type { Context } from "@opencode-ai/plugin/effect/plugin"
import { Effect, Schema } from "effect"
import { Agent } from "../../agent.js"
import { Config } from "../../config.js"
import { ConfigEntryObserver } from "../../config/plugin/entry-observer.js"
import { Job } from "../../job.js"
import { Permission } from "../../permission.js"
import { Session } from "../../session.js"
@@ -38,6 +39,13 @@ export const Input = Schema.Struct({
}),
})
const ForkInput = Schema.Struct({
...Input.fields,
fork: Schema.optionalKey(Schema.Boolean).annotate({
description: "Give the subagent your conversation history before this response.",
}),
})
export const Output = Schema.Struct({
sessionID: SessionSchema.ID,
status: Schema.Literals(["completed", "running"]),
@@ -61,17 +69,26 @@ export const Plugin = {
const config = yield* Config.Service
const permission = yield* Permission.Service
const subagents = yield* SubagentJob.make
const loaded = yield* ConfigEntryObserver.observe(config, ctx.event, ctx.tool.reload())
yield* ctx.tool
.transform((editor) =>
.transform((editor) => {
const fork = Config.latest(loaded.entries, "experimental")?.subagent_fork === true
editor.add({
name,
options: { codemode: false },
description,
input: Input,
description: fork
? description.replace(
"New child sessions start with fresh context, so include all relevant context and instructions when you don't pass a sessionID.",
"New child sessions start with fresh context by default, so include the context needed for the task.",
)
: description,
input: fork ? ForkInput : Input,
output: Output,
execute: (input, context) =>
execute: (input: typeof ForkInput.Type, context) =>
Effect.gen(function* () {
if (fork && input.fork !== undefined && input.sessionID !== undefined)
return yield* new ToolFailure({ message: "Cannot use fork with sessionID. Omit one of them." })
const parent = yield* sessions
.get(context.sessionID)
.pipe(
@@ -150,18 +167,40 @@ export const Plugin = {
const model = agent.model ?? parent.model
const child =
existing ??
(yield* sessions
.create({
parentID: context.sessionID,
title: input.description,
agent: Agent.ID.make(input.agent),
model,
})
.pipe(
Effect.mapError(
(error) => new ToolFailure({ message: `Parent session not found: ${context.sessionID}`, error }),
),
))
(yield* (
fork && input.fork
? sessions.fork({
sessionID: context.sessionID,
parentID: context.sessionID,
boundary: { type: "before", messageID: context.messageID },
})
: sessions.create({
parentID: context.sessionID,
title: input.description,
agent: Agent.ID.make(input.agent),
model,
})
).pipe(
Effect.mapError(
(error) =>
new ToolFailure({
message:
fork && input.fork
? `Failed to create subagent: ${error.message}`
: `Parent session not found: ${context.sessionID}`,
error,
}),
),
))
if (fork && input.fork)
yield* sessions.rename({ sessionID: child.id, title: input.description }).pipe(
Effect.andThen(sessions.switchAgent({ sessionID: child.id, agent: agent.id })),
Effect.andThen(model ? sessions.switchModel({ sessionID: child.id, model }) : Effect.void),
Effect.mapError(
(error) => new ToolFailure({ message: `Failed to configure subagent: ${child.id}`, error }),
),
)
const background = input.background === true
yield* context.progress({ sessionID: child.id, status: "running" })
@@ -173,7 +212,12 @@ export const Plugin = {
sessionID: child.id,
text:
existing === undefined
? ["You are a subagent spawned by another session.", input.prompt].join("\n")
? [
fork && input.fork
? "You are a forked subagent. Use the inherited history as context and perform only the task below."
: "You are a subagent spawned by another session.",
input.prompt,
].join("\n")
: input.prompt,
...(background && existing === undefined ? { resume: false } : {}),
})
@@ -230,8 +274,8 @@ export const Plugin = {
metadata: { sessionID: output.sessionID, status: output.status },
})),
),
}),
)
})
})
.pipe(Effect.orDie)
yield* ctx.session.hook("context", (event) =>
-31
View File
@@ -1,31 +0,0 @@
export * as ErrorSummary from "./error-summary.js"
import { Option, Schema } from "effect"
const decode = Schema.decodeUnknownOption(
Schema.Struct({
name: Schema.optional(Schema.String),
_tag: Schema.optional(Schema.String),
code: Schema.optional(Schema.Union([Schema.String, Schema.Number])),
errno: Schema.optional(Schema.Number),
cause: Schema.optional(Schema.Unknown),
}),
)
/** Error messages, stacks and SQL parameters may contain credentials. Retain only diagnostic classifications. */
export function from(error: unknown) {
const errors: { type: string; code?: string | number; errno?: number }[] = []
const seen = new Set<unknown>()
while (error && !seen.has(error) && errors.length < 8) {
seen.add(error)
const result = decode(error)
if (Option.isNone(result)) break
errors.push({
type: result.value._tag ?? (error instanceof Error ? error.name : result.value.name) ?? "unknown",
code: result.value.code,
errno: result.value.errno,
})
error = error instanceof Error ? error.cause : result.value.cause
}
return errors
}
@@ -409,12 +409,14 @@ describe("ConfigNormalize", () => {
experimental: {
portable_shell_scanner: true,
subagent_depth: 0,
subagent_fork: true,
policies: [{ action: "provider.use", resource: "custom", effect: "allow" }],
},
}).encoded.experimental,
).toEqual({
portable_shell_scanner: true,
subagent_depth: 0,
subagent_fork: true,
policies: [
{ action: "provider.use", resource: "*", effect: "deny" },
{ action: "provider.use", resource: "anthropic", effect: "allow" },
@@ -1,221 +0,0 @@
import { describe, expect } from "bun:test"
import { Context, Deferred, Duration, Effect, Fiber, Layer, LayerMap, RcMap, Schema } from "effect"
import { TestClock } from "effect/testing"
import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
import { LayerNode } from "@opencode-ai/util/effect/layer-node"
import { makeGlobalNode } from "@opencode-ai/util/effect/app-node"
import { Bus } from "@opencode-ai/core/bus"
import { Database } from "@opencode-ai/core/database/database"
import { Form } from "@opencode-ai/core/form"
import { Location } from "@opencode-ai/core/location"
import { LocationActivity } from "@opencode-ai/core/location-activity"
import { LocationServiceMap, type LocationServices } from "@opencode-ai/core/location-services"
import { Project } from "@opencode-ai/core/project"
import { ProjectTable } from "@opencode-ai/core/project/sql"
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 { SessionRunner } from "@opencode-ai/core/session/runner/index"
import { SessionTable } from "@opencode-ai/core/session/sql"
import { SessionStore } from "@opencode-ai/core/session/store"
import { Workspace } from "@opencode-ai/core/workspace"
import { testEffect } from "./lib/effect"
// Keep real execution ownership, location caching, forms, and eviction. The fixture
// runner waits on a form instead of making a model request before asking a question.
const locations = Layer.effect(
LocationServiceMap.Service,
Effect.gen(function* () {
const bus = yield* Bus.Service
const map = yield* LayerMap.make(
(ref: Location.Ref) =>
// The fixture only exercises these three Location services.
// oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion
Layer.merge(
Layer.succeed(
Location.Service,
Location.Service.of({
directory: ref.directory,
workspaceID: ref.workspaceID,
project: { id: Project.ID.global, directory: ref.directory, canonical: ref.directory },
}),
),
Layer.effect(
SessionRunner.Service,
Effect.gen(function* () {
const forms = yield* Form.Service
return SessionRunner.Service.of({
drain: ({ sessionID }) =>
forms
.ask({
sessionID,
title: "Questions",
fields: [{ key: "runtime", type: "string" }],
})
.pipe(
Effect.orDie,
Effect.as(SessionRunner.DrainResult.Complete()),
Effect.onInterrupt(() => Effect.sleep("5 minutes")),
),
})
}),
),
).pipe(
Layer.provideMerge(Form.layer),
Layer.provide(Layer.succeed(Bus.Service, bus)),
Layer.fresh,
) as unknown as Layer.Layer<LocationServices>,
{ idleTimeToLive: Duration.infinity },
)
return {
...map,
get: (ref: Location.Ref) => map.get(LocationServiceMap.canonical(ref)),
contextEffect: (ref: Location.Ref) => map.contextEffect(LocationServiceMap.canonical(ref)),
contextEffectOption: (ref: Location.Ref) => map.contextEffectOption(LocationServiceMap.canonical(ref)),
invalidate: (ref: Location.Ref) => map.invalidate(LocationServiceMap.canonical(ref)),
}
}),
)
const it = testEffect(
AppNodeBuilder.build(
LayerNode.group([
Database.node,
Bus.node,
SessionStore.node,
LocationServiceMap.node,
SessionExecution.node,
LocationActivity.node,
]),
[
LocationServiceMap.node.replace(
makeGlobalNode({
service: LocationServiceMap.Service,
layer: locations,
deps: [Bus.node],
}),
),
],
),
)
describe("LocationActivity eviction", () => {
for (const [count, admission] of [
[1, "none"],
[2, "none"],
[1, "other"],
[1, "same"],
] as const) {
const newWork = admission !== "none"
it.effect(
`interrupts ${count} waiting executions before eviction (${admission} session admitted during cleanup)`,
() =>
Effect.gen(function* () {
const db = (yield* Database.Service).db
const bus = yield* Bus.Service
const map = yield* LocationServiceMap.Service
const execution = yield* SessionExecution.Service
const store = yield* SessionStore.Service
const sessionIDs = Array.from({ length: count }, (_, index) =>
Session.ID.make(`ses_waiting_question_${index}`),
)
const newcomer = admission === "same" ? sessionIDs[0] : Session.ID.make("ses_new_question")
const ref = LocationServiceMap.canonical({ directory: AbsolutePath.make("/project") })
const idle = Location.Ref.make({ directory: ref.directory, workspaceID: Workspace.ID.make("wrk_idle") })
yield* db
.insert(ProjectTable)
.values({ id: Project.ID.global, worktree: ref.directory, sandboxes: [] })
.run()
.pipe(Effect.orDie)
yield* db
.insert(SessionTable)
.values(
Array.from(new Set([...sessionIDs, newcomer]), (sessionID) => ({
id: sessionID,
project_id: Project.ID.global,
slug: "question",
directory: ref.directory,
title: "Waiting question",
version: "test",
})),
)
.run()
.pipe(Effect.orDie)
const created = yield* Deferred.make<void>()
const newCreated = yield* Deferred.make<void>()
const pending: Form.Info[] = []
const interrupted: SessionEvent.Execution.Interrupted["data"][] = []
const unsubscribe = yield* bus.listen((event) =>
Effect.gen(function* () {
if (event.type === SessionEvent.Execution.Interrupted.type) {
interrupted.push(Schema.decodeUnknownSync(SessionEvent.Execution.Interrupted.data)(event.data))
}
if (event.type !== Form.Event.Created.type) return
pending.push(Schema.decodeUnknownSync(Form.Event.Created.data)(event.data).form)
if (pending.length === count) yield* Deferred.succeed(created, undefined)
if (pending.length > count) yield* Deferred.succeed(newCreated, undefined)
}),
)
yield* Effect.addFinalizer(() => unsubscribe)
const running = yield* Effect.forEach(sessionIDs, (sessionID) =>
execution.resume(sessionID).pipe(Effect.exit, Effect.forkScoped),
)
yield* Effect.addFinalizer(() =>
Effect.forEach([...sessionIDs, newcomer], (sessionID) => execution.interrupt(sessionID)).pipe(
Effect.andThen(TestClock.adjust("5 minutes")),
),
)
yield* Deferred.await(created)
const context = yield* map.contextEffect(ref).pipe(Effect.scoped)
const forms = Context.get(context, Form.Service)
expect((yield* store.listSuspended()).toSorted()).toEqual(sessionIDs.toSorted())
yield* Location.Service.pipe(Effect.provide(map.get(idle)), Effect.scoped)
// Human input produces no durable activity while the question is pending.
yield* TestClock.adjust("1 minute")
yield* TestClock.adjust("62 minutes")
// Interruption has cancelled each question, but slow cleanup still owns the graph.
expect(Array.from(yield* execution.active).toSorted()).toEqual(sessionIDs.toSorted())
expect(Array.from(yield* RcMap.keys(map.rcMap))).toEqual([ref])
expect(yield* forms.list()).toEqual([])
for (const form of pending) expect(yield* forms.state(form.id)).toEqual({ status: "cancelled" })
if (newWork) {
yield* execution.wake(newcomer)
if (admission === "other") yield* Deferred.await(newCreated)
}
yield* TestClock.adjust("5 minutes")
if (newWork) yield* Deferred.await(newCreated)
const results = yield* Effect.forEach(running, Fiber.join)
expect(results.every((exit) => exit._tag === "Failure")).toBe(true)
expect(Array.from(yield* execution.active)).toEqual(newWork ? [newcomer] : [])
expect(yield* store.listSuspended()).toEqual(newWork ? [newcomer] : [])
expect(interrupted.toSorted((a, b) => a.sessionID.localeCompare(b.sessionID))).toEqual(
sessionIDs.map((sessionID) => ({ sessionID, reason: "inactivity" })),
)
expect(Array.from(yield* RcMap.keys(map.rcMap))).toEqual(newWork ? [ref] : [])
if (newWork) {
expect(yield* forms.list({ sessionID: newcomer })).toEqual([pending[count]])
if (admission === "same") {
const later = LocationServiceMap.canonical({ directory: AbsolutePath.make("/later") })
yield* Location.Service.pipe(Effect.provide(map.get(later)), Effect.scoped)
yield* TestClock.adjust("30 minutes")
// Keep fresh work active while a different graph reaches its own deadline.
yield* bus.publish(SessionEvent.Execution.Started, { sessionID: newcomer }, { location: ref })
yield* TestClock.adjust("32 minutes")
expect(Array.from(yield* execution.active)).toEqual([newcomer])
expect(Array.from(yield* RcMap.keys(map.rcMap))).toEqual([ref])
}
yield* execution.interrupt(newcomer)
yield* TestClock.adjust("5 minutes")
yield* execution.awaitIdle(newcomer)
yield* TestClock.adjust("62 minutes")
expect(yield* store.listSuspended()).toEqual([])
expect(Array.from(yield* RcMap.keys(map.rcMap))).toEqual([])
}
}),
)
}
})
@@ -5,7 +5,7 @@ import { Catalog } from "@opencode-ai/core/catalog"
import { Plugin } from "@opencode-ai/core/plugin"
import { PluginHooks } from "@opencode-ai/core/plugin/hooks"
import { PluginHost } from "@opencode-ai/core/plugin/host"
import { OptimizePlugin } from "@opencode-ai/core/plugin/optimize"
import { SystemPromptPlugin } from "@opencode-ai/core/plugin/system-prompt"
import { Session } from "@opencode-ai/core/session"
import { SessionSystemPrompt } from "@opencode-ai/core/session/system-prompt"
import type { SessionHooks } from "@opencode-ai/plugin/effect/session"
@@ -26,22 +26,17 @@ const makeHost = Effect.gen(function* () {
})
const context = (id: string, system = fallback): SessionHooks["context"] => ({
sessionID: Session.ID.make("ses_model_optimization"),
sessionID: Session.ID.make("ses_system_prompt"),
agent: Agent.ID.make("build"),
model: Model.Ref.make({ providerID: Provider.ID.make("test"), id: Model.ID.make(id) }),
system: [SystemPart.make(system)],
messages: [],
tools: Object.fromEntries(
["shell", "read", "grep", "glob", "edit", "write", "patch"].map((name) => [
name,
{ description: name, input: { type: "object" } },
]),
),
tools: {},
generation: {},
providerOptions: {},
})
describe("OptimizePlugin", () => {
describe("SystemPromptPlugin", () => {
test("uses current vocabulary in the Meta prompt", () => {
expect(PROMPT_META).toContain("`webfetch` tool")
expect(PROMPT_META).toContain("`subagent` tool")
@@ -56,8 +51,8 @@ describe("OptimizePlugin", () => {
)
})
test("enables prompt plugins without model-specific tool optimization", () => {
expect(OptimizePlugin.Plugins.map((plugin) => plugin.id)).toEqual([
test("uses granular IDs with a common prefix", () => {
expect(SystemPromptPlugin.Plugins.map((plugin) => plugin.id)).toEqual([
"opencode.prompt.openai",
"opencode.prompt.kimi",
"opencode.prompt.arcee",
@@ -77,7 +72,7 @@ describe("OptimizePlugin", () => {
model.name = "Muse Spark"
})
})
yield* Effect.forEach(OptimizePlugin.Plugins, (plugin) => plugin.effect(pluginHost), {
yield* Effect.forEach(SystemPromptPlugin.Plugins, (plugin) => plugin.effect(pluginHost), {
discard: true,
})
const cases = [
@@ -111,7 +106,7 @@ describe("OptimizePlugin", () => {
}),
)
it.effect("renders the OpenAI prompt without changing tools or project instructions", () =>
it.effect("renders the OpenAI prompt and preserves project instructions", () =>
Effect.gen(function* () {
const catalog = yield* Catalog.Service
const hooks = yield* PluginHooks.Service
@@ -119,7 +114,7 @@ describe("OptimizePlugin", () => {
yield* catalog.transform((editor) =>
editor.model.update(Provider.ID.make("test"), Model.ID.make("gpt-5"), () => {}),
)
yield* OptimizePlugin.OpenAIPlugin.effect(pluginHost)
yield* SystemPromptPlugin.OpenAIPlugin.effect(pluginHost)
const event = context("gpt-5")
event.system.push(SystemPart.make("Project instructions"))
event.tools.shell = { description: "Run a command", input: { type: "object" } }
@@ -133,73 +128,6 @@ describe("OptimizePlugin", () => {
expect(event.system[0]?.text).toStartWith("You are an AI agent powered by OpenCode")
expect(event.system[0]?.text).toContain("Prefer dedicated tools over shell commands")
expect(event.system[0]?.text).not.toContain("${OPENCODE_TOOL_GUIDANCE}")
expect(event.system[0]?.text).toContain("Use the write tool")
expect(event.system[0]?.text).toContain("Use the edit tool")
expect(Object.keys(event.tools).sort()).toEqual(["edit", "glob", "grep", "patch", "read", "shell", "write"])
}),
)
it.effect("curates search tools across providers without changing editing tools", () =>
Effect.gen(function* () {
const hooks = yield* PluginHooks.Service
const pluginHost = yield* makeHost
yield* OptimizePlugin.OpenAIToolsPlugin.effect(pluginHost)
yield* OptimizePlugin.AnthropicToolsPlugin.effect(pluginHost)
const cases = [
["openai", "gpt-5", ["edit", "patch", "read", "shell", "write"]],
["openrouter", "openai/gpt-6-astra", ["edit", "patch", "read", "shell", "write"]],
["azure", "GPT-4.1", ["edit", "patch", "read", "shell", "write"]],
["groq", "openai/gpt-oss-120b", ["edit", "patch", "read", "shell", "write"]],
["anthropic", "claude-opus-4-8", ["edit", "patch", "read", "shell", "write"]],
["amazon-bedrock", "us.anthropic.Claude-sonnet-4-6", ["edit", "patch", "read", "shell", "write"]],
["github-copilot", "claude-sonnet-4.6", ["edit", "patch", "read", "shell", "write"]],
["google", "gemini-2.5-pro", ["edit", "glob", "grep", "patch", "read", "shell", "write"]],
["moonshotai", "kimi-k2", ["edit", "glob", "grep", "patch", "read", "shell", "write"]],
["openai", "o3", ["edit", "glob", "grep", "patch", "read", "shell", "write"]],
["anthropic", "other-model", ["edit", "glob", "grep", "patch", "read", "shell", "write"]],
] as const
yield* Effect.forEach(
cases,
([providerID, id, tools]) =>
Effect.gen(function* () {
const event = {
...context(id),
model: Model.Ref.make({ providerID: Provider.ID.make(providerID), id: Model.ID.make(id) }),
}
yield* hooks.trigger("session", "context", event)
expect(Object.keys(event.tools).sort()).toEqual([...tools])
expect(event.system.map((part) => part.text)).toEqual([fallback])
}),
{ discard: true },
)
}),
)
it.effect("can disable OpenAI tool optimization while retaining its prompt and Anthropic tool optimization", () =>
Effect.gen(function* () {
const hooks = yield* PluginHooks.Service
const pluginHost = yield* makeHost
yield* OptimizePlugin.OpenAIPlugin.effect(pluginHost)
yield* OptimizePlugin.AnthropicToolsPlugin.effect(pluginHost)
yield* Effect.scoped(
Effect.gen(function* () {
yield* OptimizePlugin.OpenAIToolsPlugin.effect(pluginHost)
const event = context("gpt-5")
yield* hooks.trigger("session", "context", event)
expect(event.system[0]?.text).toContain("# Delegation")
expect(Object.keys(event.tools).sort()).toEqual(["edit", "patch", "read", "shell", "write"])
}),
)
const event = context("gpt-5")
yield* hooks.trigger("session", "context", event)
expect(event.system[0]?.text).toContain("# Delegation")
expect(Object.keys(event.tools).sort()).toEqual(["edit", "glob", "grep", "patch", "read", "shell", "write"])
const claude = context("claude-sonnet-4-6")
yield* hooks.trigger("session", "context", claude)
expect(claude.system.map((part) => part.text)).toEqual([fallback])
expect(Object.keys(claude.tools).sort()).toEqual(["edit", "patch", "read", "shell", "write"])
}),
)
@@ -220,7 +148,7 @@ describe("OptimizePlugin", () => {
model.name = name
})
})
yield* OptimizePlugin.MetaPlugin.effect(pluginHost)
yield* SystemPromptPlugin.MetaPlugin.effect(pluginHost)
yield* Effect.forEach(
cases,
@@ -241,7 +169,7 @@ describe("OptimizePlugin", () => {
}),
)
it.effect("preserves tools and an explicit agent system prompt by default", () =>
it.effect("preserves an explicit agent system prompt", () =>
Effect.gen(function* () {
const agents = yield* Agent.Service
const hooks = yield* PluginHooks.Service
@@ -251,7 +179,7 @@ describe("OptimizePlugin", () => {
}),
)
const pluginHost = yield* makeHost
yield* Effect.forEach(OptimizePlugin.Plugins, (plugin) => plugin.effect(pluginHost), {
yield* Effect.forEach(SystemPromptPlugin.Plugins, (plugin) => plugin.effect(pluginHost), {
discard: true,
})
const event = context("gpt-5", "Custom agent prompt")
@@ -259,32 +187,29 @@ describe("OptimizePlugin", () => {
yield* hooks.trigger("session", "context", event)
expect(event.system.map((part) => part.text)).toEqual(["Custom agent prompt"])
expect(Object.keys(event.tools).sort()).toEqual(["edit", "glob", "grep", "patch", "read", "shell", "write"])
}),
)
it.effect("still curates tools when agent lookup fails", () =>
it.effect("skips the hook when agent lookup fails", () =>
Effect.gen(function* () {
const agents = yield* Agent.Service
const hooks = yield* PluginHooks.Service
const pluginHost = yield* makeHost
yield* OptimizePlugin.OpenAIPlugin.effect(pluginHost)
yield* OptimizePlugin.OpenAIToolsPlugin.effect(pluginHost)
yield* SystemPromptPlugin.OpenAIPlugin.effect(pluginHost)
yield* agents.transform((editor) => editor.remove(Agent.ID.make("build")))
const event = context("gpt-5")
yield* hooks.trigger("session", "context", event)
expect(event.system.map((part) => part.text)).toEqual([fallback])
expect(Object.keys(event.tools).sort()).toEqual(["edit", "patch", "read", "shell", "write"])
}),
)
it.effect("allows one model-lab optimization plugin to be enabled independently", () =>
it.effect("allows one model-lab prompt plugin to be enabled independently", () =>
Effect.gen(function* () {
const hooks = yield* PluginHooks.Service
const pluginHost = yield* makeHost
yield* OptimizePlugin.KimiPlugin.effect(pluginHost)
yield* SystemPromptPlugin.KimiPlugin.effect(pluginHost)
const gemini = context("gemini-2.5-pro")
const kimi = context("kimi-k2")
@@ -296,41 +221,35 @@ describe("OptimizePlugin", () => {
}),
)
it.effect("preserves tools for model aliases and catalog-ID prompt selection by default", () =>
it.effect("selects against the catalog ID rather than the physical model ID or family", () =>
Effect.gen(function* () {
const catalog = yield* Catalog.Service
const hooks = yield* PluginHooks.Service
const pluginHost = yield* makeHost
const cases = [
["gpt-5-alias", "custom-model", undefined, "# Delegation"],
["gpt-6-alias", "custom-model", undefined, "Do not settle for a partial"],
["openai-alias", "GPT-5", undefined, fallback],
["codex-family-alias", "custom-deployment", "GPT-CODEX", fallback],
["astra-api-alias", "gpt-6-astra", undefined, fallback],
["astra-family-alias", "custom-deployment", "gpt-6", fallback],
["claude-catalog-alias", "custom-model", undefined, fallback],
["anthropic-api-alias", "Claude-Opus-4-8", undefined, fallback],
["anthropic-family-alias", "custom-deployment", "CLAUDE-SONNET", fallback],
] as const
yield* catalog.transform((editor) => {
for (const [id, modelID, family] of cases)
editor.model.update(Provider.ID.make("test"), Model.ID.make(id), (model) => {
model.modelID = Model.ID.make(modelID)
if (family) model.family = Model.Family.make(family)
})
editor.model.update(Provider.ID.make("test"), Model.ID.make("openai-alias"), (model) => {
model.modelID = Model.ID.make("gpt-5")
})
editor.model.update(Provider.ID.make("test"), Model.ID.make("gpt-5-alias"), (model) => {
model.modelID = Model.ID.make("custom-model")
})
editor.model.update(Provider.ID.make("test"), Model.ID.make("codex-family-alias"), (model) => {
model.modelID = Model.ID.make("custom-deployment")
model.family = Model.Family.make("gpt-codex")
})
})
yield* Effect.forEach(OptimizePlugin.Plugins, (plugin) => plugin.effect(pluginHost), { discard: true })
yield* Effect.forEach(
cases,
([id, , , prompt]) =>
Effect.gen(function* () {
const event = context(id)
yield* hooks.trigger("session", "context", event)
expect(event.system[0]?.text).toContain(prompt)
expect(Object.keys(event.tools).sort()).toEqual(["edit", "glob", "grep", "patch", "read", "shell", "write"])
}),
{ discard: true },
)
yield* SystemPromptPlugin.OpenAIPlugin.effect(pluginHost)
const physicalOpenAI = context("openai-alias")
const physicalCustom = context("gpt-5-alias")
const familyOpenAI = context("codex-family-alias")
yield* hooks.trigger("session", "context", physicalOpenAI)
yield* hooks.trigger("session", "context", physicalCustom)
yield* hooks.trigger("session", "context", familyOpenAI)
expect(physicalOpenAI.system.map((part) => part.text)).toEqual([fallback])
expect(physicalCustom.system.map((part) => part.text)).toEqual([expect.stringContaining("# Delegation")])
expect(familyOpenAI.system.map((part) => part.text)).toEqual([fallback])
}),
)
})
+65 -32
View File
@@ -578,40 +578,73 @@ describe("Session.create", () => {
}),
)
it.effect("replays a fork with stable projected identities", () =>
Effect.gen(function* () {
const session = yield* Session.Service
const bus = yield* Bus.Service
const { db } = yield* Database.Service
const parent = yield* session.create({ location, title: "Parent" })
yield* session.prompt({ sessionID: parent.id, text: "First", resume: false })
yield* SessionInbox.promote(db, bus, parent.id, "steer")
yield* session.synthetic({ sessionID: parent.id, text: "Second", resume: false })
yield* SessionInbox.promote(db, bus, parent.id, "steer")
const forked = yield* session.fork({ sessionID: parent.id, boundary: { type: "through" } })
const original = (yield* session.context(forked.id)).map((message) => message.id)
const recorded = yield* db
.select()
.from(EventTable)
.where(eq(EventTable.aggregate_id, forked.id))
.get()
.pipe(Effect.orDie)
if (!recorded) return yield* Effect.die(new Error("Fork event not found"))
for (const ownership of ["none", "source", "other"] as const) {
it.effect(`replays a fork with ${ownership} ownership and stable projected identities`, () =>
Effect.gen(function* () {
const session = yield* Session.Service
const bus = yield* Bus.Service
const { db } = yield* Database.Service
const source = yield* session.create({
location,
title: "Source",
agent: Agent.ID.make("build"),
model: Model.Ref.make({ id: Model.ID.make("source"), providerID: Provider.ID.make("test") }),
metadata: { source: true },
})
const parentID =
ownership === "none"
? undefined
: ownership === "source"
? source.id
: (yield* session.create({
location: Location.Ref.make({ directory: AbsolutePath.make("/owner") }),
title: "Owner",
metadata: { owner: true },
})).id
yield* session.prompt({ sessionID: source.id, text: "First", resume: false })
yield* SessionInbox.promote(db, bus, source.id, "steer")
yield* session.synthetic({ sessionID: source.id, text: "Second", resume: false })
yield* SessionInbox.promote(db, bus, source.id, "steer")
const forked = yield* session.fork({ sessionID: source.id, boundary: { type: "through" }, parentID })
expect(forked.parentID).toBe(parentID)
expect(forked).toMatchObject({
title: "Source (fork #1)",
agent: source.agent,
model: source.model,
metadata: source.metadata,
location: source.location,
fork: { sessionID: source.id },
})
const original = (yield* session.context(forked.id)).map((message) => message.id)
const recorded = yield* db
.select()
.from(EventTable)
.where(eq(EventTable.aggregate_id, forked.id))
.orderBy(asc(EventTable.seq))
.all()
.pipe(Effect.orDie)
expect(recorded.map((event) => event.type)).toEqual(
parentID ? ["session.created.1", "session.forked.2"] : ["session.forked.2"],
)
yield* bus.remove(forked.id)
yield* db.delete(SessionTable).where(eq(SessionTable.id, forked.id)).run().pipe(Effect.orDie)
yield* bus.replay({
id: recorded.id,
created: recorded.created,
aggregateID: recorded.aggregate_id,
seq: recorded.seq,
type: recorded.type,
data: recorded.data,
})
yield* bus.remove(forked.id)
yield* db.delete(SessionTable).where(eq(SessionTable.id, forked.id)).run().pipe(Effect.orDie)
yield* Effect.forEach(recorded, (event) =>
bus.replay({
id: event.id,
created: event.created,
aggregateID: event.aggregate_id,
seq: event.seq,
type: event.type,
data: event.data,
}),
)
expect((yield* session.context(forked.id)).map((message) => message.id)).toEqual(original)
}),
)
expect((yield* session.context(forked.id)).map((message) => message.id)).toEqual(original)
expect(yield* session.get(forked.id)).toEqual(forked)
}),
)
}
it.effect("inherits instruction entries when forking", () =>
Effect.gen(function* () {
@@ -35,7 +35,7 @@ import { McpInstructions } from "@opencode-ai/core/mcp/instructions"
import { PluginSupervisor } from "@opencode-ai/core/plugin/supervisor"
import { Plugin } from "@opencode-ai/core/plugin"
import { PluginHooks } from "@opencode-ai/core/plugin/hooks"
import { OptimizePlugin } from "@opencode-ai/core/plugin/optimize"
import { SystemPromptPlugin } from "@opencode-ai/core/plugin/system-prompt"
import { describe, expect } from "bun:test"
import { eq } from "drizzle-orm"
import { Effect, Layer } from "effect"
@@ -193,7 +193,7 @@ describe("SessionRunnerLLM recorded", () => {
catalog: catalogHost(catalog),
session: { hook: (name, callback) => hooks.register("session", name, callback) },
})
yield* Effect.forEach(OptimizePlugin.Plugins, (plugin) => plugin.effect(pluginHost), { discard: true })
yield* Effect.forEach(SystemPromptPlugin.Plugins, (plugin) => plugin.effect(pluginHost), { discard: true })
const { db } = yield* Database.Service
yield* db
.insert(ProjectTable)
+2 -2
View File
@@ -51,7 +51,7 @@ import { SessionUsage } from "@opencode-ai/core/session/usage"
import { PluginSupervisor } from "@opencode-ai/core/plugin/supervisor"
import { Plugin } from "@opencode-ai/core/plugin"
import { PluginHooks } from "@opencode-ai/core/plugin/hooks"
import { OptimizePlugin } from "@opencode-ai/core/plugin/optimize"
import { SystemPromptPlugin } from "@opencode-ai/core/plugin/system-prompt"
import { QuestionTool } from "@opencode-ai/core/tool/plugin/question"
import { Agent } from "@opencode-ai/core/agent"
import { Config } from "@opencode-ai/core/config"
@@ -519,7 +519,7 @@ const setup = Effect.gen(function* () {
catalog: catalogHost(catalog),
session: { hook: (name, callback) => hooks.register("session", name, callback) },
})
yield* Effect.forEach(OptimizePlugin.Plugins, (plugin) => plugin.effect(pluginHost), {
yield* Effect.forEach(SystemPromptPlugin.Plugins, (plugin) => plugin.effect(pluginHost), {
discard: true,
})
yield* agents.transform((editor) =>
+287 -1
View File
@@ -30,11 +30,12 @@ import { SessionMessage } from "@opencode-ai/core/session/message"
import { SessionRunnerModel } from "@opencode-ai/core/session/runner/model"
import { SessionStore } from "@opencode-ai/core/session/store"
import { Plugin } from "@opencode-ai/core/plugin"
import { PluginHooks } from "@opencode-ai/core/plugin/hooks"
import { PluginSupervisor } from "@opencode-ai/core/plugin/supervisor"
import { Permission } from "@opencode-ai/core/permission"
import { SubagentTool } from "@opencode-ai/core/tool/plugin/subagent"
import { Tool } from "@opencode-ai/core/tool"
import { tmpdir } from "./fixture/tmpdir"
import { tmpdir, tmpdirScoped } from "./fixture/tmpdir"
import { tempGlobalLayer } from "./fixture/global"
import { offlineModels } from "./fixture/models"
import { testEffect } from "./lib/effect"
@@ -177,6 +178,291 @@ const withSubagent = (location: Location.Ref) =>
})
describe("SubagentTool", () => {
for (const enabled of [undefined, false, true]) {
productionIt.live(`gates the fork parameter with experimental.subagent_fork=${enabled}`, () =>
Effect.gen(function* () {
const dir = yield* tmpdirScoped()
yield* Effect.promise(() =>
Bun.write(path.join(dir.path, "opencode.json"), JSON.stringify({ experimental: { subagent_fork: enabled } })),
)
const sessions = yield* Session.Service
const parent = yield* sessions.create({
location: Location.Ref.make({ directory: AbsolutePath.make(dir.path) }),
})
yield* withSubagent(parent.location)
const locations = yield* LocationServiceMap.Service
const registry = yield* Tool.Service.pipe(Effect.provide(locations.get(parent.location)))
const hooks = yield* PluginHooks.Service.pipe(Effect.provide(locations.get(parent.location)))
const snapshot = yield* registry.snapshot()
const definition = snapshot.definitions.find((tool) => tool.name === SubagentTool.name)!
const context = yield* hooks.trigger("session", "context", {
sessionID: parent.id,
agent: toolIdentity.agent,
model: parentModel,
system: [],
messages: [],
tools: { subagent: { description: definition.description, input: { ...definition.inputSchema } } },
generation: {},
providerOptions: {},
})
expect(Object.keys(context.tools.subagent.input.properties ?? {})).toContain("sessionID")
expect(Object.keys(context.tools.subagent.input.properties ?? {}).includes("fork")).toBe(enabled === true)
expect(context.tools.subagent.input).toEqual(definition.inputSchema)
expect(Object.keys(definition.inputSchema.properties ?? {}).includes("fork")).toBe(enabled === true)
if (enabled === true) return
expect(Object.keys(definition.inputSchema.properties ?? {})).toEqual([
"agent",
"description",
"prompt",
"sessionID",
"background",
])
expect(definition.description).toBe(SubagentTool.description)
expect(definition.description).toContain(
"New child sessions start with fresh context, so include all relevant context and instructions when you don't pass a sessionID.",
)
expect(JSON.stringify(context.tools.subagent)).not.toMatch(/fork/i)
// An unknown field keeps the original schema's behavior; it cannot enable forking or advertise it.
const result = yield* executeTool(registry, {
sessionID: parent.id,
...toolIdentity,
call: {
type: "tool-call",
id: "call-disabled-fork",
name: SubagentTool.name,
input: { agent: "reviewer", description: "review", prompt: "review", fork: true },
},
})
expect(result.status).toBe("completed")
const childID = outputSessionID(result.metadata)
expect((yield* sessions.get(childID)).fork).toBeUndefined()
expect((yield* sessions.inbox(childID)).find((message) => message.type === "user")?.payload.text).toBe(
"You are a subagent spawned by another session.\nreview",
)
const continued = yield* executeTool(registry, {
sessionID: parent.id,
...toolIdentity,
call: {
type: "tool-call",
id: "call-disabled-fork-continuation",
name: SubagentTool.name,
input: { agent: "reviewer", description: "review", prompt: "continue", fork: true, sessionID: childID },
},
})
expect(continued.status).toBe("completed")
expect((yield* sessions.list({ parentID: parent.id })).data).toHaveLength(1)
}),
)
}
it.live("rejects fork together with sessionID without changing the child", () =>
Effect.gen(function* () {
const dir = yield* tmpdirScoped()
yield* Effect.promise(() =>
Bun.write(path.join(dir.path, "opencode.json"), JSON.stringify({ experimental: { subagent_fork: true } })),
)
const sessions = yield* Session.Service
const parent = yield* sessions.create({
location: Location.Ref.make({ directory: AbsolutePath.make(dir.path) }),
})
const child = yield* sessions.create({ parentID: parent.id })
yield* withSubagent(parent.location)
const locations = yield* LocationServiceMap.Service
const registry = yield* Tool.Service.pipe(Effect.provide(locations.get(parent.location)))
for (const fork of [false, true]) {
const result = yield* executeTool(registry, {
sessionID: parent.id,
...toolIdentity,
call: {
type: "tool-call",
id: `call-conflicting-fork-${fork}`,
name: SubagentTool.name,
input: { agent: "reviewer", description: "review", prompt: "review", fork, sessionID: child.id },
},
})
expect(result).toMatchObject({
status: "error",
error: { message: "Cannot use fork with sessionID. Omit one of them." },
})
}
expect(yield* sessions.get(child.id)).toEqual(child)
expect(yield* sessions.inbox(child.id)).toEqual([])
expect((yield* sessions.list({ parentID: parent.id })).data).toHaveLength(1)
}),
)
completionIt.live("sends inherited history to a forked child and preserves it on continuation", () =>
Effect.gen(function* () {
const dir = yield* tmpdirScoped()
yield* Effect.promise(() =>
Bun.write(path.join(dir.path, "opencode.json"), JSON.stringify({ experimental: { subagent_fork: true } })),
)
const sessions = yield* Session.Service
const parent = yield* sessions.create({
location: Location.Ref.make({ directory: AbsolutePath.make(dir.path) }),
agent: toolIdentity.agent,
model: parentModel,
metadata: { source: "fork-test" },
})
yield* withSubagent(parent.location)
const locations = yield* LocationServiceMap.Service
const registry = yield* Tool.Service.pipe(Effect.provide(locations.get(parent.location)))
const hooks = yield* PluginHooks.Service.pipe(Effect.provide(locations.get(parent.location)))
const requests: PluginHooks.Domains["session"]["context"][] = []
yield* hooks.register("session", "context", (event) =>
Effect.sync(() => {
requests.push(event)
}),
)
const bus = yield* Bus.Service
const { db } = yield* Database.Service
yield* sessions.prompt({ sessionID: parent.id, text: "Remember the project context", resume: false })
yield* SessionInbox.promote(db, bus, parent.id, "steer")
const previous = SessionMessage.ID.create()
yield* bus.publish(SessionEvent.Step.Started, {
sessionID: parent.id,
assistantMessageID: previous,
agent: toolIdentity.agent,
model: parentModel,
})
yield* bus.publish(SessionEvent.Step.Ended, {
sessionID: parent.id,
assistantMessageID: previous,
finish: "tool-calls",
cost: Money.USD.zero,
tokens,
})
yield* sessions.updateMessage({
sessionID: parent.id,
messageID: previous,
content: [
{
type: "tool",
id: "call-parent-read",
name: "read",
time: { created: parent.time.created },
state: {
status: "completed",
input: { filePath: "README.md" },
content: [{ type: "text", text: "Inherited file contents" }],
},
},
],
})
const spawning = SessionMessage.ID.create()
yield* bus.publish(SessionEvent.Step.Started, {
sessionID: parent.id,
assistantMessageID: spawning,
agent: toolIdentity.agent,
model: parentModel,
})
yield* bus.publish(SessionEvent.Text.Started, { sessionID: parent.id, assistantMessageID: spawning, ordinal: 0 })
yield* bus.publish(SessionEvent.Text.Ended, {
sessionID: parent.id,
assistantMessageID: spawning,
ordinal: 0,
text: "Spawning response must not be inherited",
})
yield* sessions.prompt({ sessionID: parent.id, text: "Later parent message", resume: false })
yield* SessionInbox.promote(db, bus, parent.id, "steer")
const result = yield* executeTool(registry, {
sessionID: parent.id,
...toolIdentity,
messageID: spawning,
call: {
type: "tool-call",
id: "call-fork",
name: SubagentTool.name,
input: { agent: "reviewer", description: "fork review", prompt: "Review the file", fork: true },
},
})
expect(result.status).toBe("completed")
const child = yield* sessions.get(outputSessionID(result.metadata))
expect(child).toMatchObject({
parentID: parent.id,
title: "fork review",
agent: "reviewer",
model: childModel,
metadata: parent.metadata,
fork: { sessionID: parent.id, boundary: { type: "before", messageID: spawning } },
})
const request = requests.find((request) => request.sessionID === child.id)!
expect(request.agent).toBe(Agent.ID.make("reviewer"))
expect(request.messages).toEqual(
expect.arrayContaining([
expect.objectContaining({ role: "user", content: [{ type: "text", text: "Remember the project context" }] }),
expect.objectContaining({
role: "assistant",
content: [expect.objectContaining({ type: "tool-call", id: "call-parent-read" })],
}),
expect.objectContaining({
role: "tool",
content: [
expect.objectContaining({
type: "tool-result",
result: { type: "text", value: "Inherited file contents" },
}),
],
}),
expect.objectContaining({
role: "user",
content: [
{
type: "text",
text: "You are a forked subagent. Use the inherited history as context and perform only the task below.\nReview the file",
},
],
}),
]),
)
expect(JSON.stringify(request.messages)).not.toContain("Spawning response must not be inherited")
expect(JSON.stringify(request.messages)).not.toContain("Later parent message")
expect((yield* sessions.context(child.id)).map((message) => message.id)).not.toContain(previous)
const continued = yield* executeTool(registry, {
sessionID: parent.id,
...toolIdentity,
call: {
type: "tool-call",
id: "call-fork-continue",
name: SubagentTool.name,
input: { agent: "reviewer", description: "follow up", prompt: "Continue reviewing", sessionID: child.id },
},
})
expect(outputSessionID(continued.metadata)).toBe(child.id)
const latest = requests.findLast((request) => request.sessionID === child.id)!
expect(JSON.stringify(latest.messages)).toContain("Inherited file contents")
expect(JSON.stringify(latest.messages)).toContain("Continue reviewing")
expect(JSON.stringify(latest.messages)).not.toContain("Later parent message")
expect((yield* sessions.list({ parentID: parent.id })).data).toHaveLength(1)
for (const fork of [undefined, false]) {
const fresh = yield* executeTool(registry, {
sessionID: parent.id,
...toolIdentity,
call: {
type: "tool-call",
id: `call-fresh-${fork}`,
name: SubagentTool.name,
input: {
agent: "fallback",
description: "fresh",
prompt: "Start fresh",
...(fork === undefined ? {} : { fork }),
},
},
})
expect(fresh.status).toBe("completed")
const freshChild = yield* sessions.get(outputSessionID(fresh.metadata))
expect(freshChild.fork).toBeUndefined()
expect(freshChild.model).toMatchObject(parentModel)
const freshRequest = requests.find((request) => request.sessionID === freshChild.id)!
expect(JSON.stringify(freshRequest.messages)).not.toContain("Inherited file contents")
expect(JSON.stringify(freshRequest.messages)).toContain("Start fresh")
}
}),
)
completionIt.live("admits one durable completion across live delivery and restart replay", () =>
Effect.acquireRelease(
Effect.promise(() => tmpdir()),
@@ -14,7 +14,6 @@ import { ApplicationLifecycle } from "../lifecycle"
import { finishFirstLaunchOnboarding, isFirstLaunchOnboardingPending } from "../lifecycle/onboarding"
import { BackgroundService } from "../service/background-service"
import { DesktopCli } from "../service/desktop-cli"
import { SidecarCredentials } from "../service/sidecar-credentials"
import { getDefaultServerUrl, setDefaultServerUrl } from "../service/server-settings"
import { Updater } from "../updater"
import { getLastFocusedWindow, setBackgroundColor } from "../windows"
@@ -30,8 +29,8 @@ export const appHandlers = AppRpcs.toLayer(
const logging = yield* DesktopLogging.Service
const runFork = Effect.runForkWith(yield* Effect.context())
return AppRpcs.of({
AppAwaitInitialization: () => background.connection.pipe(Effect.map(SidecarCredentials.ready)),
AppReconnectService: () => background.reconnect.pipe(Effect.map(SidecarCredentials.ready)),
AppAwaitInitialization: () => background.connection,
AppReconnectService: () => background.reconnect,
AppConsumeInitialDeepLinks: () => Effect.sync(lifecycle.consumeInitialDeepLinks),
AppGetDefaultServerUrl: () => Effect.sync(getDefaultServerUrl),
AppSetDefaultServerUrl: ({ url }) => Effect.sync(() => setDefaultServerUrl(url)),
@@ -1,14 +1,14 @@
export * as BackgroundServiceState from "./background-service-state"
import { Effect, Exit, Ref } from "effect"
import type { SidecarCredentials } from "./sidecar-credentials"
import type { ServerReadyData } from "../../shared/ipc-contract"
export const make = Effect.fn("BackgroundServiceState.make")(function* (options: {
readonly initial: Effect.Effect<SidecarCredentials.Data, unknown>
readonly reconnect: Effect.Effect<SidecarCredentials.Data>
readonly initial: Effect.Effect<ServerReadyData, unknown>
readonly reconnect: Effect.Effect<ServerReadyData>
}) {
// Every Exit is an Effect, so the latest resolution replays directly for each consumer.
const current = yield* Ref.make<Exit.Exit<SidecarCredentials.Data, unknown>>(yield* options.initial.pipe(Effect.exit))
const current = yield* Ref.make<Exit.Exit<ServerReadyData, unknown>>(yield* options.initial.pipe(Effect.exit))
return {
connection: Ref.get(current).pipe(Effect.flatten, Effect.orDie),
reconnect: options.reconnect.pipe(Effect.tap((next) => Ref.set(current, Exit.succeed(next)))),
@@ -1,14 +1,14 @@
import { app } from "electron"
import { Context, Effect, FileSystem, Layer, Path } from "effect"
import type { ServerReadyData } from "../../shared/ipc-contract"
import { BackgroundServiceState } from "./background-service-state"
import { cleanStages, DesktopCli } from "./desktop-cli"
import { SidecarCredentials } from "./sidecar-credentials"
export * as BackgroundService from "./background-service"
export interface Interface {
readonly connection: Effect.Effect<SidecarCredentials.Data>
readonly reconnect: Effect.Effect<SidecarCredentials.Data>
readonly connection: Effect.Effect<ServerReadyData>
readonly reconnect: Effect.Effect<ServerReadyData>
}
export class Service extends Context.Service<Service, Interface>()("opencode/desktop/BackgroundService") {}
@@ -56,9 +56,10 @@ const connect = Effect.fn("BackgroundService.connect")(function* (mode: "initial
...endpoint(url.origin),
})
if (mode === "initial" && isolated && cli.binary) yield* cleanStages(cli.binary).pipe(Effect.orDie)
const ready = { url: url.origin, password: service.auth.password } satisfies SidecarCredentials.Data
SidecarCredentials.set(ready)
return ready
return {
url: url.origin,
password: service.auth.password,
} satisfies ServerReadyData
})
function endpoint(url: string | undefined) {
@@ -1,24 +0,0 @@
import { describe, expect, test } from "bun:test"
import { authorization, ready } from "./sidecar-credentials"
const sidecar = { url: "http://127.0.0.1:4096", password: "secret" }
const expected = `Basic ${Buffer.from("opencode:secret").toString("base64")}`
describe("sidecar authorization", () => {
test("adds the Basic credential only for the sidecar origin", () => {
expect(authorization(sidecar, "http://127.0.0.1:4096/api/session?limit=1")).toBe(expected)
expect(authorization(sidecar, "http://127.0.0.1:4097/api/session")).toBeUndefined()
expect(authorization(sidecar, "http://localhost:4096/api/session")).toBeUndefined()
expect(authorization(sidecar, "https://127.0.0.1:4096/api/session")).toBeUndefined()
})
test("hands the renderer the origin only", () => {
expect(ready(sidecar)).toEqual({ url: sidecar.url })
})
test("adds nothing before the sidecar is known or when it has no password", () => {
expect(authorization(undefined, "http://127.0.0.1:4096/api/session")).toBeUndefined()
expect(authorization({ url: sidecar.url, password: null }, "http://127.0.0.1:4096/api/session")).toBeUndefined()
expect(authorization(sidecar, "not a url")).toBeUndefined()
})
})
@@ -1,30 +0,0 @@
export * as SidecarCredentials from "./sidecar-credentials"
import type { ServerReadyData } from "../../shared/ipc-contract"
export type Data = ServerReadyData & { password: string | null }
// The renderer talks to the sidecar without an Authorization header; the main process adds it from
// here so GET requests stay CORS-simple and skip the preflight round trip. Both the initial connection
// and every reconnect publish the current endpoint.
let current: Data | undefined
export function set(data: Data) {
current = data
}
export function get() {
return current
}
/** What the renderer learns about the sidecar: its origin, never its credential. */
export function ready(data: Data): ServerReadyData {
return { url: data.url }
}
/** The Basic credential for a request to the sidecar origin, or undefined for any other URL. */
export function authorization(sidecar: Data | undefined, url: string) {
if (!sidecar?.password || !URL.canParse(url)) return
if (new URL(url).origin !== sidecar.url) return
return `Basic ${Buffer.from(`opencode:${sidecar.password}`).toString("base64")}`
}
+1 -21
View File
@@ -1,6 +1,5 @@
import type { BrowserWindow } from "electron"
import { SidecarCredentials } from "../service/sidecar-credentials"
import { addRendererHeaders, hasHeader, upsertHeader } from "./headers"
import { addRendererHeaders } from "./headers"
import { isRendererUrl } from "./protocol"
const rendererPermissions = new Set(["clipboard-sanitized-write", "notifications"])
@@ -32,25 +31,6 @@ export function wireNavigationPolicy(win: BrowserWindow, openExternalURL: (url:
}
export function wireRendererHeaders(win: BrowserWindow) {
// The renderer sends sidecar requests without credentials, so its GETs are CORS-simple and need no
// preflight. Electron applies these listeners in Chromium's extraHeaders mode, after the CORS
// decision, so adding Authorization here does not reintroduce one.
//
// Only the renderer's own top-level frame is credentialed. Other content in this session (web views,
// embedded pages) can reach the same loopback origin and must not inherit its access. Requests with
// no frame, such as from a service worker, are not credentialed either; the renderer registers none.
win.webContents.session.webRequest.onBeforeSendHeaders(
{ urls: ["http://127.0.0.1/*", "http://localhost/*"] },
(details, callback) => {
const frame = details.frame
const renderer = !!frame && frame.parent === null && isRendererUrl(frame.url)
const authorization = renderer && SidecarCredentials.authorization(SidecarCredentials.get(), details.url)
if (authorization && !hasHeader(details.requestHeaders, "Authorization")) {
upsertHeader(details.requestHeaders, "Authorization", authorization)
}
callback({ requestHeaders: details.requestHeaders })
},
)
win.webContents.session.webRequest.onHeadersReceived((details, callback) => {
const responseHeaders = details.responseHeaders ?? {}
addRendererHeaders(responseHeaders, { document: isRendererUrl(details.url, true) })
@@ -49,8 +49,12 @@ export function MigrationStatus(props: { server: ServerReadyData }) {
await wait(1_000, abort.signal)
if (abort.signal.aborted) return
// The main process credentials sidecar requests; see `wireRendererHeaders`.
const client = OpenCode.make({ baseUrl: props.server.url })
const client = OpenCode.make({
baseUrl: props.server.url,
headers: props.server.password
? { Authorization: `Basic ${btoa(`opencode:${props.server.password}`)}` }
: undefined,
})
void (async () => {
while (true) {
@@ -27,7 +27,7 @@ describe("desktop renderer initialization", () => {
})
test("returns initialized sidecar data", () => {
const sidecar = { url: "http://127.0.0.1:1234" }
const sidecar = { url: "http://127.0.0.1:1234", password: "secret" }
expect(initializationData(Object.assign(() => sidecar, { error: undefined }))).toBe(sidecar)
})
@@ -47,7 +47,7 @@ describe("desktop renderer initialization", () => {
})
test("refreshes the managed sidecar endpoint", async () => {
const sidecar = { url: "http://127.0.0.1:4321" }
const sidecar = { url: "http://127.0.0.1:4321", password: "next" }
const updates: (typeof sidecar)[] = []
const resolve = createSidecarResolver({
api: { reconnectService: async () => sidecar },
@@ -60,7 +60,7 @@ describe("desktop renderer initialization", () => {
})
test("keeps the current sidecar when reconnection resolves the same endpoint", async () => {
const sidecar = { url: "http://127.0.0.1:4321" }
const sidecar = { url: "http://127.0.0.1:4321", password: "same" }
const updates: (typeof sidecar)[] = []
const resolve = createSidecarResolver({
api: { reconnectService: async () => ({ ...sidecar }) },
@@ -73,7 +73,7 @@ describe("desktop renderer initialization", () => {
})
test("does not publish a sidecar resolved after cancellation", async () => {
const sidecar = { url: "http://127.0.0.1:4321" }
const sidecar = { url: "http://127.0.0.1:4321", password: "next" }
const pending = Promise.withResolvers<typeof sidecar>()
const updates: (typeof sidecar)[] = []
const resolve = createSidecarResolver({
@@ -7,10 +7,11 @@ export function initializationData<A>(state: (() => A | undefined) & { error: un
return state()
}
// The main process adds Authorization to sidecar requests (`wireRendererHeaders`); the renderer never
// holds the password, and its GETs carry only CORS-safelisted headers so they skip the preflight.
export function sidecarHttp(data: SidecarData) {
return { url: data.url }
return {
url: data.url,
password: data.password ?? undefined,
}
}
export function createSidecarResolver(input: {
@@ -28,7 +29,7 @@ export function createSidecarResolver(input: {
}
function sameSidecar(current: SidecarData | undefined, next: SidecarData) {
return current?.url === next.url
return current?.url === next.url && current.password === next.password
}
function markLocalServerStartup(error: unknown) {
+1 -1
View File
@@ -1,6 +1,6 @@
// The sidecar password never crosses into the renderer; the main process adds it to sidecar requests.
export type ServerReadyData = {
url: string
password: string | null
}
export type TitlebarTheme = {
@@ -3,6 +3,7 @@ import { Rpc, RpcGroup } from "effect/unstable/rpc"
const ServerReadyData = Schema.Struct({
url: Schema.String,
password: Schema.NullOr(Schema.String),
})
export const AppAwaitInitialization = Rpc.make("AppAwaitInitialization", { success: ServerReadyData })
File diff suppressed because one or more lines are too long
@@ -11,6 +11,9 @@ export class Info extends Schema.Class<Info>("ConfigExperimental.Info")({
subagent_depth: NonNegativeInt.pipe(optional).annotate({
description: "Maximum subagent nesting depth. Defaults to 1.",
}),
subagent_fork: Schema.Boolean.pipe(optional).annotate({
description: "Enable the subagent fork parameter. Defaults to false.",
}),
policies: ConfigPolicy.Info.pipe(Schema.Array, optional).annotate({
description: "Ordered policies controlling access to configured resources",
}),
+1 -1
View File
@@ -233,7 +233,7 @@ export namespace Execution {
export const Interrupted = Event.durable({
type: "session.execution.interrupted",
...options,
schema: { ...Base, reason: Schema.Literals(["user", "shutdown", "superseded", "inactivity"]) },
schema: { ...Base, reason: Schema.Literals(["user", "shutdown", "superseded"]) },
})
export type Interrupted = typeof Interrupted.Type
}
+11
View File
@@ -10,6 +10,17 @@ import { AbsolutePath } from "../src/schema.js"
import { WebSearch } from "../src/websearch.js"
describe("Config.Entry", () => {
test("keeps subagent forking opt-in", () => {
const decode = Schema.decodeUnknownSync(Config.Info)
const encode = Schema.encodeSync(Config.Info)
expect(encode(decode({ experimental: {} }))).toEqual({ experimental: {} })
for (const subagent_fork of [false, true]) {
const input = { experimental: { subagent_fork } }
expect(encode(decode(input))).toEqual(input)
}
expect(() => decode({ experimental: { subagent_fork: "true" } })).toThrow()
})
test("accepts directory-only worktree config and omits it when absent", () => {
const decode = Schema.decodeUnknownSync(Config.Info)
const input = { worktree: { directory: "../worktrees" } }
@@ -177,9 +177,7 @@
padding: 4px 8px 12px;
}
[data-component="session-review-v2-sidebar-root"]
[data-slot="session-review-v2-sidebar-tree"]
.scroll-view__thumb[data-orientation="vertical"] {
[data-component="session-review-v2-sidebar-root"] [data-slot="session-review-v2-sidebar-tree"] .scroll-view__thumb {
width: 16px;
}
@@ -190,20 +188,6 @@
background-color: var(--v2-border-border-muted, var(--border-weak-base));
}
[data-component="session-review-v2-sidebar-root"]
[data-slot="session-review-v2-sidebar-tree"]
.scroll-view__thumb[data-orientation="horizontal"] {
height: 16px;
opacity: 1;
}
[data-component="session-review-v2-sidebar-root"]
[data-slot="session-review-v2-sidebar-tree"]
.scroll-view__thumb[data-orientation="horizontal"]::after {
width: auto;
height: 6px;
}
[data-component="session-review-v2-sidebar-root"]
[data-slot="session-review-v2-sidebar-tree"]
.scroll-view__thumb:hover::after,
@@ -124,7 +124,6 @@ export function SessionReviewV2Sidebar(props: SessionReviewV2SidebarProps) {
<ScrollView
data-slot="session-review-v2-sidebar-tree"
class="group/file-tree-v2"
orientation="both"
thumbVisibility="scroll"
viewportRef={props.viewportRef}
>
+1 -11
View File
@@ -10,7 +10,6 @@ import { Spinner } from "./spinner"
export function DialogUpdate(props: {
check?: (signal: AbortSignal) => Promise<string | undefined>
state: () => UpdateState | undefined
skip: () => void
install: () => Promise<void>
restart: () => void
}) {
@@ -48,16 +47,7 @@ export function DialogUpdate(props: {
: type === "installed"
? { label: "Restart", run: props.restart }
: undefined
return [
{
label: "Skip",
run: () => {
props.skip()
dialog.clear()
},
},
...(confirm ? [confirm] : []),
]
return [{ label: "Skip", run: () => dialog.clear() }, ...(confirm ? [confirm] : [])]
})
createEffect(() => setActive(Math.max(0, buttons().length - 1)))
@@ -95,12 +95,14 @@ export const { use: useUpdateNotification, provider: UpdateNotificationProvider
// The notification can predate an installation through /update.
if (known && active?.type !== "installing" && !(active?.type === "installed" && active.version === known.version))
setState({ type: known.type, version: known.version })
// Manual checks hide the current notice without marking the version as seen.
if (origin === "manual") setNotification(undefined)
if (origin === "notification") dismiss()
const status = state()?.type
dialog.replace(() => (
<DialogUpdate
check={status === undefined || status === "failed" ? check : undefined}
state={state}
skip={dismiss}
install={install}
restart={restart}
/>
+4 -36
View File
@@ -15,21 +15,15 @@
outline: none;
}
.scroll-view[data-orientation="horizontal"] .scroll-view__viewport {
overflow-x: auto;
overflow-y: hidden;
}
.scroll-view[data-orientation="both"] .scroll-view__viewport {
overflow: auto;
}
.scroll-view__viewport::-webkit-scrollbar {
display: none;
}
.scroll-view__thumb {
position: absolute;
inset-inline-end: 0;
top: 0;
width: 12px;
transition: opacity 200ms ease;
cursor: default;
user-select: none;
@@ -37,19 +31,7 @@
opacity: 0;
}
.scroll-view__thumb[data-orientation="vertical"] {
inset-inline-end: 0;
top: 0;
width: 12px;
}
.scroll-view__thumb[data-orientation="horizontal"] {
left: 0;
bottom: 0;
height: 12px;
}
.scroll-view__thumb[data-orientation="vertical"]::after {
.scroll-view__thumb::after {
content: "";
position: absolute;
left: 50%;
@@ -63,20 +45,6 @@
transition: background-color 150ms ease;
}
.scroll-view__thumb[data-orientation="horizontal"]::after {
content: "";
position: absolute;
left: 0;
right: 0;
top: 50%;
height: 4px;
transform: translateY(-50%);
border-radius: 9999px;
background-color: var(--border-weak-base);
backdrop-filter: blur(4px);
transition: background-color 150ms ease;
}
.scroll-view__thumb:hover::after,
.scroll-view__thumb[data-dragging="true"]::after {
background-color: var(--border-strong-base);
+1 -22
View File
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test"
import { canScrollKey, scrollKey, scrollOffsetFromThumbPointer, scrollTopFromThumbPointer } from "./scroll-view"
import { canScrollKey, scrollKey, scrollTopFromThumbPointer } from "./scroll-view"
describe("scrollKey", () => {
test("maps plain navigation keys", () => {
@@ -88,24 +88,3 @@ describe("scrollTopFromThumbPointer", () => {
expect(scrollTopFromThumbPointer(input)).toBeCloseTo((292 / 344) * 7200)
})
})
describe("scrollOffsetFromThumbPointer", () => {
const input = {
viewportStart: 100,
grabOffset: 10,
clientSize: 400,
scrollClientSize: 400,
scrollSize: 1_000,
thumbSize: 100,
}
test("maps horizontal pointer movement to scroll offset", () => {
expect(scrollOffsetFromThumbPointer({ ...input, pointer: 118 })).toBe(0)
expect(scrollOffsetFromThumbPointer({ ...input, pointer: 402 })).toBe(600)
})
test("reverses horizontal pointer movement for RTL", () => {
expect(scrollOffsetFromThumbPointer({ ...input, pointer: 118, reverse: true })).toBe(600)
expect(scrollOffsetFromThumbPointer({ ...input, pointer: 402, reverse: true })).toBe(0)
})
})
+67 -147
View File
@@ -8,7 +8,7 @@ export type ScrollViewThumbVisibility = "hover" | "scroll"
export interface ScrollViewProps extends ComponentProps<"div"> {
viewportRef?: (el: HTMLDivElement) => void
orientation?: "vertical" | "horizontal" | "both"
orientation?: "vertical" | "horizontal" // currently only vertical is fully implemented for thumb
/**
* `hover`: show while hovered or scrolling. `scroll`: show only while scrolling.
*
@@ -78,37 +78,12 @@ export function scrollTopFromThumbPointer(input: {
thumbHeight: number
/** Viewport height used for max scroll. Defaults to `clientHeight` (track == viewport). */
scrollClientHeight?: number
}) {
return scrollOffsetFromThumbPointer({
pointer: input.pointer,
viewportStart: input.viewportTop,
grabOffset: input.grabOffset,
clientSize: input.clientHeight,
scrollSize: input.scrollHeight,
thumbSize: input.thumbHeight,
scrollClientSize: input.scrollClientHeight,
})
}
export function scrollOffsetFromThumbPointer(input: {
pointer: number
viewportStart: number
grabOffset: number
clientSize: number
scrollSize: number
thumbSize: number
scrollClientSize?: number
reverse?: boolean
}) {
const padding = 8
const maxThumbStart = input.clientSize - padding * 2 - input.thumbSize
if (maxThumbStart <= 0) return 0
const thumbStart = Math.max(
0,
Math.min(input.pointer - input.viewportStart - padding - input.grabOffset, maxThumbStart),
)
const progress = input.reverse ? 1 - thumbStart / maxThumbStart : thumbStart / maxThumbStart
return progress * Math.max(0, input.scrollSize - (input.scrollClientSize ?? input.clientSize))
const maxThumbTop = input.clientHeight - padding * 2 - input.thumbHeight
if (maxThumbTop <= 0) return 0
const thumbTop = Math.max(0, Math.min(input.pointer - input.viewportTop - padding - input.grabOffset, maxThumbTop))
return (thumbTop / maxThumbTop) * Math.max(0, input.scrollHeight - (input.scrollClientHeight ?? input.clientHeight))
}
export function ScrollView(props: ScrollViewProps) {
@@ -141,8 +116,7 @@ export function ScrollView(props: ScrollViewProps) {
let rootRef!: HTMLDivElement
let viewportRef!: HTMLDivElement
let verticalThumbRef!: HTMLDivElement
let horizontalThumbRef!: HTMLDivElement
let thumbRef!: HTMLDivElement
const thumbMount = () => local.thumbContainer
const thumbHover = () => local.thumbHoverTarget
@@ -150,20 +124,18 @@ export function ScrollView(props: ScrollViewProps) {
const [state, setState] = createStore({
isHovered: false,
dragging: undefined as "vertical" | "horizontal" | undefined,
isDragging: false,
isScrolling: false,
verticalThumbSize: 0,
verticalThumbStart: 0,
showVerticalThumb: false,
horizontalThumbSize: 0,
horizontalThumbStart: 0,
showHorizontalThumb: false,
thumbHeight: 0,
thumbTop: 0,
showThumb: false,
})
const isHovered = () => state.isHovered
const isDragging = () => state.dragging !== undefined
const isDragging = () => state.isDragging
const isScrolling = () => state.isScrolling
const vertical = () => local.orientation === "vertical" || local.orientation === "both"
const horizontal = () => local.orientation === "horizontal" || local.orientation === "both"
const thumbHeight = () => state.thumbHeight
const thumbTop = () => state.thumbTop
const showThumb = () => state.showThumb
let scrollIdleTimer: ReturnType<typeof setTimeout> | undefined
@@ -185,42 +157,33 @@ export function ScrollView(props: ScrollViewProps) {
const updateThumb = () => {
if (!viewportRef) return
const { scrollTop, scrollHeight, clientHeight } = viewportRef
if (scrollHeight <= clientHeight || scrollHeight === 0) {
setState("showThumb", false)
return
}
setState("showThumb", true)
const trackPadding = 8
const minThumbSize = 32
const trackClientHeight = thumbMount()?.clientHeight || clientHeight
const trackHeight = trackClientHeight - trackPadding * 2
if (vertical()) {
const trackSize = Math.max(0, (thumbMount()?.clientHeight || viewportRef.clientHeight) - trackPadding * 2)
const size = trackSize
? Math.min(trackSize, Math.max((viewportRef.clientHeight / viewportRef.scrollHeight) * trackSize, minThumbSize))
: 0
const maxScroll = viewportRef.scrollHeight - viewportRef.clientHeight
const maxStart = trackSize - size
setState("showVerticalThumb", maxScroll > 0)
setState("verticalThumbSize", size)
setState(
"verticalThumbStart",
trackPadding + (maxScroll > 0 ? (viewportRef.scrollTop / maxScroll) * maxStart : 0),
)
} else {
setState("showVerticalThumb", false)
}
const minThumbHeight = 32
// Calculate raw thumb height based on ratio
let height = (clientHeight / scrollHeight) * trackHeight
height = Math.max(height, minThumbHeight)
if (horizontal()) {
const trackSize = Math.max(0, (thumbMount()?.clientWidth || viewportRef.clientWidth) - trackPadding * 2)
const size = trackSize
? Math.min(trackSize, Math.max((viewportRef.clientWidth / viewportRef.scrollWidth) * trackSize, minThumbSize))
: 0
const maxScroll = viewportRef.scrollWidth - viewportRef.clientWidth
const maxStart = trackSize - size
const rtl = getComputedStyle(viewportRef).direction === "rtl"
const offset = Math.max(0, Math.min(rtl ? -viewportRef.scrollLeft : viewportRef.scrollLeft, maxScroll))
const start = maxScroll > 0 ? (offset / maxScroll) * maxStart : 0
setState("showHorizontalThumb", maxScroll > 0)
setState("horizontalThumbSize", size)
setState("horizontalThumbStart", trackPadding + (rtl ? maxStart - start : start))
} else {
setState("showHorizontalThumb", false)
}
const maxScrollTop = scrollHeight - clientHeight
const maxThumbTop = trackHeight - height
const top = maxScrollTop > 0 ? (scrollTop / maxScrollTop) * maxThumbTop : 0
// Ensure thumb stays within bounds (shouldn't be necessary due to math above, but good for safety)
const boundedTop = trackPadding + Math.max(0, Math.min(top, maxThumbTop))
setState("thumbHeight", height)
setState("thumbTop", boundedTop)
}
onMount(() => {
@@ -241,13 +204,6 @@ export function ScrollView(props: ScrollViewProps) {
updateThumb()
})
createEffect(() => {
if (!horizontal() || !viewportRef) return
const observer = new MutationObserver(updateThumb)
observer.observe(viewportRef, { childList: true, subtree: true, characterData: true })
onCleanup(() => observer.disconnect())
})
createEffect(() => {
const target = thumbHover()
if (!target) return
@@ -263,88 +219,58 @@ export function ScrollView(props: ScrollViewProps) {
})
})
const onThumbPointerDown = (axis: "vertical" | "horizontal", e: PointerEvent) => {
const onThumbPointerDown = (e: PointerEvent) => {
e.preventDefault()
e.stopPropagation()
setState("dragging", axis)
const thumb = axis === "vertical" ? verticalThumbRef : horizontalThumbRef
const grabOffset =
axis === "vertical"
? e.clientY - thumb.getBoundingClientRect().top
: e.clientX - thumb.getBoundingClientRect().left
setState("isDragging", true)
const grabOffset = e.clientY - thumbRef.getBoundingClientRect().top
const track = thumbMount() ?? viewportRef
thumb.setPointerCapture(e.pointerId)
thumbRef.setPointerCapture(e.pointerId)
const onPointerMove = (e: PointerEvent) => {
const vertical = axis === "vertical"
const rtl = !vertical && getComputedStyle(viewportRef).direction === "rtl"
const offset = scrollOffsetFromThumbPointer({
pointer: vertical ? e.clientY : e.clientX,
viewportStart: vertical ? track.getBoundingClientRect().top : track.getBoundingClientRect().left,
const { scrollHeight, clientHeight } = viewportRef
viewportRef.scrollTop = scrollTopFromThumbPointer({
pointer: e.clientY,
viewportTop: track.getBoundingClientRect().top,
grabOffset,
clientSize: vertical ? track.clientHeight : track.clientWidth,
scrollClientSize: vertical ? viewportRef.clientHeight : viewportRef.clientWidth,
scrollSize: vertical ? viewportRef.scrollHeight : viewportRef.scrollWidth,
thumbSize: vertical ? state.verticalThumbSize : state.horizontalThumbSize,
reverse: rtl,
clientHeight: track.clientHeight,
scrollClientHeight: clientHeight,
scrollHeight,
thumbHeight: thumbHeight(),
})
if (vertical) {
viewportRef.scrollTop = offset
return
}
viewportRef.scrollLeft = rtl ? -offset : offset
}
const done = (e: PointerEvent) => {
setState("dragging", undefined)
thumb.releasePointerCapture(e.pointerId)
thumb.removeEventListener("pointermove", onPointerMove)
thumb.removeEventListener("pointerup", done)
thumb.removeEventListener("pointercancel", done)
setState("isDragging", false)
thumbRef.releasePointerCapture(e.pointerId)
thumbRef.removeEventListener("pointermove", onPointerMove)
thumbRef.removeEventListener("pointerup", done)
thumbRef.removeEventListener("pointercancel", done)
}
thumb.addEventListener("pointermove", onPointerMove)
thumb.addEventListener("pointerup", done)
thumb.addEventListener("pointercancel", done)
thumbRef.addEventListener("pointermove", onPointerMove)
thumbRef.addEventListener("pointerup", done)
thumbRef.addEventListener("pointercancel", done)
}
const renderVerticalThumb = () => (
const renderThumb = () => (
<div
ref={(el) => {
verticalThumbRef = el
thumbRef = el
}}
onPointerDown={(event) => onThumbPointerDown("vertical", event)}
onPointerDown={onThumbPointerDown}
class="scroll-view__thumb"
data-orientation="vertical"
data-visible={thumbVisible()}
data-dragging={state.dragging === "vertical"}
data-dragging={isDragging()}
style={{
height: `${state.verticalThumbSize}px`,
transform: `translateY(${state.verticalThumbStart}px)`,
height: `${thumbHeight()}px`,
transform: `translateY(${thumbTop()}px)`,
"z-index": 100, // ensure it displays over content
}}
/>
)
const renderHorizontalThumb = () => (
<div
ref={(el) => {
horizontalThumbRef = el
}}
onPointerDown={(event) => onThumbPointerDown("horizontal", event)}
class="scroll-view__thumb"
data-orientation="horizontal"
data-visible={thumbVisible()}
data-dragging={state.dragging === "horizontal"}
style={{
width: `${state.horizontalThumbSize}px`,
transform: `translateX(${state.horizontalThumbStart}px)`,
"z-index": 100,
}}
/>
)
// Keybinds implementation
// We ensure the viewport has a tabindex so it can receive focus
// We can also explicitly catch PageUp/Down if we want smooth scroll or specific behavior,
@@ -394,7 +320,6 @@ export function ScrollView(props: ScrollViewProps) {
<div
ref={rootRef}
class={`scroll-view ${local.class || ""}`}
data-orientation={local.orientation}
style={local.style}
onPointerEnter={() => {
if (hoverRoot()) setState("isHovered", true)
@@ -438,14 +363,9 @@ export function ScrollView(props: ScrollViewProps) {
</div>
{/* Thumb Overlay — optionally portaled into an external track */}
<Show when={state.showVerticalThumb}>
<Show when={thumbMount()} fallback={renderVerticalThumb()}>
{(mount) => <Portal mount={mount()}>{renderVerticalThumb()}</Portal>}
</Show>
</Show>
<Show when={state.showHorizontalThumb}>
<Show when={thumbMount()} fallback={renderHorizontalThumb()}>
{(mount) => <Portal mount={mount()}>{renderHorizontalThumb()}</Portal>}
<Show when={showThumb()}>
<Show when={thumbMount()} fallback={renderThumb()}>
{(mount) => <Portal mount={mount()}>{renderThumb()}</Portal>}
</Show>
</Show>
</div>
+1 -3
View File
@@ -68,7 +68,6 @@ export type SelectProps<T> = Omit<
numeric?: boolean
children?: (item: T) => JSX.Element
valueClass?: string
contentClass?: string
}
export function Select<T>(props: SelectProps<T>) {
@@ -89,7 +88,6 @@ export function Select<T>(props: SelectProps<T>) {
"numeric",
"disabled",
"valueClass",
"contentClass",
"placement",
"gutter",
"sameWidth",
@@ -210,7 +208,7 @@ export function Select<T>(props: SelectProps<T>) {
</span>
</Trigger>
<Portal>
<Content class={local.contentClass} data-component="menu-v2-content" data-slot="select-v2-content">
<Content data-component="menu-v2-content" data-slot="select-v2-content">
<Listbox data-slot="select-v2-listbox" />
</Content>
</Portal>
+3 -64
View File
@@ -1,30 +1,20 @@
@property --file-tree-v2-row-overlay {
syntax: "<color>";
inherits: true;
initial-value: transparent;
}
[data-component="file-tree-v2"] {
display: flex;
flex-direction: column;
gap: 2px;
width: max-content;
min-width: 100%;
}
[data-component="file-tree-v2"] [data-slot="file-tree-v2-row"] {
--file-tree-v2-row-overlay: transparent;
box-sizing: border-box;
width: 100%;
min-width: max-content;
min-width: 0;
height: 28px;
display: flex;
align-items: center;
justify-content: flex-start;
gap: 6px;
padding-inline-end: 8px;
overflow: clip;
overflow: visible;
border: none;
border-radius: 6px;
background-color: transparent;
@@ -34,12 +24,7 @@
scroll-margin-block: 8px;
transition:
background-color 120ms ease,
color 120ms ease,
--file-tree-v2-row-overlay 120ms ease;
}
[data-component="file-tree-v2"] [data-slot="file-tree-v2-label"] {
margin-inline-end: 12px;
color 120ms ease;
}
[data-component="file-tree-v2"] [data-slot="file-tree-v2-row"][data-ignored] {
@@ -47,14 +32,10 @@
}
[data-component="file-tree-v2"] [data-slot="file-tree-v2-row"]:hover {
--file-tree-v2-row-overlay: var(--v2-overlay-simple-overlay-hover);
background-color: var(--v2-overlay-simple-overlay-hover);
}
[data-component="file-tree-v2"] [data-slot="file-tree-v2-row"][data-selected] {
--file-tree-v2-row-overlay: var(--v2-overlay-simple-overlay-pressed);
color: var(--v2-text-text-base);
background-color: var(--v2-overlay-simple-overlay-pressed);
}
@@ -63,14 +44,6 @@
background-color: var(--v2-overlay-simple-overlay-pressed);
}
[data-component="file-tree-v2"]
[data-slot="file-tree-v2-context-trigger"][data-context-menu-open]
[data-slot="file-tree-v2-row"]:not([data-selected]) {
--file-tree-v2-row-overlay: var(--v2-overlay-simple-overlay-hover);
background-color: var(--v2-overlay-simple-overlay-hover);
}
[data-component="file-tree-v2"] [data-slot="file-tree-v2-guide"] {
position: absolute;
top: 0;
@@ -137,9 +110,6 @@
[data-component="file-tree-v2"] [data-slot="file-tree-v2-change"] {
box-sizing: border-box;
flex: none;
position: sticky;
inset-inline-end: 8px;
z-index: 1;
display: flex;
flex-direction: row;
align-items: center;
@@ -156,37 +126,6 @@
font-feature-settings:
"tnum" on,
"lnum" on;
background:
linear-gradient(var(--file-tree-v2-row-overlay), var(--file-tree-v2-row-overlay)), var(--v2-background-bg-base);
}
[data-component="file-tree-v2"] [data-slot="file-tree-v2-change"]::before {
content: "";
position: absolute;
inset-block: 0;
inset-inline-end: 100%;
width: 16px;
pointer-events: none;
background:
linear-gradient(to right, transparent, var(--file-tree-v2-row-overlay)),
linear-gradient(to right, transparent, var(--v2-background-bg-base));
}
[data-component="file-tree-v2"]:dir(rtl) [data-slot="file-tree-v2-change"]::before {
background:
linear-gradient(to left, transparent, var(--file-tree-v2-row-overlay)),
linear-gradient(to left, transparent, var(--v2-background-bg-base));
}
[data-component="file-tree-v2"] [data-slot="file-tree-v2-change"]::after {
content: "";
position: absolute;
inset-block: 0;
inset-inline-start: 100%;
width: 16px;
pointer-events: none;
background:
linear-gradient(var(--file-tree-v2-row-overlay), var(--file-tree-v2-row-overlay)), var(--v2-background-bg-base);
}
[data-component="file-tree-v2"] [data-slot="file-tree-v2-change"][data-change="modified"] {
@@ -1499,39 +1499,3 @@ Use versions compatible with the OpenCode release you target and test the
installed package, not only a workspace-linked copy. Because the plugin API is
beta, publish compatible plugin updates when V2 entrypoints or contracts
change.
## Support V1
A plugin can support V1 and V2 from the same package entrypoint. Default export
one object with a V1 `server()` function and a V2 `setup()` function:
```ts title="src/index.ts"
import { Plugin } from "@opencode-ai/plugin"
export default {
...Plugin.define({
id: "example",
async setup(ctx) {
await ctx.tool.hook("execute.before", () => {
console.log("A tool is about to run")
})
},
}),
async server() {
return {
"tool.execute.before": async () => {
console.log("A tool is about to run")
},
}
},
}
```
- V1 calls `server()` and uses the returned hooks.
- V2 reads the default export's `id` and `setup()` (or `effect()` for Effect plugins), ignoring `server()`.
- Keep each implementation on its own API; sharing an export does not translate V1 hooks into V2 hooks.
- Spread `Plugin.define(...)` into the exported object so it type-checks the V2 definition separately from `server()`.
The V1 object form is supported in OpenCode `1.18.29`. Older V1 releases may
expect function exports instead; test the installed package with the oldest V1
release you intend to support and with V2.
@@ -1,251 +0,0 @@
---
title: "Go"
description: "Low cost subscription for open coding models."
---
OpenCode Go is a low cost subscription — **$5 for your first month**, then **$10/month** — that gives you reliable access to popular open coding models.
Go works like any other provider in OpenCode. You subscribe to OpenCode Go and get your API key. It's **completely optional** and you don't need it to use OpenCode.
It is designed primarily for international users and provides stable global access.
## How it works
1. Sign in to the [OpenCode console](https://console.opencode.ai), subscribe to Go, add your billing details, and copy your API key.
2. Run `/connect` in the TUI, select **OpenCode Go**, and paste your API key.
```text
/connect
```
3. Run `/models` to select a model available through Go.
```text
/models
```
<Callout>Only one member per workspace can subscribe to OpenCode Go.</Callout>
The current list of models includes:
- **Grok 4.5**
- **GLM-5.2**
- **GLM-5.1**
- **GPT 5.6 Luna**
- **Kimi K3**
- **Kimi K2.7 Code**
- **Kimi K2.6**
- **MiMo-V2.5**
- **MiMo-V2.5-Pro**
- **MiniMax M3**
- **MiniMax M2.7**
- **Qwen3.8 Max**
- **Qwen3.7 Max**
- **Qwen3.7 Plus**
- **Qwen3.6 Plus**
- **DeepSeek V4 Pro**
- **DeepSeek V4 Flash**
- **Hy3**
The list of models may change as we test and add new ones.
## Usage limits
OpenCode Go includes the following limits:
- **5 hour limit** — $12 of usage
- **Weekly limit** — $30 of usage
- **Monthly limit** — $60 of usage
Limits are defined in dollar value. Your actual request count depends on the model you use. Cheaper models like DeepSeek V4 Flash allow for more requests, while higher-cost models like GLM-5.2 allow for fewer.
The table below provides an estimated request count based on typical Go usage patterns:
| Model | Requests per 5 hours | Requests per week | Requests per month |
| ----------------- | -------------------- | ----------------- | ------------------ |
| Grok 4.5 | 120 | 300 | 600 |
| GPT 5.6 Luna | 2,050 | 5,100 | 10,250 |
| GLM-5.2 | 880 | 2,150 | 4,300 |
| GLM-5.1 | 880 | 2,150 | 4,300 |
| Kimi K3 | 110 | 250 | 490 |
| Kimi K2.7 Code | 1,350 | 3,380 | 6,750 |
| Kimi K2.6 | 1,150 | 2,880 | 5,750 |
| MiMo-V2.5 | 30,100 | 75,200 | 150,400 |
| MiMo-V2.5-Pro | 3,250 | 8,150 | 16,300 |
| MiniMax M3 | 3,200 | 8,000 | 16,000 |
| MiniMax M2.7 | 3,400 | 8,500 | 17,000 |
| Qwen3.8 Max | 160 | 400 | 810 |
| Qwen3.7 Max | 340 | 840 | 1,690 |
| Qwen3.7 Plus | 4,300 | 10,800 | 21,600 |
| Qwen3.6 Plus | 3,300 | 8,200 | 16,300 |
| DeepSeek V4 Pro | 3,450 | 8,550 | 17,150 |
| DeepSeek V4 Flash | 31,650 | 79,050 | 158,150 |
| Hy3 | 4,300 | 10,750 | 21,500 |
The estimates are based on observed request patterns:
- Grok 4.5 — 1,100 input, 71,500 cached, 220 output tokens per request
- GLM-5.2/5.1 — 700 input, 52,000 cached, 150 output tokens per request
- GPT 5.6 Luna — 1,000 input, 50,000 cached, 220 output tokens per request
- Kimi K3 — 1,050 input, 76,500 cached, 300 output tokens per request
- Kimi K2.7/K2.6 — 870 input, 55,000 cached, 200 output tokens per request
- DeepSeek V4 Pro — 750 input, 82,000 cached, 290 output tokens per request
- DeepSeek V4 Flash — 790 input, 68,000 cached, 280 output tokens per request
- MiniMax M3 — 510 input, 56,000 cached, 190 output tokens per request
- MiniMax M2.7 — 300 input, 55,000 cached, 125 output tokens per request
- MiMo-V2.5 — 830 input, 71,500 cached, 295 output tokens per request
- MiMo-V2.5-Pro — 790 input, 86,000 cached, 305 output tokens per request
- Qwen3.8 Max — 420 input, 66,000 cached, 200 output tokens per request
- Qwen3.7 Max — 420 input, 66,000 cached, 200 output tokens per request
- Qwen3.7 Plus — 500 input, 57,000 cached, 190 output tokens per request
- Qwen3.6 Plus — 500 input, 57,000 cached, 190 output tokens per request
- Hy3 — 830 input, 71,500 cached, 295 output tokens per request
The estimates are also based on the following prices per 1M tokens and the monthly usage included with each model:
<div class="docs-table-scroll" role="region" aria-label="Go model pricing" tabIndex={0}>
| Model | Input | Output | Cached Read | Cached Write | Usage |
| ---------------------------- | ------ | ------ | ----------- | ------------ | ----- |
| Grok 4.5 | $2.00 | $6.00 | $0.30 | - | $15 |
| GPT 5.6 Luna (≤ 272K tokens) | $0.20 | $1.20 | $0.02 | $0.25 | $15 |
| GPT 5.6 Luna (> 272K tokens) | $0.40 | $1.80 | $0.04 | $0.50 | $15 |
| GLM-5.2 | $1.40 | $4.40 | $0.26 | - | $60 |
| GLM-5.1 | $1.40 | $4.40 | $0.26 | - | $60 |
| Kimi K3 | $3.00 | $15.00 | $0.30 | - | $15 |
| Kimi K2.7 Code | $0.95 | $4.00 | $0.19 | - | $60 |
| Kimi K2.6 | $0.95 | $4.00 | $0.16 | - | $60 |
| MiMo V2.5 | $0.14 | $0.28 | $0.0028 | - | $60 |
| MiMo V2.5 Pro | $0.435 | $0.87 | $0.003625 | - | $15 |
| MiniMax M3 | $0.30 | $1.20 | $0.06 | - | $60 |
| MiniMax M2.7 | $0.30 | $1.20 | $0.06 | $0.375 | $60 |
| MiniMax M2.5 | $0.30 | $1.20 | $0.06 | $0.375 | $60 |
| Qwen3.8 Max | $2.00 | $6.00 | $0.25 | $2.50 | $15 |
| Qwen3.7 Max | $2.50 | $7.50 | $0.50 | $3.125 | $60 |
| Qwen3.7 Plus (≤ 256K tokens) | $0.40 | $1.60 | $0.04 | $0.50 | $60 |
| Qwen3.7 Plus (> 256K tokens) | $1.20 | $4.80 | $0.12 | $1.50 | $60 |
| Qwen3.6 Plus (≤ 256K tokens) | $0.50 | $3.00 | $0.05 | $0.625 | $60 |
| Qwen3.6 Plus (> 256K tokens) | $2.00 | $6.00 | $0.20 | $2.50 | $60 |
| DeepSeek V4 Pro | $0.435 | $0.87 | $0.003625 | - | $15 |
| DeepSeek V4 Flash | $0.14 | $0.28 | $0.0028 | - | $60 |
| Hy3 | $0.14 | $0.58 | $0.035 | - | $60 |
</div>
You can track your current usage in the [console](https://console.opencode.ai).
<Callout type="tip">If you reach the usage limit, you can continue using the free models.</Callout>
Usage limits may change as we learn from early usage and feedback.
### Usage beyond limits
If you also have credits on your Console balance, you can enable the **Use balance** option in the console. When enabled, Go will fall back to your [pay-as-you-go balance](/console/models#pricing) after you've reached your usage limits instead of blocking requests.
### Why some models have lower usage
With Go, you pay $10/month and we aim to give you 6x that in usage.
- For most models, we make this work through bulk discounts and reserved GPU capacity. We pass those savings on to you through the 6x multiplier.
- For some models, we haven't had the opportunity to negotiate a discount or host them at a lower cost, either because the model is new or because their public pricing is already discounted.
- For these models, you still get a little more than if you paid the model providers directly. This is why their usage multiplier is lower in the table above.
## Endpoints
You can also access Go models through the following API endpoints.
<div class="docs-table-scroll" role="region" aria-label="Go model endpoints" tabIndex={0}>
| Model | Model ID | Endpoint | AI SDK Package |
| ----------------- | ----------------- | ------------------------------------------------ | --------------------------- |
| Grok 4.5 | grok-4.5 | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` |
| GPT 5.6 Luna | gpt-5.6-luna | `https://opencode.ai/zen/go/v1/responses` | `@ai-sdk/openai` |
| GLM-5.2 | glm-5.2 | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` |
| GLM-5.1 | glm-5.1 | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` |
| Kimi K3 | kimi-k3 | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` |
| Kimi K2.7 Code | kimi-k2.7-code | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` |
| Kimi K2.6 | kimi-k2.6 | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` |
| DeepSeek V4 Pro | deepseek-v4-pro | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` |
| DeepSeek V4 Flash | deepseek-v4-flash | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` |
| MiMo-V2.5 | mimo-v2.5 | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` |
| MiMo-V2.5-Pro | mimo-v2.5-pro | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` |
| MiniMax M3 | minimax-m3 | `https://opencode.ai/zen/go/v1/messages` | `@ai-sdk/anthropic` |
| MiniMax M2.7 | minimax-m2.7 | `https://opencode.ai/zen/go/v1/messages` | `@ai-sdk/anthropic` |
| MiniMax M2.5 | minimax-m2.5 | `https://opencode.ai/zen/go/v1/messages` | `@ai-sdk/anthropic` |
| Qwen3.8 Max | qwen3.8-max | `https://opencode.ai/zen/go/v1/messages` | `@ai-sdk/anthropic` |
| Qwen3.7 Max | qwen3.7-max | `https://opencode.ai/zen/go/v1/messages` | `@ai-sdk/anthropic` |
| Qwen3.7 Plus | qwen3.7-plus | `https://opencode.ai/zen/go/v1/messages` | `@ai-sdk/anthropic` |
| Qwen3.6 Plus | qwen3.6-plus | `https://opencode.ai/zen/go/v1/messages` | `@ai-sdk/anthropic` |
| Hy3 | hy3 | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` |
</div>
These AI SDK packages are for applications calling Go directly. To use Go in OpenCode, connect with `/connect` and set
the [model](/models) using the format `opencode-go/<model-id>`:
```jsonc title="opencode.jsonc"
{
"$schema": "https://opencode.ai/config.json",
"model": "opencode-go/kimi-k3",
}
```
### Models
Fetch the full list of available models and their metadata from the models endpoint:
```bash
curl https://opencode.ai/zen/go/v1/models
```
## Privacy
| Model | Model training | Data retention |
| ----------------- | -------------- | -------------- |
| Grok 4.5 | Not used | 30 days |
| GPT 5.6 Luna | Not used | 30 days |
| GLM-5.2 | Not used | 0 days |
| GLM-5.1 | Not used | 0 days |
| Kimi K3 | Not used | 0 days |
| Kimi K2.7 Code | Not used | 0 days |
| Kimi K2.6 | Not used | 0 days |
| MiMo-V2.5-Pro | Not used | 0 days |
| MiMo-V2.5 | Not used | 0 days |
| Qwen3.8 Max | Not used | 0 days |
| Qwen3.7 Max | Not used | 0 days |
| Qwen3.7 Plus | Not used | 0 days |
| Qwen3.6 Plus | Not used | 0 days |
| MiniMax M3 | Not used | 0 days |
| MiniMax M2.7 | Not used | 0 days |
| DeepSeek V4 Pro | Not used | 0 days |
| DeepSeek V4 Flash | Not used | 0 days |
| Hy3 | Not used | 0 days |
- **Grok 4.5:** ZDR disables important API features that depend on stored data, including the stateful Responses API, Files and Collections, and the Batch API. [Learn more](https://docs.x.ai/developers/faq/security#what-is-zero-data-retention-zdr).
- **GPT 5.6 Luna:** Abuse monitoring logs are generated for all API feature usage and retained for up to 30 days. [Learn more](https://developers.openai.com/api/docs/guides/your-data#data-retention-controls-for-abuse-monitoring).
- **DeepSeek V4 Flash:** ZDR agreement is renewed monthly. The current agreement is valid through August 31, 2026.
## Background
Open models have gotten really good. They now reach performance close to proprietary models for coding tasks. Because many providers can serve them competitively, they are usually far cheaper.
However, getting reliable, low latency access to them can be difficult. Providers vary in quality and availability.
<Callout type="tip">We tested a select group of models and providers that work well with OpenCode.</Callout>
To fix this, we did a couple of things:
1. We tested a select group of open models and talked to their teams about how to best run them.
2. We worked with a few providers to make sure these were being served correctly.
3. We benchmarked the combination of the model/provider and came up with a list that we feel good recommending.
OpenCode Go gives you access to these models for **$5 for your first month**, then **$10/month**.
## Goals
We created OpenCode Go to:
1. Make AI coding **accessible** to more people with a low cost subscription.
2. Provide **reliable** access to the best open coding models.
3. Curate models that are **tested and benchmarked** for coding agent use.
4. Have **no lock-in** by allowing you to use any other provider with OpenCode as well.

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