Compare commits

..

15 Commits

Author SHA1 Message Date
Shoubhit Dash cc7d4ebb69 refactor(core): adopt declarative jujutsu vcs markers 2026-08-26 14:03:30 +05:30
Shoubhit Dash 4eaf533cd0 feat(plugin): add declarative vcs repository markers (#45192) 2026-08-26 13:49:36 +05:30
Shoubhit Dash 0f7a76eff0 fix(ai): keep bedrock mantle responses on http (#45197) 2026-08-26 13:38:27 +05:30
Luke Parker 16d731bd67 feat(app): render settings as a fullscreen surface (#45190) 2026-08-26 07:57:36 +00:00
Luke Parker ea582fc133 feat(app): stack collapsed tool calls (#45176) 2026-08-26 07:56:53 +00:00
opencode-agent[bot] 7e27e81bc7 fix(app): preserve timeline measurements when moving sessions (#45145)
Co-authored-by: Brendonovich <14191578+Brendonovich@users.noreply.github.com>
2026-08-26 14:39:01 +08:00
opencode-agent[bot] 667722897e fix(app): identify session worktrees from project inventory (#45153)
Co-authored-by: Brendonovich <14191578+Brendonovich@users.noreply.github.com>
2026-08-26 14:38:08 +08:00
opencode-agent[bot] d12dbd12a9 fix(app): prevent duplicate rows when editing queued prompts (#45169)l
Co-authored-by: Brendonovich <14191578+Brendonovich@users.noreply.github.com>
2026-08-26 06:21:44 +00:00
opencode-agent[bot] b0bd0bc394 fix(app): align project settings server sections (#45163)
Co-authored-by: Brendonovich <14191578+Brendonovich@users.noreply.github.com>
2026-08-26 04:42:26 +00:00
Dax 437df1164c feat(plugin): expose session move 2026-08-26 00:14:12 -04:00
opencode-agent[bot] 9a91e21a76 fix(app): preserve workspace choices across draft tabs (#45149)
Co-authored-by: Brendonovich <14191578+Brendonovich@users.noreply.github.com>
2026-08-26 03:51:14 +00:00
opencode-agent[bot] d01ac2069a chore: update nix node_modules hashes 2026-08-26 03:32:00 +00:00
Aiden Cline a78d3c5438 fix(ai): recover Anthropic request_too_large as overflow (#45144) 2026-08-25 22:30:14 -05:00
Shoubhit Dash 46465000a0 fix(core): harden jujutsu repository integration 2026-08-25 21:13:02 +05:30
Shoubhit Dash bee852b5cf feat(core): add jujutsu vcs plugin 2026-08-25 20:58:23 +05:30
92 changed files with 2240 additions and 599 deletions
+4 -4
View File
@@ -1,8 +1,8 @@
{
"nodeModules": {
"x86_64-linux": "sha256-oQnV96kE3lIqsQaaUrH4tiEX8/5xvBWizXMGxayFSHo=",
"aarch64-linux": "sha256-Hkl1xdCQ7voAllwtyrm3TjQT9cfej29fvPIP3lH7zVo=",
"aarch64-darwin": "sha256-s0WHRB13qcD0KlgWNXO7gLpsDOnfB8xny81GnN5YeQc=",
"x86_64-darwin": "sha256-fnYi1AxCrnO3byW9keDfBH2ueCfGZdaweOrV6AerrGs="
"x86_64-linux": "sha256-t7k0Nk9Z7FMkAKt2UReI1jD1KoPB+LhQQx1x1p5Htlc=",
"aarch64-linux": "sha256-tU7C2zYKiX+RpwBBBLjX7vrqQNLPvDc5Uz9EbgGJvSA=",
"aarch64-darwin": "sha256-A3o+2zNuFHV5FZx/azdXBjcKdS5o41b2e2Q1Qq8C1m0=",
"x86_64-darwin": "sha256-NXgvteaxJQqBBZIHnQbivghHTJnL2IMZiFPNssGp2Os="
}
}
+4 -2
View File
@@ -40,15 +40,16 @@ const patterns = [
/model_context_window_exceeded/i,
/too many tokens/i,
/token limit exceeded/i,
/request_too_large/i,
]
const payloadPatterns = [/request_too_large/i, /request entity too large/i, /payload too large/i, /request too large/i]
const payloadPatterns = [/request entity too large/i, /payload too large/i, /request too large/i]
const exclusions = [/^(throttling error|service unavailable):/i, /rate limit/i, /too many requests/i]
export const isContextOverflow = (message: string) =>
!exclusions.some((pattern) => pattern.test(message)) &&
(patterns.some((pattern) => pattern.test(message)) || /^400\s*(status code)?\s*\(no body\)/i.test(message))
(patterns.some((pattern) => pattern.test(message)) || /^4(?:00|13)\s*(status code)?\s*\(no body\)/i.test(message))
export const isPayloadTooLarge = (message: string) => payloadPatterns.some((pattern) => pattern.test(message))
@@ -106,6 +107,7 @@ export function classifyProviderFailure(input: ProviderFailure): AIError["reason
clientScoped &&
(codes.includes("context_length_exceeded") ||
codes.includes("model_context_window_exceeded") ||
codes.includes("request_too_large") ||
isContextOverflow(text))
)
return new InvalidRequestReason({ ...common, classification: "context-overflow" })
@@ -1,5 +1,5 @@
import { Auth } from "../route/auth.js"
import type { Route as RouteDef, RouteDefaultsInput } from "../route/client.js"
import { Route, type RouteDefaultsInput } from "../route/client.js"
import type { ProviderPackage } from "../provider-package.js"
import { OpenAIChat } from "../protocols/openai-chat.js"
import { OpenAIResponses } from "../protocols/openai-responses.js"
@@ -26,9 +26,15 @@ export interface Settings extends ProviderPackage.Settings {
readonly providerOptions?: OpenAIProviderOptionsInput
}
const responsesRoute = OpenAIResponses.route.with({
const responsesRoute = Route.make({
id: "bedrock-mantle-responses",
provider: id,
providerMetadataKey: OpenAIResponses.route.providerMetadataKey,
protocol: OpenAIResponses.protocol,
endpoint: OpenAIResponses.route.endpoint,
auth: OpenAIResponses.route.auth,
transport: OpenAIResponses.httpTransport,
defaults: OpenAIResponses.route.defaults,
})
const chatRoute = OpenAIChat.route.with({
@@ -38,7 +44,7 @@ const chatRoute = OpenAIChat.route.with({
export const routes = [responsesRoute, chatRoute]
const configuredRoute = <Body, Prepared>(route: RouteDef<Body, Prepared>, input: Config) => {
const configuredRoute = <Body, Prepared>(route: Route<Body, Prepared>, input: Config) => {
const region = input.region ?? input.credentials?.region ?? "us-east-1"
const credentials = input.credentials === undefined ? undefined : { ...input.credentials, region }
return route.with({
+22
View File
@@ -211,6 +211,28 @@ describe("RequestExecutor", () => {
}).pipe(Effect.provide(responsesLayer([new Response("request too large", { status: 413 })]))),
)
it.effect("classifies Anthropic request_too_large as context overflow", () =>
Effect.gen(function* () {
const executor = yield* RequestExecutor.Service
const error = yield* executor.execute(request).pipe(Effect.flip)
expectAIError(error)
expect(error.reason).toMatchObject({
_tag: "InvalidRequest",
classification: "context-overflow",
http: { response: { status: 413 } },
})
}).pipe(
Effect.provide(
responsesLayer([
new Response('{"error":{"type":"request_too_large","message":"Request exceeds the maximum size"}}', {
status: 413,
}),
]),
),
),
)
it.effect("does not classify ordinary invalid requests as context overflow", () =>
Effect.gen(function* () {
const executor = yield* RequestExecutor.Service
+9 -4
View File
@@ -18,13 +18,19 @@ describe("provider error classification", () => {
expect(messages.every(isContextOverflow)).toBe(true)
})
test("classifies request size failures separately from context overflow", () => {
const failures = [
classifyProviderFailure({ message: "request too large", status: 413 }),
test("classifies Anthropic request_too_large as recoverable overflow", () => {
expect(
classifyProviderFailure({
message: '{"error":{"type":"request_too_large","message":"Request exceeds the maximum size"}}',
status: 400,
}),
).toMatchObject({ _tag: "InvalidRequest", classification: "context-overflow" })
expect(isContextOverflow("413 status code (no body)")).toBe(true)
})
test("classifies generic request size failures separately from context overflow", () => {
const failures = [
classifyProviderFailure({ message: "request too large", status: 413 }),
classifyProviderFailure({ message: "upstream request entity too large", status: 502 }),
]
@@ -33,7 +39,6 @@ describe("provider error classification", () => {
expect.objectContaining({ _tag: "InvalidRequest", classification: "payload-too-large" }),
),
)
expect(isContextOverflow("413 status code (no body)")).toBe(false)
})
test("does not classify rate limits as context overflow", () => {
@@ -3,6 +3,7 @@ import { Effect } from "effect"
import { HttpClientRequest } from "effect/unstable/http"
import { LLM, Message } from "../../src/index.js"
import { AmazonBedrockMantle } from "../../src/providers.js"
import { OpenAIResponses } from "../../src/protocols/openai-responses.js"
import { compileRequest, LLMClient } from "../../src/route/client.js"
import { it } from "../lib/effect.js"
import { dynamicResponse, fixedResponse } from "../lib/http.js"
@@ -19,6 +20,7 @@ describe("Amazon Bedrock Mantle provider", () => {
it.effect("uses Chat by default and exposes Responses", () =>
Effect.gen(function* () {
const provider = AmazonBedrockMantle.configure({ credentials })
expect(provider.responses("openai.gpt-oss-120b").route.transport).toBe(OpenAIResponses.httpTransport)
const chat = yield* compileRequest(LLM.request({ model: provider.model("openai.gpt-oss-120b"), prompt: "Hi" }))
const responses = yield* compileRequest(
LLM.request({ model: provider.responses("openai.gpt-oss-120b"), prompt: "Hi" }),
@@ -24,11 +24,17 @@ test("session settings use the remote server context", async ({ page }) => {
await configureServers(page)
await page.goto(`/server/${base64Encode(serverB)}/session/${sessionB.id}`)
await expect(page.getByRole("heading", { name: sessionB.title, exact: true })).toBeVisible()
const sessionHeading = page.getByRole("heading", { name: sessionB.title, exact: true, includeHidden: true })
await expect(sessionHeading).toBeVisible()
await page.keyboard.press("Control+,")
const dialog = page.locator(".settings-dialog")
const autoAccept = dialog.locator('[data-action="settings-auto-accept-permissions"]')
const settings = page.getByTestId("settings-screen")
await expect(settings).toBeVisible()
await expect(page.getByRole("dialog")).toHaveCount(0)
await expect(settings.getByRole("tablist")).toHaveCSS("width", "328px")
await expect(sessionHeading).toBeAttached()
await expect(sessionHeading).toBeHidden()
const autoAccept = settings.locator('[data-action="settings-auto-accept-permissions"]')
const input = autoAccept.getByRole("switch")
await expect(autoAccept).toBeVisible()
await expect(input).toBeEnabled()
@@ -55,9 +61,12 @@ test("session settings use the remote server context", async ({ page }) => {
},
])
await dialog.getByRole("tab", { name: "Models" }).click()
await expect(dialog.getByRole("switch", { name: "Server B Model" })).toBeEnabled()
await expect(dialog.getByRole("switch", { name: "Server A Model" })).toHaveCount(0)
await settings.getByRole("tab", { name: "Models" }).click()
await expect(settings.getByRole("switch", { name: "Server B Model" })).toBeEnabled()
await expect(settings.getByRole("switch", { name: "Server A Model" })).toHaveCount(0)
await settings.getByRole("button", { name: "Back to app" }).click()
await expect(settings).toBeHidden()
await expect(sessionHeading).toBeVisible()
})
test("auto-accept responds for an unfocused server session", async ({ page }) => {
@@ -78,7 +87,7 @@ test("auto-accept responds for an unfocused server session", async ({ page }) =>
await page.goto(`/server/${base64Encode(serverA)}/session/${sessionA.id}`)
await expect(page.getByRole("heading", { name: sessionA.title, exact: true })).toBeVisible()
await page.keyboard.press("Control+,")
const autoAccept = page.locator(".settings-dialog").locator('[data-action="settings-auto-accept-permissions"]')
const autoAccept = page.getByTestId("settings-screen").locator('[data-action="settings-auto-accept-permissions"]')
await autoAccept.locator('[data-slot="switch-control"]').click()
await expect(autoAccept.getByRole("switch")).toBeChecked()
await expect
@@ -178,7 +187,7 @@ test("auto-accept sweeps again after a reconnect", async ({ page }) => {
const first = await transport.waitForConnection()
await page.keyboard.press("Control+,")
const autoAccept = page.locator(".settings-dialog").locator('[data-action="settings-auto-accept-permissions"]')
const autoAccept = page.getByTestId("settings-screen").locator('[data-action="settings-auto-accept-permissions"]')
await autoAccept.locator('[data-slot="switch-control"]').click()
await expect(autoAccept.getByRole("switch")).toBeChecked()
await expect
@@ -234,7 +243,7 @@ test("auto-accept approves a request discovered by opening a session", async ({
await expect(page.getByRole("heading", { name: sessionA.title, exact: true })).toBeVisible()
await page.keyboard.press("Control+,")
const autoAccept = page.locator(".settings-dialog").locator('[data-action="settings-auto-accept-permissions"]')
const autoAccept = page.getByTestId("settings-screen").locator('[data-action="settings-auto-accept-permissions"]')
await autoAccept.locator('[data-slot="switch-control"]').click()
await expect(autoAccept.getByRole("switch")).toBeChecked()
@@ -2,7 +2,7 @@ import { expect, test, type Route } from "@playwright/test"
const server = "http://127.0.0.1:4097"
test("nested server dialog keeps focus inside the top layer", async ({ page }) => {
test("server dialog keeps focus above fullscreen settings", async ({ page }) => {
await page.addInitScript((server) => {
localStorage.setItem("opencode.global.dat:server", JSON.stringify({ list: [server] }))
}, server)
@@ -24,8 +24,9 @@ test("nested server dialog keeps focus inside the top layer", async ({ page }) =
await page.goto("/")
await page.keyboard.press("Control+,")
const settings = page.locator(".settings-dialog")
const settings = page.getByTestId("settings-screen")
await expect(settings).toBeVisible()
await expect(page.getByRole("dialog")).toHaveCount(0)
await settings.getByRole("tab", { name: "Servers" }).click()
await settings.getByRole("button", { name: "Add server" }).click()
@@ -41,6 +42,9 @@ test("nested server dialog keeps focus inside the top layer", async ({ page }) =
await expect(password).toBeFocused()
await password.fill("secret")
await expect(password).toHaveValue("secret")
await page.keyboard.press("Escape")
await expect(editor).toBeHidden()
await expect(settings).toBeVisible()
})
function json(route: Route, body: unknown, status = 200) {
@@ -9,7 +9,7 @@ test("space activates a focused timeline button instead of scrolling", async ({
reducedMotion: true,
})
const scroller = page.locator(".scroll-view__viewport", { has: page.locator("[data-timeline-row]") })
const trigger = page.locator(`[data-timeline-part-id="${shellID}"] [data-slot="collapsible-trigger"]`)
const trigger = page.getByRole("button", { name: "Used Shell" })
await trigger.focus()
const before = await scroller.evaluate((element) => element.scrollTop)
await trigger.press("Space")
@@ -40,7 +40,7 @@ test.describe("regression: session timeline context group resize", () => {
expect(samples.at(-1)?.expanded).toBe("true")
})
test("paints a stable exploring to explored transition", async ({ page }) => {
test("keeps a grouped tool summary stable as its calls complete", async ({ page }) => {
const events: OpenCodeEvent[] = []
await page.setViewportSize({ width: 1400, height: 900 })
await mockServer(page, events, [
@@ -55,13 +55,12 @@ test.describe("regression: session timeline context group resize", () => {
await devtools.send("Emulation.setCPUThrottlingRate", { rate: 4 })
const context = page.locator(`[data-timeline-part-ids="${contextIDs.join(",")}"]`).first()
await expectAppVisible(context)
await expect(context.locator('[data-component="tool-status-title"]')).toHaveAttribute("aria-label", "Exploring")
await expect(context.getByRole("button")).toHaveAccessibleName("Used Read, Glob, Grep, List")
const contextSelector = `[data-timeline-part-ids="${contextIDs.join(",")}"]`
const regions = defineVisualRegions({
status: {
selector: `${contextSelector} [data-component="tool-status-title"]`,
opacitySelectors: ['[data-slot="tool-status-active"]', '[data-slot="tool-status-done"]'],
selector: `${contextSelector} [data-component="context-tool-group-trigger"]`,
},
context: { selector: contextSelector, closest: '[data-timeline-row="AssistantPart"]' },
following: {
@@ -89,7 +88,7 @@ test.describe("regression: session timeline context group resize", () => {
await page.waitForTimeout(delay)
}
await expect(context.locator('[data-component="tool-status-title"]')).toHaveAttribute("aria-label", "Explored")
await expect(context.getByRole("button")).toHaveAccessibleName("Used Read, Glob, Grep, List")
await page.waitForTimeout(700)
const trace = await stopVisualProbe<keyof typeof regions>(page)
const labels = trace.samples
@@ -108,7 +107,7 @@ test.describe("regression: session timeline context group resize", () => {
]),
)
expect(labels).toEqual(["Exploring", "Explored"])
expect(labels).toEqual(["Used Read, Glob, Grep, List"])
expect(issues, JSON.stringify(trace.samples, null, 2)).toEqual([])
})
})
@@ -209,13 +208,7 @@ function turn(index: number, target: boolean, status: "running" | "completed" =
const content: SessionMessageAssistant["content"] = target
? [
toolContent(
contextTool(
contextIDs[0]!,
assistantID,
"read",
{ path: "src/recent-a.ts", offset: 0, limit: 120 },
status,
),
contextTool(contextIDs[0]!, assistantID, "read", { path: "src/recent-a.ts", offset: 0, limit: 120 }, status),
),
toolContent(contextTool(contextIDs[1]!, assistantID, "glob", { path: directory, pattern: "**/*.ts" }, status)),
toolContent(
@@ -83,6 +83,7 @@ test("keeps an expanded file diff header at the same viewport position", async (
const before = Array.from({ length: 80 }, (_, index) => `export const value${index} = ${index}\n`).join("")
const after = before.replaceAll(" = ", " = compute(").replaceAll("\n", ")\n")
await setupTimeline(page, {
settings: { editToolPartsExpanded: true },
messages: [
userMessage([userText("Preceding context ".repeat(120))]),
assistantMessage([
@@ -26,7 +26,9 @@ for (const expanded of [false, true]) {
messages: [userMessage(), assistantMessage([shell(id, "completed", lines(3))])],
settings: { shellToolPartsExpanded: expanded },
})
const trigger = page.locator(`[data-timeline-part-id="${id}"] [data-slot="collapsible-trigger"]`)
const trigger = expanded
? page.locator(`[data-timeline-part-id="${id}"] [data-slot="collapsible-trigger"]`)
: page.getByRole("button", { name: "Used Shell" })
await expect(trigger).toHaveAttribute("aria-expanded", String(expanded))
await trigger.click()
await expect(trigger).toHaveAttribute("aria-expanded", String(!expanded))
@@ -1,12 +1,9 @@
import { expect, test } from "@playwright/test"
import { assistantMessage, setupTimeline, toolPart, userMessage } from "../performance/timeline-stability/fixture"
for (const profile of [
{ locale: "de", label: "Erkundung abgeschlossen" },
{ locale: "ar", label: "تم الاستكشاف" },
] as const) {
test(`projects translated context status in ${profile.locale}`, async ({ page }) => {
const ids = [`prt_locale_${profile.locale}_01_read`, `prt_locale_${profile.locale}_02_glob`]
for (const locale of ["de", "ar"] as const) {
test(`projects localized tool names with an English fallback in ${locale}`, async ({ page }) => {
const ids = [`prt_locale_${locale}_01_read`, `prt_locale_${locale}_02_glob`]
await setupTimeline(page, {
messages: [
userMessage(),
@@ -15,11 +12,12 @@ for (const profile of [
toolPart(ids[1]!, "glob", "completed", { path: ".", pattern: "**/*.ts" }),
]),
],
locale: profile.locale,
locale,
})
const group = page.locator(`[data-timeline-part-ids="${ids.join(",")}"]`)
await expect(group.locator('[data-component="tool-status-title"]')).toHaveAttribute("aria-label", profile.label)
await expect(page.locator("html")).toHaveAttribute("lang", profile.locale)
await expect(group.getByRole("button")).toHaveAccessibleName(/^Used /)
await expect(group.locator('[data-component="tag"]')).toHaveText("2")
await expect(page.locator("html")).toHaveAttribute("lang", locale)
})
}
@@ -53,9 +53,14 @@ test.describe("session timeline projection", () => {
]
await setupTimeline(page, { messages: [userMessage(), assistantMessage(parts)] })
await expect(
page.locator('[data-timeline-part-ids="prt_01_read,prt_02_glob,prt_03_grep,prt_04_list"]'),
).toBeVisible()
const first = page.locator(
'[data-timeline-part-ids="prt_01_read,prt_02_glob,prt_03_grep,prt_04_list,prt_webfetch,prt_websearch,prt_task,prt_bash,prt_edit,prt_write,prt_patch"]',
)
const second = page.locator('[data-timeline-part-ids="prt_skill,prt_custom"]')
await expect(first).toBeVisible()
await expect(second).toBeVisible()
await first.getByRole("button").click()
await second.getByRole("button").click()
for (const id of [
"prt_webfetch",
"prt_websearch",
@@ -78,8 +83,7 @@ test.describe("session timeline projection", () => {
await expect(patch.locator('[data-slot="message-part-title-filename"]')).toHaveCount(0)
await expect(patch.locator('[data-slot="message-part-actions"]')).toHaveCount(0)
const edit = page.locator('[data-timeline-part-id="prt_edit"]')
await expect(edit.locator('[data-component="apply-patch-tool"]')).toBeVisible()
await expect(edit.locator('[data-slot="basic-tool-tool-title"]')).toContainText("Edit")
await expect(edit).toContainText("Edit")
await expect(page.locator('[data-timeline-part-id="prt_todo"]')).toHaveCount(0)
})
@@ -87,6 +91,7 @@ test.describe("session timeline projection", () => {
const first = "prt_patch_first"
const second = "prt_patch_second"
const timeline = await setupTimeline(page, {
settings: { editToolPartsExpanded: true },
messages: [
userMessage(),
assistantMessage([
@@ -13,7 +13,7 @@ import {
userMessage,
} from "../performance/timeline-stability/fixture"
test("groups singleton and separated context operations at correct boundaries", async ({ page }) => {
test("groups every collapsed tool until visible text separates the stack", async ({ page }) => {
const parts = [
toolPart("prt_boundary_01_read", "read", "completed", { path: "src/a.ts" }),
textPart("prt_boundary_02_text", "Boundary text"),
@@ -25,9 +25,112 @@ test("groups singleton and separated context operations at correct boundaries",
await setupTimeline(page, { messages: [userMessage(), assistantMessage(parts)] })
await expect(page.locator('[data-timeline-part-ids="prt_boundary_01_read"]')).toBeVisible()
await expect(page.locator('[data-timeline-part-ids="prt_boundary_03_glob,prt_boundary_04_grep"]')).toBeVisible()
await expect(page.locator('[data-timeline-part-ids="prt_boundary_06_list"]')).toBeVisible()
await expect(page.locator('[data-timeline-row="AssistantPart"]')).toHaveCount(5)
const group = page.locator(
'[data-timeline-part-ids="prt_boundary_03_glob,prt_boundary_04_grep,prt_boundary_05_shell,prt_boundary_06_list"]',
)
await expect(group).toBeVisible()
await expect(group.getByRole("button")).toHaveAccessibleName("Used Glob, Grep, Shell, List")
await expect(group.locator('[data-component="tag"]')).toHaveText("4")
await expect(page.locator('[data-timeline-row="AssistantPart"]')).toHaveCount(3)
await expect(page.locator('[data-timeline-spacing="content"]')).toHaveCount(2)
await expect(page.locator('[data-timeline-spacing="content"]').nth(0)).toHaveCSS("padding-top", "16px")
})
test("expands a mixed collapsed tool stack without expanding its individual calls", async ({ page }) => {
const parts = [
shell("prt_stack_shell_1", "completed", "first"),
toolPart("prt_stack_explore", "subagent", "completed", {
agent: "explore",
description: "Inspect the project",
prompt: "Explore the project",
}),
toolPart("prt_stack_patch", "patch", "completed", { patchText: "Update src/value.ts" }),
shell("prt_stack_shell_2", "completed", "second"),
]
await setupTimeline(page, { messages: [userMessage(), assistantMessage(parts)] })
const group = page.locator(
'[data-timeline-part-ids="prt_stack_shell_1,prt_stack_explore,prt_stack_patch,prt_stack_shell_2"]',
)
const summary = group.getByRole("button", { name: "Used Shell, Explore, Patch" })
await expect(summary).toHaveAttribute("aria-expanded", "false")
await expect(summary).toHaveCSS("height", "28px")
await expect(group.locator('[data-component="tag"]')).toHaveText("4")
await summary.click()
await expect(summary).toHaveAttribute("aria-expanded", "true")
await expect(group.locator('[data-slot="context-tool-group-item"]')).toHaveCount(4)
await expect(group.locator('[data-timeline-part-id="prt_stack_shell_1"]')).toBeVisible()
await expect(group.locator('[data-timeline-part-id="prt_stack_patch"]')).toBeVisible()
await expect(group.locator('[data-component="context-tool-group-list"]')).toHaveCSS("row-gap", "8px")
const content = group.locator(':scope > [data-component="collapsible"] > [data-slot="collapsible-content"]')
await expect(content).toHaveCSS("margin-left", "0px")
await expect(content).toHaveCSS("padding-left", "12px")
await expect.poll(() => content.evaluate((element) => getComputedStyle(element, "::before").content)).toBe("none")
})
test("leaves tools expanded by settings outside the collapsed stack", async ({ page }) => {
const parts = [
shell("prt_expanded_shell", "completed", "expanded"),
toolPart("prt_collapsed_patch", "patch", "completed", { patchText: "Update src/value.ts" }),
toolPart("prt_collapsed_read", "read", "completed", { path: "src/value.ts" }),
]
await setupTimeline(page, {
messages: [userMessage(), assistantMessage(parts)],
settings: { shellToolPartsExpanded: true },
})
await expect(page.locator('[data-timeline-part-id="prt_expanded_shell"]')).toBeVisible()
const group = page.locator('[data-timeline-part-ids="prt_collapsed_patch,prt_collapsed_read"]')
await expect(group.getByRole("button", { name: "Used Patch, Read" })).toBeVisible()
await expect(group.locator('[data-component="tag"]')).toHaveText("2")
await expect(page.locator('[data-timeline-spacing="tool"]')).toHaveCSS("padding-top", "8px")
})
test("keeps failed search calls and their error cards inside the collapsed stack", async ({ page }) => {
const parts = [
toolPart(
"prt_error_glob",
"glob",
"error",
{ path: "C:/Users", pattern: "*.ts" },
{
error: "Invalid tool input",
},
),
toolPart(
"prt_error_grep",
"grep",
"error",
{ path: "C:/Users", pattern: "value" },
{
error: "Search timed out after 30 seconds",
},
),
]
await setupTimeline(page, { messages: [userMessage(), assistantMessage(parts)] })
const group = page.locator('[data-timeline-part-ids="prt_error_glob,prt_error_grep"]')
const summary = group.getByRole("button", { name: "Used Glob, Grep" })
await expect(group.locator('[data-component="tag"]')).toHaveText("2")
await summary.click()
await expect(group.locator('[data-kind="tool-error-card"]')).toHaveCount(2)
const glob = group.locator('[data-timeline-part-id="prt_error_glob"]')
await expect(glob).toContainText("Invalid tool input")
await expect(glob.locator('[data-component="tool-error-card-icon"]')).toBeVisible()
await expect(glob.locator('[data-component="tool-error-card-icon"] use')).toHaveAttribute(
"href",
"#opencode-v2-icon-circle-exclamation",
)
await expect
.poll(() =>
glob
.locator('[data-kind="tool-error-card"]')
.evaluate((element) => getComputedStyle(element, "::before").display),
)
.toBe("none")
await expect(group.locator('[data-timeline-part-id="prt_error_grep"]')).toContainText(
"Search timed out after 30 seconds",
)
})
test("reducer-hardening: converges when idle arrives before final part and message completion", async ({ page }) => {
@@ -21,6 +21,9 @@ test("renders every tool error outcome without leaking hidden tools", async ({ p
)
await setupTimeline(page, { messages: [userMessage(), assistantMessage(parts)] })
const group = page.locator(`[data-timeline-part-ids="${ordinary.map((_, index) => `prt_error_${index}`).join(",")}"]`)
await expect(group.locator('[data-component="tag"]')).toHaveText(String(ordinary.length))
await group.getByRole("button").click()
await expect(page.locator('[data-kind="tool-error-card"]')).toHaveCount(ordinary.length + 1)
await expect(page.getByText(/dismissed/i)).toBeVisible()
await expect(page.locator('[data-timeline-part-id="prt_todo_error"]')).toHaveCount(0)
@@ -33,6 +36,7 @@ test("transitions shell and question through running error outcomes", async ({ p
const shellID = "prt_transition_error_shell"
const questionID = "prt_transition_error_question"
const timeline = await setupTimeline(page, {
settings: { shellToolPartsExpanded: true },
messages: [
userMessage(),
assistantMessage(
@@ -44,7 +48,6 @@ test("transitions shell and question through running error outcomes", async ({ p
),
],
})
await timeline.waitForPart(shellID)
await expect(page.locator(`[data-timeline-part-id="${questionID}"]`)).toHaveCount(0)
await timeline.send(partUpdated(toolPart(shellID, "shell", "running", { command: "exit 1" })), 120)
await timeline.send(partUpdated(toolPart(questionID, "question", "running", questionInput())), 180)
@@ -68,6 +71,7 @@ test("preserves surviving grouped patch state when its first patch fails", async
const failed = "prt_grouped_patch_failed"
const surviving = "prt_grouped_patch_surviving"
const timeline = await setupTimeline(page, {
settings: { editToolPartsExpanded: true },
messages: [
userMessage(),
assistantMessage(
@@ -147,10 +151,12 @@ test("labels all web search provider variants", async ({ page }) => {
toolPart("prt_search_generic", "websearch", "completed", { query: "generic" }),
]
await setupTimeline(page, { messages: [userMessage(), assistantMessage(parts)] })
await page.getByRole("button", { name: "Used Parallel Web Search, Exa Web Search, Web Search" }).click()
await expect(page.getByRole("button", { name: /Parallel Web Search/ })).toBeVisible()
await expect(page.getByRole("button", { name: /Exa Web Search/ })).toBeVisible()
await expect(page.getByRole("button", { name: /^Web Search/ })).toBeVisible()
const tools = page.locator('[data-component="context-tool-group-list"]')
await expect(tools.getByRole("button", { name: /Parallel Web Search/ })).toBeVisible()
await expect(tools.getByRole("button", { name: /Exa Web Search/ })).toBeVisible()
await expect(tools.getByRole("button", { name: /^Web Search/ })).toBeVisible()
})
test("labels completed searches with result counts", async ({ page }) => {
@@ -201,6 +207,11 @@ test("labels skill tools from IDs and result metadata", async ({ page }) => {
],
})
const group = page.locator(`[data-timeline-part-ids="${pending},${completed}"]`)
await expect(group.getByRole("button")).toHaveAccessibleName("Used Skill")
await expect(group.locator('[data-component="tag"]')).toHaveText("2")
await group.getByRole("button").click()
for (const [id, name] of [
[pending, "frontend-design"],
[completed, "OpenCode"],
@@ -42,8 +42,7 @@ test("shows parent lineage while the child timeline loads", async ({ page }) =>
const release = Promise.withResolvers<void>()
await page.route(
(url) =>
url.pathname === `/api/session/${childID}/message` &&
url.port === (process.env.PLAYWRIGHT_SERVER_PORT ?? "4096"),
url.pathname === `/api/session/${childID}/message` && url.port === (process.env.PLAYWRIGHT_SERVER_PORT ?? "4096"),
async (route) => {
requested.resolve()
await release.promise
@@ -53,6 +52,7 @@ test("shows parent lineage while the child timeline loads", async ({ page }) =>
await page.goto(sessionHref(parentID))
await expectSessionTitle(page, parentTitle)
await page.getByRole("button", { name: "Used Explore" }).click()
await page.locator(`a[href="${sessionHref(childID)}"]`).click()
await Promise.all([requested.promise, expect(page).toHaveURL(sessionHref(childID))])
await Promise.all([
@@ -77,6 +77,7 @@ test("keeps the parent visible while the child session resolves", async ({ page
await page.goto(sessionHref(parentID))
await expectSessionTitle(page, parentTitle)
await page.getByRole("button", { name: "Used Explore" }).click()
await page.locator(`a[href="${sessionHref(childID)}"]`).click()
await requested.promise
await Promise.all([expect(page).toHaveURL(sessionHref(parentID)), expectSessionTitle(page, parentTitle)]).finally(
@@ -194,6 +195,7 @@ async function setup(page: Page, events?: () => OpenCodeEvent[]) {
async function openChildFromParent(page: Page) {
await page.goto(sessionHref(parentID))
await expectSessionTitle(page, parentTitle)
await page.getByRole("button", { name: "Used Explore" }).click()
const card = page.locator(`a[href="${sessionHref(childID)}"]`)
await expect(card).toBeVisible()
@@ -133,7 +133,7 @@ export function createNewSessionComposerAdapter(props: {
return {
adapter,
project: createComposerProjectControls({ draftId: props.draftID }),
project: createComposerProjectControls({ draftId: props.draftID, worktree: props.worktree }),
model,
ready: prompt.ready,
}
@@ -4,10 +4,11 @@ import { useGlobal, useServerCtx } from "@/runtime/server/runtime"
import { useServerSDK } from "@/runtime/server/client"
import { serverName, ServerConnection, useServers } from "@/runtime/server/registry"
import { useWorkspaceLocation } from "@/workspaces/location"
import { workspaceSelectionDestination } from "@/workspaces/paths"
import { useTabs } from "@/shell/tabs/tabs"
import type { PromptProjectControls } from "./selector"
export function createComposerProjectControls(props: { draftId: string }) {
export function createComposerProjectControls(props: { draftId: string; worktree: () => string }) {
const servers = useServers()
const serverSDK = useServerSDK()
const location = useWorkspaceLocation()
@@ -38,7 +39,7 @@ export function createComposerProjectControls(props: { draftId: string }) {
tabs.updateDraft(props.draftId, {
server: ServerConnection.key(connection),
directory: worktree,
worktree: undefined,
worktree: workspaceSelectionDestination(props.worktree(), location().directory),
branch: undefined,
})
}
@@ -5,6 +5,8 @@ import { useWorkspaceLocation } from "@/workspaces/location"
import { useServerSDK } from "@/runtime/server/client"
import { useData } from "@/runtime/server/current"
import { useSettings } from "@/settings/model"
import { useTabs } from "@/shell/tabs/tabs"
import { ServerConnection } from "@/runtime/server/registry"
import { normalizeProjectInfo } from "@/runtime/server/global-sync/utils"
import {
isWorkspaceDirectory,
@@ -12,6 +14,7 @@ import {
sameDirectory,
workspaceDefaultSelection,
workspaceDirectories,
workspaceSelectionDestination,
} from "@/workspaces/paths"
export function resolveNewSessionWorktree(input: {
@@ -57,6 +60,7 @@ export function createNewSessionWorkspaceController(input: {
const serverSDK = useServerSDK()
const data = useData()
const settings = useSettings()
const tabs = useTabs()
const [state, setState] = createStore({ search: "" })
const searchBranches = debounce((search: string) => setState("search", search.trim()), 100)
const currentProject = createMemo(() => {
@@ -121,7 +125,8 @@ export function createNewSessionWorkspaceController(input: {
const remember = (worktree = value()) => {
const project = currentProject()
if (!project) return
const local = worktree === "main" || sameDirectory(worktree, project.worktree)
tabs.initializeDraftWorktrees(ServerConnection.key(serverSDK.server), sdk().directory, fallback())
const local = workspaceSelectionDestination(worktree, project.worktree) === "main"
settings.workspaces.setLastUsed(serverSDK.scope, project.id, local ? "local" : "workspace")
}
@@ -141,6 +146,7 @@ export function createNewSessionWorkspaceController(input: {
set: (worktree: string) => {
input.setSelectedBranch(undefined)
input.setSelectedWorktree(normalizeNewSessionWorktree(worktree, sdk().directory, currentProject()?.worktree))
remember(worktree)
},
create: (branch: string) => {
input.setSelectedBranch(branch)
@@ -160,7 +166,10 @@ export function createNewSessionWorkspaceController(input: {
const loaded = branches.latest
const list = loaded?.directory === projectRoot() ? loaded.data : []
return [
...new Set([...list, ...(current && current.toLowerCase().includes(state.search.toLowerCase()) ? [current] : [])]),
...new Set([
...list,
...(current && current.toLowerCase().includes(state.search.toLowerCase()) ? [current] : []),
]),
].slice(0, 50)
},
searchBranches,
+1
View File
@@ -884,6 +884,7 @@ export const dict = {
"settings.section.desktop": "Desktop",
"settings.section.server": "Server",
"settings.backToApp": "Back to app",
"settings.tab.general": "General",
"settings.tab.preferences": "Preferences",
"settings.tab.shortcuts": "Shortcuts",
@@ -0,0 +1,54 @@
import { describe, expect, test } from "bun:test"
import type { SessionInboxInfo } from "@opencode-ai/client/promise"
import { queuedPromptRows } from "./queue"
const queued = [
{
id: "msg_original",
sessionID: "ses_1",
timeCreated: 1,
type: "user",
delivery: "queue",
payload: { text: "original" },
},
{
id: "msg_replacement",
sessionID: "ses_1",
timeCreated: 2,
type: "user",
delivery: "queue",
payload: { text: "edited" },
},
] satisfies SessionInboxInfo[]
describe("queuedPromptRows", () => {
test("keeps the edited prompt to one row while its replacement is admitted", () => {
expect(queuedPromptRows(queued, { original: "msg_original", replacement: "msg_replacement" })).toEqual([
{ id: "msg_replacement", text: "edited", attachments: false },
])
})
test("keeps the original visible until its replacement appears", () => {
expect(queuedPromptRows([queued[0]], { original: "msg_original", replacement: "msg_replacement" })).toEqual([
{ id: "msg_original", text: "original", attachments: false },
])
})
test("retains unrelated queue entries", () => {
expect(queuedPromptRows(queued)).toEqual([
{ id: "msg_original", text: "original", attachments: false },
{ id: "msg_replacement", text: "edited", attachments: false },
])
})
test("keeps other prompts visible while a mutation replaces the edited prompt", () => {
const other = { ...queued[0], id: "msg_other", payload: { text: "other" } }
expect(
queuedPromptRows([queued[0], other, queued[1]], { original: "msg_original", replacement: "msg_replacement" }),
).toEqual([
{ id: "msg_other", text: "other", attachments: false },
{ id: "msg_replacement", text: "edited", attachments: false },
])
})
})
+75 -37
View File
@@ -1,6 +1,8 @@
import { createEffect, createMemo, onCleanup, type Accessor } from "solid-js"
import { createStore } from "solid-js/store"
import { useMutation } from "@tanstack/solid-query"
import type { SessionInboxInfo } from "@opencode-ai/client/promise"
import { SessionMessage } from "@opencode-ai/schema/session-message"
import type { ComposerDelivery } from "@/composer/adapter"
import type { ComposerModel } from "@/composer/model"
import type { ComposerStateTarget } from "@/composer/submission-state"
@@ -34,39 +36,67 @@ export function createSessionQueue(input: {
const server = useServerSDK()
const location = useWorkspaceLocation()
const language = useLanguage()
const [state, setState] = createStore<{ editing?: { id: string; stash: EditStash }; busy: boolean }>({ busy: false })
const [state, setState] = createStore<{ editing?: { id: string; stash: EditStash } }>({})
const notify = () => showToast({ title: language.t("common.requestFailed") })
const mutation = useMutation(() => ({
mutationFn: async (
change:
| { type: "reorder"; inboxIDs: string[] }
| {
type: "edit"
inboxIDs: string[]
original: string
replacement: string
item: QueuedPrompt | undefined
prompt: Prompt
text: string
delivery: ComposerDelivery
},
) => {
if (change.type === "reorder") return rewrite(change.inboxIDs)
const replacement = await editedPromptInput(
input.sessionID,
location().directory,
change.item,
change.prompt,
change.text,
)
// Admit before cancelling so a failed replacement never discards the original.
const admitted = await data.session.prompt({
...replacement,
id: change.replacement,
delivery: change.delivery,
...(change.delivery === "queue" ? { resume: false } : {}),
})
await server.api.session.inbox.cancel({ sessionID: input.sessionID, inboxID: change.original })
cancelEdit()
if (change.delivery === "queue")
await rewrite(change.inboxIDs.map((id) => (id === change.original ? admitted.id : id)))
},
onError: notify,
onSettled: () => data.session.pending.sync(input.sessionID).catch(() => undefined),
}))
const queued = createMemo(() =>
data.session.pending
.list(input.sessionID)
.filter((item): item is QueuedPrompt => item.type === "user" && item.delivery === "queue"),
)
const rows = createMemo(() =>
queued().map((item) => ({
id: item.id,
text: queuedPromptText(item),
attachments: (item.payload.files?.length ?? 0) > 0,
})),
)
const rows = createMemo(() => {
const replacement = mutation.isPending ? mutation.variables : undefined
return queuedPromptRows(
queued(),
replacement?.type === "edit" && replacement.delivery === "queue" ? replacement : undefined,
)
})
createEffect(() => {
const editing = state.editing
if (!editing || state.busy || queued().some((item) => item.id === editing.id)) return
if (!editing || mutation.isPending || queued().some((item) => item.id === editing.id)) return
setState("editing", undefined)
})
onCleanup(() => cancelEdit())
const notify = () => showToast({ title: language.t("common.requestFailed") })
const run = (work: () => Promise<unknown>) => {
setState("busy", true)
return work()
.catch(() => notify())
.finally(async () => {
await data.session.pending.sync(input.sessionID).catch(() => undefined)
setState("busy", false)
})
}
const rewrite = async (inboxIDs: string[]) => {
const pending = await server.api.session.inbox.list({ sessionID: input.sessionID })
if (pending.some((item) => item.delivery === "queue" && item.type !== "user"))
@@ -108,12 +138,12 @@ export function createSessionQueue(input: {
return server.api.session.inbox.cancel({ sessionID: input.sessionID, inboxID: id }).catch(() => notify())
}
const reorder = (inboxIDs: string[]) => {
if (state.busy) return Promise.resolve()
return run(() => rewrite(inboxIDs))
if (mutation.isPending) return Promise.resolve()
return mutation.mutateAsync({ type: "reorder", inboxIDs }).catch(() => undefined)
}
const edit = (id: string) => {
if (state.busy) return false
if (mutation.isPending) return false
if (state.editing?.id === id) return true
const item = queued().find((entry) => entry.id === id)
if (!item) return false
@@ -147,25 +177,22 @@ export function createSessionQueue(input: {
}
const confirmEdit = (delivery: ComposerDelivery) => {
const editing = state.editing
if (!editing || state.busy) return
if (!editing || mutation.isPending) return
const prompt = clonePrompt(input.draft.current())
const text = prompt.map((part) => ("content" in part ? part.content : "")).join("")
if (!text.trim() && !prompt.some((part) => part.type === "image")) return cancelEdit()
const item = queued().find((entry) => entry.id === editing.id)
const pristine = item && text.trim() === queuedPromptText(item) && !prompt.some((part) => part.type === "image")
if (pristine && delivery === "queue") return cancelEdit()
const inboxIDs = queued().map((entry) => entry.id)
void run(async () => {
const replacement = await editedPromptInput(input.sessionID, location().directory, item, prompt, text)
// Admit before cancelling so a failed replacement never discards the original.
const admitted = await data.session.prompt({
...replacement,
delivery,
...(delivery === "queue" ? { resume: false } : {}),
})
await server.api.session.inbox.cancel({ sessionID: input.sessionID, inboxID: editing.id })
cancelEdit()
if (delivery === "queue") await rewrite(inboxIDs.map((id) => (id === editing.id ? admitted.id : id)))
mutation.mutate({
type: "edit",
inboxIDs: queued().map((entry) => entry.id),
original: editing.id,
replacement: SessionMessage.ID.create(),
item,
prompt,
text,
delivery,
})
}
const editFirst = () => {
@@ -187,7 +214,7 @@ export function createSessionQueue(input: {
cancelEdit,
editFirst,
rows,
busy: () => state.busy,
busy: () => mutation.isPending,
working: input.working,
steer,
remove,
@@ -204,6 +231,17 @@ export type SessionQueueView = Pick<
"rows" | "editing" | "working" | "busy" | "steer" | "remove" | "edit" | "reorder"
>
export function queuedPromptRows(items: QueuedPrompt[], replacement?: { original: string; replacement: string }) {
const replaced = replacement && items.some((item) => item.id === replacement.replacement)
return items
.filter((item) => !replaced || item.id !== replacement.original)
.map((item) => ({
id: item.id,
text: queuedPromptText(item),
attachments: (item.payload.files?.length ?? 0) > 0,
}))
}
export function queuedPromptText(item: QueuedPrompt) {
const display = item.payload.metadata?.["displayText"]
return typeof display === "string" && display.length > 0 ? display : item.payload.text
@@ -105,6 +105,8 @@ export function createTimelineController(input: { session: TimelineSessionSource
sessionMessages: projectedMessages,
status: input.session.data.status,
showReasoningSummaries: settings.general.showReasoningSummaries,
shellToolDefaultOpen: settings.general.shellToolPartsExpanded,
editToolDefaultOpen: settings.general.editToolPartsExpanded,
pendingUserMessageIDs,
})
const [pending, setPending] = createStore({ rename: false })
@@ -342,12 +342,11 @@ function MessageTimelineView(
const projection = props.data.projection
const sessionDirectory = createMemo(() => props.session.data.info()?.location.directory ?? sdk().directory)
const project = createMemo(() => {
const projectID = props.session.data.info()?.projectID
const value = projectID
? data.project.get(projectID)
: data.project.list().find((item) => containsDirectory(item.canonical, sessionDirectory()))
if (!value) return undefined
return { ...value, worktree: value.canonical, worktrees: [] }
const session = props.session.data.info()
const projects = server.ctx.sync.data.project
return session
? projectForSession(session, projects)
: projects.find((item) => containsDirectory(item.worktree, sessionDirectory()))
})
const workspaceSession = createMemo(() => isWorkspaceDirectory(project(), sessionDirectory()))
const showProjectIcon = () =>
@@ -388,7 +387,7 @@ function MessageTimelineView(
const pinned = createMemo(() => props.pinned)
const messageByID = projection.messageByID
const virtualized = createTimelineVirtualizer({
sessionKey: props.data.sessionKey,
sessionKey: () => `${server.key}/${props.data.sessionID()}`,
projection,
showHeader,
pinned,
@@ -8,6 +8,8 @@ export function createTimelineProjection(input: {
sessionMessages: Accessor<SessionMessageInfo[]>
status: Accessor<SessionStatus>
showReasoningSummaries: Accessor<boolean>
shellToolDefaultOpen: Accessor<boolean>
editToolDefaultOpen: Accessor<boolean>
pendingUserMessageIDs: Accessor<ReadonlySet<string>>
}) {
const sessionMessageByID = createMemo(
@@ -81,6 +83,8 @@ export function createTimelineProjection(input: {
input.showReasoningSummaries(),
input.status(),
input.pendingUserMessageIDs(),
input.shellToolDefaultOpen(),
input.editToolDefaultOpen(),
),
)
const activeMessageID = createMemo(() => projection().activeMessageID)
+3 -17
View File
@@ -1,24 +1,10 @@
import { onCleanup } from "solid-js"
import { useCommand } from "@/shell/commands/command"
import { useLanguage } from "@/runtime/i18n/language"
import { useDialog } from "@opencode-ai/ui/context/dialog"
import { useSettingsSurface } from "./surface"
export function useSettingsDialog(defaultValue?: string) {
const dialog = useDialog()
let run = 0
let dead = false
onCleanup(() => {
dead = true
})
return () => {
const current = ++run
void import("@/settings/shell").then((module) => {
if (dead || run !== current) return
void dialog.show(() => <module.DialogSettings defaultValue={defaultValue} />)
})
}
const settings = useSettingsSurface()
return () => settings.open(defaultValue)
}
export function useSettingsCommand() {
+105 -16
View File
@@ -5,6 +5,89 @@
height: 100%;
}
.settings-screen {
display: flex;
width: 100%;
height: 100%;
min-width: 0;
min-height: 0;
justify-content: center;
overflow: hidden;
background: var(--v2-background-bg-deep);
outline: none;
}
.settings-screen > .settings {
display: flex;
width: min(100%, 1048px);
min-width: 0;
}
.settings-screen
> .settings[data-component="tabs-v2"][data-variant="settings"][data-orientation="vertical"]
> [data-slot="tabs-v2-list"] {
width: 328px;
min-width: 328px;
padding-block: 48px;
padding-inline-start: 24px;
padding-inline-end: 104px;
border-inline-end: none;
background: transparent;
}
.settings-screen > .settings > .settings-panel {
flex: 1;
min-width: 0;
max-width: 720px;
}
.settings-screen .settings-tab-header {
padding: 48px 0 32px;
background: linear-gradient(to bottom, var(--v2-background-bg-deep) calc(100% - 24px), transparent);
}
.settings-screen .settings-tab-body {
padding-inline: 0;
}
.settings-nav {
display: flex;
width: 200px;
flex-direction: column;
gap: 16px;
}
.settings-back {
display: flex;
height: 28px;
align-items: center;
gap: 6px;
padding-inline: 6px;
border: 0;
border-radius: 4px;
background: transparent;
color: var(--v2-text-text-muted);
font: inherit;
line-height: var(--line-height-compact);
text-align: start;
cursor: pointer;
}
.settings-back:hover,
.settings-back:focus-visible {
background: var(--v2-background-bg-layer-03);
color: var(--v2-text-text-base);
}
.settings-back:focus-visible {
outline: 2px solid var(--v2-border-border-focus);
outline-offset: 2px;
}
[dir="rtl"] .settings-back-icon {
transform: scaleX(-1);
}
[data-component="dialog-v2"][data-variant="settings"] [data-slot="dialog-container"] {
background: var(--v2-background-bg-base);
}
@@ -172,12 +255,12 @@
width: 100%;
}
[data-component="dialog-v2"][data-variant="settings"] [data-component="select-v2-root"] {
:is([data-component="dialog-v2"][data-variant="settings"], .settings-screen) [data-component="select-v2-root"] {
width: fit-content;
max-width: 100%;
}
[data-component="dialog-v2"][data-variant="settings"] [data-component="button-v2"] {
:is([data-component="dialog-v2"][data-variant="settings"], .settings-screen) [data-component="button-v2"] {
width: fit-content;
max-width: 100%;
}
@@ -187,27 +270,33 @@
}
@media (max-width: 639px) {
.settings-screen .settings-nav {
width: 100%;
}
.settings-screen > .settings > .settings-panel {
padding-inline-end: 16px;
}
.settings-screen .settings-tab-header {
padding-top: 24px;
}
.settings[data-component="tabs-v2"][data-variant="settings"][data-orientation="vertical"]
> [data-slot="tabs-v2-list"] {
width: 144px;
min-width: 144px;
padding-inline: 8px;
}
}
.settings-nav-footer {
display: flex;
flex-direction: column;
gap: 8px;
padding: 4px 0 4px 4px;
user-select: none;
}
.settings-nav-footer > span {
font-size: 11px;
font-weight: 440;
line-height: 1;
color: var(--v2-text-text-faint);
.settings-screen
> .settings[data-component="tabs-v2"][data-variant="settings"][data-orientation="vertical"]
> [data-slot="tabs-v2-list"] {
width: 160px;
min-width: 160px;
padding-block: 24px;
padding-inline: 12px;
}
}
.settings-provider-row {
+35 -14
View File
@@ -1,9 +1,7 @@
import { Component, createEffect, createMemo, createSignal, startTransition } from "solid-js"
import { Dialog } from "@opencode-ai/ui/dialog"
import { Component, createEffect, createMemo, createSignal, onCleanup, onMount, startTransition } from "solid-js"
import { Tabs } from "@opencode-ai/ui/tabs"
import { Icon } from "@opencode-ai/ui/icon"
import { useLanguage } from "@/runtime/i18n/language"
import { usePlatform } from "@/runtime/platform/platform"
import { SettingsGeneral } from "./general/general"
import { SettingsAppearance } from "./appearance/appearance"
import { SettingsKeybinds } from "./keybinds/keybinds"
@@ -20,19 +18,32 @@ import { useLayout } from "@/shell/state/layout"
import { useTabs } from "@/shell/tabs/tabs"
import { useGlobal, useServerCtx } from "@/runtime/server/runtime"
import { ServerConnection, useServers } from "@/runtime/server/registry"
import { useCommand } from "@/shell/commands/command"
import { useSettingsSurface } from "./surface"
import "@/settings/settings.css"
export const DialogSettings: Component<{
export const SettingsScreen: Component<{
defaultValue?: string
}> = (props) => {
const language = useLanguage()
const platform = usePlatform()
const dialog = useDialog()
const command = useCommand()
const surface = useSettingsSurface()
const layout = useLayout()
const servers = useServers()
const tabs = useTabs()
const global = useGlobal()
const [tab, setTab] = createSignal(props.defaultValue ?? "general")
let root: HTMLDivElement | undefined
onMount(() => {
command.keybinds(false)
root?.focus({ preventScroll: true })
})
onCleanup(() => command.keybinds(true))
createEffect(() => setTab(props.defaultValue ?? "general"))
const server = createMemo(() => {
const route = layout.route()
switch (route.type) {
@@ -67,11 +78,22 @@ export const DialogSettings: Component<{
})
const showProviders = () => {
void dialog.show(() => <DialogSettings defaultValue="providers" />)
dialog.close()
setTab("providers")
}
return (
<Dialog size="x-large" variant="settings" class="settings-dialog">
<div
ref={root}
data-testid="settings-screen"
class="settings-screen"
tabIndex={-1}
onKeyDown={(event) => {
if (event.key !== "Escape" || event.defaultPrevented || dialog.active) return
event.preventDefault()
surface.close()
}}
>
<Tabs
orientation="vertical"
variant="settings"
@@ -80,7 +102,11 @@ export const DialogSettings: Component<{
class="settings"
>
<Tabs.List>
<div class="flex flex-col justify-between h-full w-full">
<div class="settings-nav">
<button type="button" class="settings-back" onClick={surface.close}>
<Icon name="arrow-left" size="small" class="settings-back-icon" />
<span>{language.t("settings.backToApp")}</span>
</button>
<div class="flex flex-col gap-4 w-full">
{/* Group 1: Preferences */}
<div class="flex flex-col gap-1 w-full">
@@ -134,11 +160,6 @@ export const DialogSettings: Component<{
</Tabs.Trigger>
</div>
</div>
<div class="settings-nav-footer">
<span>{language.t("app.name.desktop")}</span>
<span>v{platform.version}</span>
</div>
</div>
</Tabs.List>
@@ -175,6 +196,6 @@ export const DialogSettings: Component<{
</Tabs.Content>
</SettingsServerScope>
</Tabs>
</Dialog>
</div>
)
}
+32
View File
@@ -0,0 +1,32 @@
import { useLocation } from "@solidjs/router"
import { createEffect, on } from "solid-js"
import { createStore } from "solid-js/store"
import { createSimpleContext } from "@opencode-ai/ui/context"
export const { use: useSettingsSurface, provider: SettingsSurfaceProvider } = createSimpleContext({
name: "SettingsSurface",
gate: false,
init: () => {
const location = useLocation()
const [store, setStore] = createStore({ open: false, tab: "general" })
let focus: HTMLElement | undefined
const close = () => {
if (!store.open) return
setStore("open", false)
if (focus?.isConnected) focus.focus({ preventScroll: true })
focus = undefined
}
createEffect(on(() => `${location.pathname}${location.search}`, close, { defer: true }))
return {
store,
open(tab = "general") {
if (!store.open && document.activeElement instanceof HTMLElement) focus = document.activeElement
setStore({ open: true, tab })
},
close,
}
},
})
@@ -17,6 +17,7 @@ export const SettingsProjects: Component = () => {
const global = useGlobal()
const [allServers, setAllServers] = createSignal(true)
const selected = global.settings.server.selected
const multiple = createMemo(() => global.servers.list().length > 1)
const projects = createMemo(() => {
const server = selected()
if (!server) return []
@@ -41,7 +42,7 @@ export const SettingsProjects: Component = () => {
const name = () => displayName(props.project)
return (
<div
class="group flex items-center justify-between gap-5 px-4 py-2.5 rounded-lg bg-v2-background-bg-base shadow-[var(--v2-elevation-raised)] cursor-pointer transition-all hover:bg-v2-background-bg-layer-01"
class="group flex items-center justify-between gap-5 px-4 py-2.5 rounded-lg bg-v2-background-bg-base shadow-[var(--v2-elevation-raised)] transition-all hover:bg-v2-background-bg-layer-01"
onClick={() => openProjectSettings(props.project, props.server)}
>
<div class="flex items-center gap-2.5 min-w-0 flex-1">
@@ -72,14 +73,16 @@ export const SettingsProjects: Component = () => {
<h2 class="settings-tab-title">{language.t("settings.projects.title")}</h2>
<span class="text-11-regular text-v2-text-text-muted">{language.t("settings.projects.description")}</span>
</div>
<InlineServerSelect
all={{
label: language.t("settings.projects.server.all"),
selected: allServers,
onSelect: () => setAllServers(true),
}}
onServerSelect={() => setAllServers(false)}
/>
<Show when={multiple()}>
<InlineServerSelect
all={{
label: language.t("settings.projects.server.all"),
selected: allServers,
onSelect: () => setAllServers(true),
}}
onServerSelect={() => setAllServers(false)}
/>
</Show>
</div>
</div>
@@ -98,7 +101,14 @@ export const SettingsProjects: Component = () => {
>
<Show when={selected()} keyed>
{(server) => (
<For each={projects()}>{(project) => <ProjectRow project={project} server={server} />}</For>
<div class="settings-section">
<Show when={multiple()}>
<h3 class="settings-section-title">{serverName(server) || ServerConnection.key(server)}</h3>
</Show>
<div class="flex flex-col gap-2 w-full">
<For each={projects()}>{(project) => <ProjectRow project={project} server={server} />}</For>
</div>
</div>
)}
</Show>
</Show>
@@ -117,9 +127,11 @@ export const SettingsProjects: Component = () => {
<For each={groups()}>
{(group) => (
<div class="settings-section">
<h3 class="settings-section-title">
{serverName(group.server) || ServerConnection.key(group.server)}
</h3>
<Show when={multiple()}>
<h3 class="settings-section-title">
{serverName(group.server) || ServerConnection.key(group.server)}
</h3>
</Show>
<div class="flex flex-col gap-2 w-full">
<For each={group.projects}>
{(project) => <ProjectRow project={project} server={group.server} />}
@@ -12,6 +12,7 @@ import {
homeProjectDirectories,
homeSessionServerStatus,
latestRootSession,
projectForSession,
sortedRootSessions,
toggleHomeProjectSelection,
} from "./helpers"
@@ -167,6 +168,27 @@ describe("layout workspace helpers", () => {
expect(childSessionOnPath(list, "root", "other")).toBeUndefined()
})
test("keeps the enriched workspace inventory when matching a session by project id", () => {
const project = {
id: "project",
worktree: "/repo",
sandboxes: ["/workspaces/feature"],
worktrees: [{ directory: "/repo" }, { directory: "/workspaces/feature", strategy: "git" }],
}
expect(projectForSession(session({ id: "feature", directory: "/workspaces/feature/packages/app" }), [project])).toBe(
project,
)
})
test("finds the enriched project for a nested workspace when its session project id is stale", () => {
const project = { id: "updated", worktree: "/repo", sandboxes: ["/workspaces/feature"] }
expect(projectForSession(session({ id: "feature", directory: "/workspaces/feature/packages/app" }), [project])).toBe(
project,
)
})
test("formats fallback project display name", () => {
expect(displayName({ worktree: "/tmp/app" })).toBe("app")
expect(displayName({ worktree: "/tmp/app", name: "My App" })).toBe("My App")
+2 -5
View File
@@ -1,6 +1,7 @@
import { getFilename } from "@opencode-ai/util/path"
import type { SessionInfo } from "@opencode-ai/client/promise"
import { pathKey } from "@/workspaces/path-key"
import { isProjectDirectory } from "@/workspaces/paths"
import type { ServerConnection } from "@/runtime/server/registry"
import type { HomeProjectSelection } from "@/shell/state/layout"
@@ -100,11 +101,7 @@ export function projectForSession<T extends { id?: string; worktree: string; san
) {
const direct = byID.get(session.projectID)
if (direct) return direct
const directory = pathKey(session.location.directory)
return projects.find(
(project) =>
pathKey(project.worktree) === directory || project.sandboxes?.some((sandbox) => pathKey(sandbox) === directory),
)
return projects.find((project) => isProjectDirectory(project, session.location.directory))
}
export const errorMessage = (err: unknown, fallback: string) => {
+4 -1
View File
@@ -6,6 +6,7 @@ import { useGlobal } from "@/runtime/server/runtime"
import { ServerConnection } from "@/runtime/server/registry"
import { SessionPanelFrame, SessionRouteFrame } from "@/session/session-frame"
import { LayoutProvider } from "@/shell/state/layout"
import { SettingsSurfaceProvider } from "@/settings/surface"
import Shell from "@/shell/shell"
import { requireServerKey } from "./session"
@@ -69,7 +70,9 @@ function TargetServerRoute(props: ParentProps) {
function AppLayout(props: ParentProps) {
return (
<LayoutProvider>
<Shell>{props.children}</Shell>
<SettingsSurfaceProvider>
<Shell>{props.children}</Shell>
</SettingsSurfaceProvider>
</LayoutProvider>
)
}
+16 -1
View File
@@ -4,11 +4,14 @@ import { Titlebar, type TitlebarUpdate } from "@/shell/titlebar/titlebar"
import { usePlatform } from "@/runtime/platform/platform"
import { ToastRegion } from "@/shell/notifications/toast"
import { TitlebarRightProvider } from "@/shell/titlebar/right-slot"
import { useSettingsSurface } from "@/settings/surface"
const DebugBar = lazy(() => import("@/shell/debug/debug-bar").then((module) => ({ default: module.DebugBar })))
const SettingsScreen = lazy(() => import("@/settings/shell").then((module) => ({ default: module.SettingsScreen })))
export default function Layout(props: ParentProps) {
const platform = usePlatform()
const settings = useSettingsSurface()
const [state, setState] = createStore({ debugTools: false })
const update: TitlebarUpdate = {
@@ -41,7 +44,19 @@ export default function Layout(props: ParentProps) {
}
/>
<main class="flex-1 min-h-0 min-w-0 overflow-x-hidden flex flex-col items-start contain-strict">
<Suspense>{props.children}</Suspense>
<div
class="flex size-full min-h-0 min-w-0 flex-col"
hidden={settings.store.open}
inert={settings.store.open}
aria-hidden={settings.store.open}
>
<Suspense>{props.children}</Suspense>
</div>
<Show when={settings.store.open}>
<Suspense>
<SettingsScreen defaultValue={settings.store.tab} />
</Suspense>
</Show>
</main>
<Show when={import.meta.env.DEV && state.debugTools}>
<Suspense>
+8
View File
@@ -245,6 +245,14 @@ export const { use: useTabs, provider: TabsProvider } = createSimpleContext({
)
})
},
initializeDraftWorktrees(server: ServerConnection.Key, directory: string, worktree: string) {
setStore(
(tab) => tab.type === "draft" && tab.server === server && tab.directory === directory && !tab.worktree,
produce((tab) => {
if (tab.type === "draft") tab.worktree = worktree
}),
)
},
promoteDraft(draftID: string, session: Omit<SessionTab, "type">) {
// Keep the replacement and navigation atomic so /new-session never renders
// after its backing draft tab has been removed from the store.
+14
View File
@@ -8,6 +8,7 @@ import {
mergeWorkspaceSessionInventory,
sessionsForWorkspace,
workspaceInventory,
workspaceSelectionDestination,
} from "./paths"
describe("isWorkspaceDirectory", () => {
@@ -41,6 +42,19 @@ describe("isWorkspaceSelection", () => {
})
})
describe("workspaceSelectionDestination", () => {
test("preserves local intent for the main selection and project root", () => {
expect(workspaceSelectionDestination("main", "/repo")).toBe("main")
expect(workspaceSelectionDestination("/repo/", "/repo")).toBe("main")
expect(workspaceSelectionDestination("c:\\repo\\", "C:\\repo")).toBe("main")
})
test("preserves workspace intent without carrying project-specific paths", () => {
expect(workspaceSelectionDestination("create", "/repo")).toBe("create")
expect(workspaceSelectionDestination("/workspaces/feature", "/repo")).toBe("create")
})
})
test("groups and filters workspace inventory by project", () => {
const inventory = workspaceInventory([
{
+4
View File
@@ -106,6 +106,10 @@ export function isWorkspaceSelection(project: WorkspaceProject | undefined, sele
return isWorkspaceDirectory(project, selection)
}
export function workspaceSelectionDestination(selection: string, projectWorktree: string) {
return selection === "main" || sameDirectory(selection, projectWorktree) ? "main" : "create"
}
export function workspaceDefaultSelection(
setting: WorkspaceDefaultDestination,
lastUsed: WorkspaceLastUsed | undefined,
@@ -293,7 +293,7 @@ export type McpResourceTemplate = {
mimeType?: string
}
export type ProjectVcs = "git" | "hg"
export type ProjectVcs = string
export type ProjectIcon = { url?: string; override?: string; color?: string }
+7 -68
View File
@@ -4,12 +4,13 @@ import { Directory, Document, type Entry } from "@opencode-ai/schema/config"
import { ConfigPlugin } from "@opencode-ai/schema/config/plugin"
import { FSUtil } from "@opencode-ai/util/fs-util"
import { makeLocationNode } from "@opencode-ai/util/effect/app-node"
import { Context, Effect, Layer, Option, Predicate, PubSub, Schema, Scope, Stream } from "effect"
import { Context, Effect, Layer, Option, PubSub, Scope, Stream } from "effect"
import path from "path"
import { fileURLToPath } from "url"
import { Config } from "../../config.js"
import { Watcher } from "../../filesystem/watcher.js"
import { Location } from "../../location.js"
import { PluginSourceDirectory } from "../../plugin/source-directory.js"
export type Operation =
| {
@@ -124,7 +125,10 @@ const scan = Effect.fn("ConfigPluginSource.scan")(function* (
) {
const discovered = yield* Effect.forEach(
entries.filter((entry): entry is Directory => entry.type === "directory"),
(entry) => discoverDirectory(fs, entry.path),
(entry) =>
PluginSourceDirectory.discover(fs, entry.path).pipe(
Effect.map((targets) => targets.map((target): Operation => ({ type: "add", target, options: {} }))),
),
).pipe(Effect.map((items) => items.flat()))
const configured = entries
.filter((entry): entry is Document => entry.type === "document")
@@ -153,75 +157,10 @@ const scan = Effect.fn("ConfigPluginSource.scan")(function* (
})
})
const sourceDirectories = ["plugin", "plugins"] as const
const Package = Schema.Struct({
exports: Schema.optional(Schema.Unknown),
module: Schema.optional(Schema.Unknown),
main: Schema.optional(Schema.Unknown),
})
const decodePackage = Schema.decodeUnknownOption(Package)
function discoverDirectory(fs: FSUtil.Interface, directory: string) {
return Effect.gen(function* () {
const children = (yield* Effect.forEach(sourceDirectories, (source) =>
fs.readDirectoryEntries(path.join(directory, source)).pipe(
Effect.orElseSucceed(() => []),
Effect.map((entries) =>
entries.map((entry) => ({ ...entry, target: path.join(directory, source, entry.name) })),
),
),
))
.flat()
.sort((a, b) => (a.target < b.target ? -1 : a.target > b.target ? 1 : 0))
const targets = yield* Effect.forEach(children, (entry) => discoverChild(fs, entry))
return targets.flatMap(Option.toArray).map((target): Operation => ({ type: "add", target, options: {} }))
})
}
function discoverChild(fs: FSUtil.Interface, entry: FSUtil.DirEntry & { target: string }) {
return Effect.gen(function* () {
const source = entry.target.endsWith(".ts") || entry.target.endsWith(".js")
if (entry.type === "file" && source) return Option.some(entry.target)
if (entry.type === "directory") return yield* discoverPackage(fs, entry.target)
if (entry.type !== "symlink") return Option.none<string>()
if (source && (yield* fs.isFile(entry.target))) return Option.some(entry.target)
if (yield* fs.isDir(entry.target)) return yield* discoverPackage(fs, entry.target)
return Option.none<string>()
})
}
function discoverPackage(fs: FSUtil.Interface, directory: string) {
return Effect.gen(function* () {
const root = yield* fs.resolve(directory)
const manifest = yield* fs
.readJson(path.join(directory, "package.json"))
.pipe(Effect.map(decodePackage), Effect.orElseSucceed(Option.none))
const configured = Option.isSome(manifest)
? [manifest.value.exports, manifest.value.module, manifest.value.main].filter(Predicate.isString)
: []
return yield* Effect.findFirst(
[...configured, "index.ts", "index.js"]
.filter((entry) => !path.isAbsolute(entry))
.map((entry) => path.resolve(directory, entry))
.filter((entry) => FSUtil.contains(directory, entry)),
(entry) =>
fs
.isFile(entry)
.pipe(
Effect.flatMap((exists) =>
exists
? fs.resolve(entry).pipe(Effect.map((resolved) => FSUtil.contains(root, resolved)))
: Effect.succeed(false),
),
),
)
})
}
function isPluginSource(entries: readonly Entry[], file: string) {
return entries.some(
(entry) =>
entry.type === "directory" &&
sourceDirectories.some((directory) => FSUtil.contains(path.join(entry.path, directory), file)),
PluginSourceDirectory.names.some((directory) => FSUtil.contains(path.join(entry.path, directory), file)),
)
}
+1
View File
@@ -14,6 +14,7 @@ const FOLDERS = new Set([
".git",
".svn",
".hg",
".jj",
".vscode",
".idea",
".turbo",
+7 -2
View File
@@ -6,6 +6,7 @@ import { Context, Effect, Layer, Schema } from "effect"
import { FSUtil } from "@opencode-ai/util/fs-util"
import { Location } from "./location.js"
import { Project } from "./project.js"
import { ProjectMarkers } from "./project/markers.js"
import { AbsolutePath } from "./schema.js"
export const Kind = Schema.Literals(["file", "directory"])
@@ -64,6 +65,7 @@ const layer = Layer.effect(
Effect.gen(function* () {
const fs = yield* FSUtil.Service
const location = yield* Location.Service
const markers = yield* ProjectMarkers.Service
const resolve = Effect.fnUntraced(function* (input: ResolveInput) {
const absolute = path.resolve(location.directory, input.path)
@@ -90,7 +92,10 @@ const layer = Layer.effect(
directory: externalDirectory,
resource: externalResource,
save: slash(
path.join((yield* Project.root(fs, AbsolutePath.make(externalDirectory))) ?? externalDirectory, "*"),
path.join(
(yield* Project.root(fs, AbsolutePath.make(externalDirectory), markers.targets())) ?? externalDirectory,
"*",
),
),
},
} satisfies Target
@@ -103,5 +108,5 @@ const layer = Layer.effect(
export const node = makeLocationNode({
service: Service,
layer: layer.pipe(Layer.orDie),
deps: [FSUtil.node, Location.node],
deps: [FSUtil.node, Location.node, ProjectMarkers.node],
})
+2
View File
@@ -10,6 +10,7 @@ export { Info, Ref, response }
export interface Interface extends Info {
readonly vcs?: Project.Vcs
readonly vcsBackend?: string
}
export class Service extends Context.Service<Service, Interface>()("@opencode/Location") {}
@@ -27,6 +28,7 @@ const layer = (ref: Ref) =>
workspaceID: ref.workspaceID,
project: { id: resolved.id, directory: resolved.directory, canonical: resolved.canonical },
vcs: resolved.vcs,
vcsBackend: resolved.vcsBackend,
})
}),
)
+1
View File
@@ -442,6 +442,7 @@ export const make = Effect.fn("PluginHost.make")(function* (plugin: Interface, p
generate: (input) => runtime.session.generate(input).pipe(Effect.map((text) => ({ text }))),
command: runtime.session.command,
rename: runtime.session.rename,
move: runtime.session.move,
synthetic: runtime.session.synthetic,
interrupt: (input) =>
runtime.session
+3
View File
@@ -84,6 +84,7 @@ import { WebSearchPlugins } from "./websearch/index.js"
import { PluginRuntime } from "./runtime.js"
import { SkillPlugin } from "./skill.js"
import { VcsHgPlugin } from "./vcs/hg.js"
import { VcsJjPlugin } from "./vcs/jj.js"
import { SystemPromptPlugin } from "./system-prompt.js"
import { VariantPlugin } from "./variant.js"
import { VcsGitPlugin } from "./vcs/git.js"
@@ -238,6 +239,7 @@ const pre = [
MCPCodeModeExclusionPlugin.Plugin,
WellKnownPlugin.Plugin,
VcsGitPlugin.Plugin,
VcsJjPlugin.Plugin,
AgentPlugin.Plugin,
PlanPlugin.Plugin,
CommandPlugin.Plugin,
@@ -287,6 +289,7 @@ export const list = Effect.fn("PluginInternal.list")(function* () {
plugins.map(
(plugin): Plugin => ({
id: plugin.id,
vcs: plugin.vcs,
effect: (host) => plugin.effect(host).pipe(Effect.provide(context)),
}),
)
+62
View File
@@ -0,0 +1,62 @@
export * as PluginModule from "./module.js"
import type { Plugin } from "@opencode-ai/plugin/effect/plugin"
import { Npm } from "@opencode-ai/util/npm"
import { importModule } from "@opencode-ai/util/runtime-import"
import { Effect, Schema } from "effect"
import path from "path"
import { pathToFileURL } from "url"
import type { ConfigPluginSource } from "../config/plugin/source.js"
import type { Versioned } from "../plugin.js"
import { PluginPromise } from "./promise.js"
const Discovery = Schema.Struct({
id: Schema.optional(Schema.String),
markers: Schema.Array(Schema.String),
})
const Definition = Schema.Struct({
default: Schema.Union([
Schema.Struct({
id: Schema.String,
tui: Schema.optional(Schema.Boolean),
vcs: Schema.optional(Discovery),
effect: Schema.declare<Plugin["effect"]>((input): input is Plugin["effect"] => typeof input === "function"),
}),
Schema.Struct({
id: Schema.String,
tui: Schema.optional(Schema.Boolean),
vcs: Schema.optional(Discovery),
setup: Schema.declare<Parameters<typeof PluginPromise.fromPromise>[0]["setup"]>(
(input): input is Parameters<typeof PluginPromise.fromPromise>[0]["setup"] => typeof input === "function",
),
}),
]),
})
export const load = Effect.fn("PluginModule.load")(function* (
operation: Extract<ConfigPluginSource.Operation, { type: "add" }>,
) {
const npm = yield* Npm.Service
const entrypoint = path.isAbsolute(operation.target)
? pathToFileURL(operation.target).href
: (yield* npm.add(operation.target, { subpaths: ["server", ""], refresh: true })).entrypoint
if (!entrypoint) return yield* Effect.fail(new Error(`Plugin entrypoint not found: ${operation.target}`))
// Bun currently ignores query parameters when caching file:// imports.
const target = typeof Bun !== "undefined" ? operation.target.replaceAll("\\", "/") : entrypoint
const source = operation.mtime === undefined ? entrypoint : `${target}?mtime=${operation.mtime}`
yield* Effect.log({ msg: "loading plugin", id: operation.target, entrypoint: source })
const mod = yield* Effect.promise(() => importModule(source))
const value = (yield* Schema.decodeUnknownEffect(Definition)(mod)).default
const plugin = "effect" in value ? value : PluginPromise.fromPromise(value)
return {
id: plugin.id,
tui: plugin.tui,
vcs: plugin.vcs,
version: JSON.stringify(operation),
source: path.isAbsolute(operation.target)
? { type: "local" as const, path: operation.target }
: { type: "package" as const, package: operation.target },
effect: (host) => plugin.effect({ ...host, options: operation.options }),
} satisfies Versioned
})
+2
View File
@@ -20,6 +20,7 @@ export interface Interface {
| "generate"
| "command"
| "rename"
| "move"
| "resume"
| "switchAgent"
| "switchModel"
@@ -76,6 +77,7 @@ export const layerWithCell = (cell: Cell) =>
generate: (input) => require(cell, (runtime) => runtime.session.generate(input)),
command: (input) => require(cell, (runtime) => runtime.session.command(input)),
rename: (input) => require(cell, (runtime) => runtime.session.rename(input)),
move: (input) => require(cell, (runtime) => runtime.session.move(input)),
resume: (sessionID) => require(cell, (runtime) => runtime.session.resume(sessionID)),
switchAgent: (input) => require(cell, (runtime) => runtime.session.switchAgent(input)),
switchModel: (input) => require(cell, (runtime) => runtime.session.switchModel(input)),
@@ -0,0 +1,68 @@
export * as PluginSourceDirectory from "./source-directory.js"
import { FSUtil } from "@opencode-ai/util/fs-util"
import { Effect, Option, Predicate, Schema } from "effect"
import path from "path"
export const names = ["plugin", "plugins"] as const
const Package = Schema.Struct({
exports: Schema.optional(Schema.Unknown),
module: Schema.optional(Schema.Unknown),
main: Schema.optional(Schema.Unknown),
})
const decodePackage = Schema.decodeUnknownOption(Package)
export const discover = Effect.fn("PluginSourceDirectory.discover")(function* (
fs: FSUtil.Interface,
directory: string,
) {
const children = (yield* Effect.forEach(names, (source) =>
fs.readDirectoryEntries(path.join(directory, source)).pipe(
Effect.orElseSucceed(() => []),
Effect.map((entries) => entries.map((entry) => ({ ...entry, target: path.join(directory, source, entry.name) }))),
),
))
.flat()
.sort((a, b) => (a.target < b.target ? -1 : a.target > b.target ? 1 : 0))
const targets = yield* Effect.forEach(children, (entry) =>
Effect.gen(function* () {
const source = entry.target.endsWith(".ts") || entry.target.endsWith(".js")
if (entry.type === "file" && source) return Option.some(entry.target)
if (entry.type === "directory") return yield* packageEntry(fs, entry.target)
if (entry.type !== "symlink") return Option.none<string>()
if (source && (yield* fs.isFile(entry.target))) return Option.some(entry.target)
if (yield* fs.isDir(entry.target)) return yield* packageEntry(fs, entry.target)
return Option.none<string>()
}),
)
return targets.flatMap(Option.toArray)
})
function packageEntry(fs: FSUtil.Interface, directory: string) {
return Effect.gen(function* () {
const root = yield* fs.resolve(directory)
const manifest = yield* fs
.readJson(path.join(directory, "package.json"))
.pipe(Effect.map(decodePackage), Effect.orElseSucceed(Option.none))
const configured = Option.isSome(manifest)
? [manifest.value.exports, manifest.value.module, manifest.value.main].filter(Predicate.isString)
: []
return yield* Effect.findFirst(
[...configured, "index.ts", "index.js"]
.filter((entry) => !path.isAbsolute(entry))
.map((entry) => path.resolve(directory, entry))
.filter((entry) => FSUtil.contains(directory, entry)),
(entry) =>
fs
.isFile(entry)
.pipe(
Effect.flatMap((exists) =>
exists
? fs.resolve(entry).pipe(Effect.map((resolved) => FSUtil.contains(root, resolved)))
: Effect.succeed(false),
),
),
)
})
}
+3 -53
View File
@@ -1,41 +1,19 @@
export * as PluginSupervisor from "./supervisor.js"
export { Service, type Interface } from "./supervisor-service.js"
import type { Plugin as PluginDefinition } from "@opencode-ai/plugin/effect/plugin"
import { Event } from "@opencode-ai/schema/config"
import { Cause, Effect, Latch, Layer, Schema, Stream } from "effect"
import { Cause, Effect, Latch, Layer, Stream } from "effect"
import path from "path"
import { pathToFileURL } from "url"
import { ConfigPluginSource } from "../config/plugin/source.js"
import { makeLocationNode } from "@opencode-ai/util/effect/app-node"
import { Bus } from "../bus.js"
import { Npm } from "@opencode-ai/util/npm"
import { Plugin } from "../plugin.js"
import { PluginPromise } from "../plugin/promise.js"
import { PluginInternal } from "./internal.js"
import { PluginModule } from "./module.js"
import { SdkPlugins } from "./sdk.js"
import { importModule } from "@opencode-ai/util/runtime-import"
import { Service } from "./supervisor-service.js"
const PluginModule = Schema.Struct({
default: Schema.Union([
Schema.Struct({
id: Schema.String,
tui: Schema.optional(Schema.Boolean),
effect: Schema.declare<PluginDefinition["effect"]>(
(input): input is PluginDefinition["effect"] => typeof input === "function",
),
}),
Schema.Struct({
id: Schema.String,
tui: Schema.optional(Schema.Boolean),
setup: Schema.declare<Parameters<typeof PluginPromise.fromPromise>[0]["setup"]>(
(input): input is Parameters<typeof PluginPromise.fromPromise>[0]["setup"] => typeof input === "function",
),
}),
]),
})
const resolve = Effect.fn("PluginSupervisor.resolve")(function* (
pre: readonly Plugin.Versioned[],
post: readonly Plugin.Versioned[],
@@ -69,7 +47,7 @@ const resolve = Effect.fn("PluginSupervisor.resolve")(function* (
continue
}
const plugin = yield* load(operation).pipe(
const plugin = yield* PluginModule.load(operation).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("failed to load plugin", { target: operation.target, cause }).pipe(
Effect.as({ error: Cause.pretty(cause) }),
@@ -102,34 +80,6 @@ const resolve = Effect.fn("PluginSupervisor.resolve")(function* (
}
})
const load = Effect.fn("PluginSupervisor.load")(function* (
operation: Extract<ConfigPluginSource.Operation, { type: "add" }>,
) {
const npm = yield* Npm.Service
const entrypoint = path.isAbsolute(operation.target)
? pathToFileURL(operation.target).href
: (yield* npm.add(operation.target, { subpaths: ["server", ""], refresh: true })).entrypoint
if (!entrypoint) return yield* Effect.fail(new Error(`Plugin entrypoint not found: ${operation.target}`))
// Bun currently ignores query parameters when caching file:// imports.
const source =
operation.mtime === undefined
? entrypoint
: typeof Bun !== "undefined"
? `${operation.target.replaceAll("\\", "/")}?mtime=${operation.mtime}`
: `${entrypoint}?mtime=${operation.mtime}`
yield* Effect.log({ msg: "loading plugin", id: operation.target, entrypoint: source })
const mod = yield* Effect.promise(() => importModule(source))
const value = (yield* Schema.decodeUnknownEffect(PluginModule)(mod)).default
const plugin = "effect" in value ? value : PluginPromise.fromPromise(value)
return {
id: plugin.id,
tui: plugin.tui,
version: JSON.stringify(operation),
source: pluginSource(operation.target),
effect: (host) => plugin.effect({ ...host, options: operation.options }),
} satisfies Plugin.Versioned
})
export const layer = Layer.effect(
Service,
Effect.gen(function* () {
+8 -1
View File
@@ -8,11 +8,18 @@ import { BranchList, FileStatus, Info, Mode } from "@opencode-ai/schema/vcs"
import { AppProcess } from "@opencode-ai/util/process"
import { Location } from "../../location.js"
import type { Adapter, BranchOptions, DiffOptions } from "../../vcs.js"
import { chunksByFile, emptyPatch, MAX_PATCH_BYTES, MAX_TOTAL_PATCH_BYTES, PATCH_CONTEXT_LINES } from "../../vcs/patch.js"
import {
chunksByFile,
emptyPatch,
MAX_PATCH_BYTES,
MAX_TOTAL_PATCH_BYTES,
PATCH_CONTEXT_LINES,
} from "../../vcs/patch.js"
import type { Patch } from "../../vcs/patch.js"
export const Plugin = define({
id: "opencode.vcs.git",
vcs: { id: "git", markers: [".git"] },
effect: Effect.fn("VcsGitPlugin")(function* (ctx) {
const location = yield* Location.Service
if (location.vcs?.type !== "git") return
+1
View File
@@ -23,6 +23,7 @@ import {
export const Plugin = define({
id: "opencode.vcs.hg",
vcs: { id: "hg", markers: [".hg"] },
effect: Effect.fn("VcsHgPlugin")(function* (ctx) {
const location = yield* Location.Service
if (location.vcs?.type !== "hg") return
+136
View File
@@ -0,0 +1,136 @@
export * as VcsJjPlugin from "./jj.js"
import { Effect } from "effect"
import { ChildProcess } from "effect/unstable/process"
import { define } from "@opencode-ai/plugin/effect/plugin"
import { FileDiff } from "@opencode-ai/schema/file-diff"
import { BranchList, FileStatus, Info, Mode } from "@opencode-ai/schema/vcs"
import { AppProcess } from "@opencode-ai/util/process"
import { Location } from "../../location.js"
import { ProjectJj } from "../../project/jj.js"
import type { Adapter, BranchOptions, DiffOptions } from "../../vcs.js"
import { countPatch, emptyPatch, MAX_TOTAL_PATCH_BYTES, PATCH_CONTEXT_LINES, splitGitPatch } from "../../vcs/patch.js"
export const Plugin = define({
id: ProjectJj.id,
vcs: ProjectJj.vcs,
effect: Effect.fn("VcsJjPlugin")(function* (ctx) {
const location = yield* Location.Service
if (location.vcs?.type !== "jj" && location.vcsBackend !== "jj") return
const processes = yield* AppProcess.Service
const adapter = make(processes, location.directory)
yield* ctx.vcs.transform((draft) => {
draft.add({
id: "jj",
name: "Jujutsu",
info: () => adapter.info(),
branches: (input) => adapter.branches({ search: input.search, limit: input.limit }),
status: () => adapter.status(),
diff: (input) => adapter.diff(input.mode, { context: input.context }),
})
})
}),
})
function make(proc: AppProcess.Interface, directory: string): Adapter {
const run = Effect.fnUntraced(
function* (args: string[], options?: { metadata?: boolean; maxOutputBytes?: number }) {
const result = yield* proc.run(
ChildProcess.make(
"jj",
["--color", "never", "--no-pager", ...(options?.metadata ? ["--ignore-working-copy"] : []), ...args],
{ cwd: directory, extendEnv: true, stdin: "ignore" },
),
{ maxOutputBytes: options?.maxOutputBytes },
)
return {
exitCode: result.exitCode,
text: () => result.stdout.toString("utf8"),
truncated: result.stdoutTruncated || result.stderrTruncated,
}
},
Effect.orElseSucceed(() => ({ exitCode: 1, text: () => "", truncated: false })),
)
const bookmarks = Effect.fnUntraced(function* (revision?: string) {
const result = yield* run(
["bookmark", "list", ...(revision ? ["-r", revision] : []), "--sort", "name", "-T", 'name ++ "\\0"'],
{ metadata: true },
)
if (result.exitCode !== 0) return []
return result.text().split("\0").filter(Boolean)
})
const base = Effect.fnUntraced(function* () {
const trunk = (yield* bookmarks("trunk()"))[0]
if (trunk) return trunk
const list = yield* bookmarks()
if (list.includes("main")) return "main"
if (list.includes("master")) return "master"
return undefined
})
const changes = Effect.fnUntraced(function* (revision: string[], options?: DiffOptions) {
const listed = yield* run(["diff", ...revision, "-T", 'status ++ "\\t" ++ path ++ "\\0"', "."])
if (listed.exitCode !== 0) return []
const items = listed
.text()
.split("\0")
.filter(Boolean)
.flatMap((entry) => {
const separator = entry.indexOf("\t")
if (separator === -1) return []
const code = entry.slice(0, separator)
const file = entry.slice(separator + 1)
if (!file) return []
const status: FileStatus["status"] =
code === "added" || code === "copied" ? "added" : code === "removed" ? "deleted" : "modified"
return [{ file, status }]
})
if (items.length === 0) return []
const result = yield* run(
["diff", ...revision, "--git", "--context", String(options?.context ?? PATCH_CONTEXT_LINES), "."],
{ metadata: true, maxOutputBytes: MAX_TOTAL_PATCH_BYTES },
)
const patches = splitGitPatch({
text: result.exitCode === 0 ? result.text() : "",
truncated: result.truncated,
})
return items
.map((item, index) => {
const patch = patches[index] ?? emptyPatch(item.file)
return { ...item, patch, ...countPatch(patch) } satisfies FileDiff.Info
})
.toSorted((a, b) => a.file.localeCompare(b.file))
})
return {
info: Effect.fn("VcsJj.info")(function* () {
const [current, root] = yield* Effect.all([bookmarks("@"), base()], { concurrency: 2 })
return { branch: { current: current[0], default: root } } satisfies Info
}),
branches: Effect.fn("VcsJj.branches")(function* (options?: BranchOptions) {
const search = options?.search?.trim().toLowerCase()
return (yield* bookmarks())
.filter((bookmark) => !search || bookmark.toLowerCase().includes(search))
.slice(0, options?.limit) satisfies BranchList
}),
status: Effect.fn("VcsJj.status")(function* () {
return (yield* changes(["-r", "@"], { context: 0 })).map((item) => ({
file: item.file,
additions: item.additions,
deletions: item.deletions,
status: item.status,
}))
}),
diff: Effect.fn("VcsJj.diff")(function* (mode: Mode, options?: DiffOptions) {
if (mode === "working") return yield* changes(["-r", "@"], options)
const root = yield* base()
if (!root) return []
return yield* changes(["--from", `fork_point(${root} | @)`], options)
}),
}
}
+73 -18
View File
@@ -13,7 +13,9 @@ import { Git } from "./git.js"
import { AppProcess } from "@opencode-ai/util/process"
import { makeGlobalNode } from "@opencode-ai/util/effect/app-node"
import { Hash } from "@opencode-ai/util/hash"
import { ProjectMarkers } from "./project/markers.js"
import { ProjectSchema } from "./project/schema.js"
import { ProjectJj } from "./project/jj.js"
import { ProjectTable, upsertProject } from "./project/sql.js"
import { WorktreeTable } from "./worktree/sql.js"
@@ -42,11 +44,16 @@ export interface Resolved {
readonly directory: AbsolutePath
readonly canonical: AbsolutePath
readonly vcs?: Vcs
readonly vcsBackend?: string
}
// Keep this filesystem-only; permission checks use it and should not execute VCS commands.
export const root = Effect.fn("Project.root")(function* (fs: FSUtil.Interface, input: AbsolutePath) {
return yield* fs.up({ targets: [".git", ".hg"], start: input, mode: "first" }).pipe(
export const root = Effect.fn("Project.root")(function* (
fs: FSUtil.Interface,
input: AbsolutePath,
markers: readonly string[] = [".git", ".hg"],
) {
return yield* fs.up({ targets: [...markers], start: input, mode: "first" }).pipe(
Effect.map((matches) => (matches[0] ? AbsolutePath.make(path.dirname(matches[0])) : undefined)),
Effect.orElseSucceed(() => undefined),
)
@@ -90,6 +97,7 @@ const layer = Layer.effect(
Effect.gen(function* () {
const fs = yield* FSUtil.Service
const git = yield* Git.Service
const markers = yield* ProjectMarkers.Service
const proc = yield* AppProcess.Service
const bus = yield* Bus.Service
const db = (yield* Database.Service).db
@@ -120,7 +128,7 @@ const layer = Layer.effect(
directories.push({
projectID: project.id,
directory: project.directory,
strategy: project.vcs.type === "git" ? "git" : undefined,
strategy: project.vcs.type === "git" && project.vcsBackend !== "jj" ? "git" : undefined,
})
// A missing directory row means this directory's resolution is a new durable
// fact (copy.ts registers copy directories directly; those never strand
@@ -157,11 +165,11 @@ const layer = Layer.effect(
Effect.gen(function* () {
if (candidate.id === item.projectID) return false
if (!FSUtil.contains(directory, candidate.directory)) return false
const markers = yield* fs
.up({ targets: [".git", ".hg"], start: candidate.directory, stop: directory, mode: "first" })
const found = yield* fs
.up({ targets: [...markers.targets()], start: candidate.directory, stop: directory, mode: "first" })
.pipe(Effect.orElseSucceed(() => []))
if (!markers[0]) return false
return (yield* fs.resolve(path.dirname(markers[0]))) === directory
if (!found[0]) return false
return (yield* fs.resolve(path.dirname(found[0]))) === directory
}),
)
yield* bus.publish(
@@ -305,19 +313,35 @@ const layer = Layer.effect(
const resolve = Effect.fn("Project.resolve")(function* (input: AbsolutePath) {
const directory = AbsolutePath.make(yield* fs.resolve(input))
const marker = yield* fs.up({ targets: [".git", ".hg"], start: directory, mode: "first" }).pipe(
const marker = yield* markers.discover(directory)
const discovered = marker?.type === "jj" ? yield* ProjectJj.discover(fs, marker.marker) : undefined
const native = yield* fs.up({ targets: [".git", ".hg"], start: directory, mode: "first" }).pipe(
Effect.map((matches) => matches[0]),
Effect.orElseSucceed(() => undefined),
)
const repo =
marker && path.basename(marker) === ".git"
? yield* git.repo.discover(AbsolutePath.make(path.dirname(marker)))
const repository =
native && path.basename(native) === ".git"
? yield* git.repo.discover(AbsolutePath.make(path.dirname(native)))
: undefined
if (repo) {
const jj =
discovered &&
repository &&
repository.worktree !== discovered.directory &&
FSUtil.contains(discovered.directory, repository.worktree)
? undefined
: discovered
const backing =
jj && (!repository || repository.worktree !== jj.directory)
? yield* git.repo.discover(jj.canonical)
: repository
const repo = jj && backing?.worktree !== jj.canonical && backing?.worktree !== jj.directory ? undefined : backing
if (repo && (!marker || FSUtil.contains(marker.directory, repo.worktree) || jj?.canonical === repo.worktree)) {
const previous = yield* cached(repo.commonDirectory)
const id = (yield* remote(repo)) ?? previous ?? (yield* rootCommit(repo))
const canonical =
repo.gitDirectory === repo.commonDirectory
const workspace = jj && jj.directory !== repo.worktree
const canonical = workspace
? repo.worktree
: repo.gitDirectory === repo.commonDirectory
? repo.worktree
: yield* git.worktree.list(repo).pipe(
Effect.map((items) => items.find((item) => item.kind === "main")?.directory ?? repo.worktree),
@@ -326,14 +350,45 @@ const layer = Layer.effect(
return yield* persist({
previous,
id: id ?? ID.global,
directory: repo.worktree,
directory: workspace ? jj.directory : repo.worktree,
canonical,
vcs: { type: "git" as const, store: repo.commonDirectory },
...(marker && marker.directory === repo.worktree && marker.type !== "git" ? { vcsBackend: marker.type } : {}),
...(jj ? { vcsBackend: "jj" } : {}),
})
}
const hg = native && path.basename(native) === ".hg" ? yield* hgDiscover(AbsolutePath.make(native)) : undefined
if (hg && (!marker || FSUtil.contains(marker.directory, hg.directory))) {
return yield* persist({
...hg,
canonical: hg.directory,
...(marker?.directory === hg.directory && marker.type !== "hg" ? { vcsBackend: marker.type } : {}),
})
}
if (jj) {
const previous = yield* cached(jj.store)
return yield* persist({
previous,
id: previous ?? ID.make(Hash.fast(`jj-repository:${jj.store}`)),
directory: jj.directory,
canonical: jj.canonical,
vcs: { type: "jj", store: jj.store },
})
}
if (marker && marker.type !== "jj") {
const previous = yield* cached(marker.marker)
return yield* persist({
previous,
id: previous ?? ID.make(Hash.fast(`vcs-repository:${marker.type}:${marker.marker}`)),
directory: marker.directory,
canonical: marker.directory,
vcs: { type: marker.type, store: marker.marker },
})
}
const hg = marker && path.basename(marker) === ".hg" ? yield* hgDiscover(AbsolutePath.make(marker)) : undefined
if (hg) return yield* persist({ ...hg, canonical: hg.directory })
return yield* persist({
id: ID.make(Hash.fast(`directory:${directory}`)),
directory,
@@ -349,5 +404,5 @@ const layer = Layer.effect(
export const node = makeGlobalNode({
service: Service,
layer: layer,
deps: [Bus.node, Database.node, FSUtil.node, Git.node, AppProcess.node],
deps: [Bus.node, Database.node, FSUtil.node, Git.node, ProjectMarkers.node, AppProcess.node],
})
+30
View File
@@ -0,0 +1,30 @@
export * as ProjectJj from "./jj.js"
import path from "path"
import { Effect } from "effect"
import { FSUtil } from "@opencode-ai/util/fs-util"
import { AbsolutePath } from "../schema.js"
export const id = "opencode.vcs.jj"
export const vcs = { id: "jj", markers: [".jj"] }
export const discover = Effect.fn("ProjectJj.discover")(function* (fs: FSUtil.Interface, metadata: AbsolutePath) {
const reference = path.join(metadata, "repo")
const direct = yield* fs.isDir(reference)
const pointer = direct ? undefined : yield* fs.readFileString(reference).pipe(Effect.orElseSucceed(() => undefined))
if (!direct && !pointer?.trim()) return undefined
const store = yield* fs.realPath(pointer ? path.resolve(metadata, pointer.trim()) : reference).pipe(
Effect.map((value) => AbsolutePath.make(value)),
Effect.orElseSucceed(() => undefined),
)
if (!store || !(yield* fs.isDir(store))) return undefined
const directory = yield* fs.realPath(path.dirname(metadata)).pipe(
Effect.map((value) => AbsolutePath.make(value)),
Effect.orElseSucceed(() => undefined),
)
if (!directory) return undefined
return { directory, store, canonical: AbsolutePath.make(path.dirname(path.dirname(store))) }
})
+179
View File
@@ -0,0 +1,179 @@
export * as ProjectMarkers from "./markers.js"
import { FSUtil } from "@opencode-ai/util/fs-util"
import { Global } from "@opencode-ai/util/global"
import { Npm } from "@opencode-ai/util/npm"
import { makeGlobalNode } from "@opencode-ai/util/effect/app-node"
import { Context, Effect, Layer, Option } from "effect"
import { parse, type ParseError } from "jsonc-parser"
import path from "path"
import { fileURLToPath } from "url"
import type { ConfigPluginSource } from "../config/plugin/source.js"
import type { Versioned } from "../plugin.js"
import { PluginModule } from "../plugin/module.js"
import { PluginSourceDirectory } from "../plugin/source-directory.js"
import { SdkPlugins } from "../plugin/sdk.js"
import { AbsolutePath } from "../schema.js"
import { ProjectJj } from "./jj.js"
export interface Match {
readonly type: string
readonly directory: AbsolutePath
readonly marker: AbsolutePath
}
export interface Interface {
readonly discover: (directory: AbsolutePath) => Effect.Effect<Match | undefined>
readonly targets: () => readonly string[]
}
export class Service extends Context.Service<Service, Interface>()("@opencode/ProjectMarkers") {}
const layer = Layer.effect(
Service,
Effect.gen(function* () {
const fs = yield* FSUtil.Service
const global = yield* Global.Service
const npm = yield* Npm.Service
const sdk = yield* SdkPlugins.Service
const known = new Set([".git", ".hg", ...ProjectJj.vcs.markers])
const loaded = new Map<string, Versioned | undefined>()
const discover = Effect.fn("ProjectMarkers.discover")(function* (directory: AbsolutePath) {
const found = yield* fs
.up({ targets: [".opencode", "opencode.json", "opencode.jsonc"], start: directory })
.pipe(Effect.orElseSucceed(() => []))
const roots = [global.config, ...found.filter((value) => path.basename(value) === ".opencode").toReversed()]
const files = [
...["opencode.json", "opencode.jsonc"].map((name) => path.join(global.config, name)),
...found.filter((value) => path.basename(value) !== ".opencode").toReversed(),
...roots.slice(1).flatMap((root) => ["opencode.json", "opencode.jsonc"].map((name) => path.join(root, name))),
]
const automatic = yield* Effect.forEach(roots, (root) => PluginSourceDirectory.discover(fs, root)).pipe(
Effect.map((entries) => entries.flat()),
)
const configured = yield* Effect.forEach([...new Set(files)], (file) => read(fs, file)).pipe(
Effect.map((entries) => entries.flat()),
)
const operations = yield* Effect.forEach(
[
...automatic.map((target): ConfigPluginSource.Operation => ({ type: "add", target, options: {} })),
...configured,
],
(operation) => {
if (operation.type === "remove" || !path.isAbsolute(operation.target)) return Effect.succeed(operation)
return fs.stat(operation.target).pipe(
Effect.map((info) => ({
...operation,
mtime: Option.getOrElse(info.mtime, () => new Date(0)).getTime(),
})),
Effect.orElseSucceed(() => operation),
)
},
)
const declarations = new Map<string, { readonly id: string; readonly markers: readonly string[] }>([
[ProjectJj.id, ProjectJj.vcs],
])
for (const plugin of sdk.all()) {
if (!plugin.vcs) continue
declarations.set(plugin.id, { id: plugin.vcs.id ?? plugin.id, markers: plugin.vcs.markers })
}
for (const operation of operations) {
if (operation.type === "remove") {
for (const id of declarations.keys()) {
if (
operation.target === "*" ||
(operation.target.endsWith(".*") ? id.startsWith(operation.target.slice(0, -1)) : operation.target === id)
) {
declarations.delete(id)
}
}
continue
}
if (operation.target === "*" || operation.target.endsWith(".*") || operation.target.startsWith("opencode."))
continue
const key = JSON.stringify(operation)
const plugin = loaded.has(key)
? loaded.get(key)
: yield* PluginModule.load(operation).pipe(
Effect.provideService(Npm.Service, npm),
Effect.catchCause((cause) =>
Effect.logDebug("failed to discover plugin repository markers", {
target: operation.target,
cause,
}).pipe(Effect.as(undefined)),
),
Effect.tap((value) => Effect.sync(() => loaded.set(key, value))),
)
if (!plugin?.vcs) continue
declarations.set(plugin.id, { id: plugin.vcs.id ?? plugin.id, markers: plugin.vcs.markers })
}
const markers = new Map<string, string>()
for (const declaration of declarations.values()) {
if (!/^[a-z][a-z0-9._-]*$/.test(declaration.id)) continue
for (const marker of declaration.markers) {
if (!marker || marker === "." || marker === ".." || /[\\/]/.test(marker)) continue
known.add(marker)
markers.set(marker, declaration.id)
}
}
if (!markers.size) return undefined
const marker = yield* fs.up({ targets: [...markers.keys()], start: directory, mode: "first" }).pipe(
Effect.map((entries) => entries[0]),
Effect.orElseSucceed(() => undefined),
)
if (!marker) return undefined
const type = markers.get(path.basename(marker))
if (!type) return undefined
return {
type,
directory: AbsolutePath.make(path.dirname(marker)),
marker: AbsolutePath.make(marker),
} satisfies Match
})
return Service.of({ discover, targets: () => [...known] })
}),
)
function read(fs: FSUtil.Interface, file: string): Effect.Effect<ConfigPluginSource.Operation[]> {
return Effect.gen(function* () {
const source = yield* fs.readFileStringSafe(file).pipe(Effect.orElseSucceed(() => undefined))
if (!source) return []
const errors: ParseError[] = []
const document: unknown = parse(source, errors, { allowTrailingComma: true })
if (errors.length || typeof document !== "object" || document === null || !("plugins" in document)) return []
if (!Array.isArray(document.plugins)) return []
return document.plugins.flatMap<ConfigPluginSource.Operation>((entry) => {
if (typeof entry === "string" && entry.startsWith("-")) {
return [{ type: "remove", target: entry.slice(1) }]
}
if (
typeof entry !== "string" &&
(typeof entry !== "object" || entry === null || !("package" in entry) || typeof entry.package !== "string")
) {
return []
}
const target = typeof entry === "string" ? entry : entry.package
const options =
typeof entry !== "string" && "options" in entry && typeof entry.options === "object" && entry.options !== null
? Object.fromEntries(Object.entries(entry.options))
: {}
if (target.startsWith("file://")) return [{ type: "add", target: fileURLToPath(target), options }]
if (target.startsWith("./") || target.startsWith("../")) {
return [{ type: "add", target: path.resolve(path.dirname(file), target), options }]
}
return [{ type: "add", target, options }]
})
})
}
export const node = makeGlobalNode({
service: Service,
layer,
deps: [FSUtil.node, Global.node, Npm.node, SdkPlugins.node],
})
+4 -10
View File
@@ -18,14 +18,8 @@ export type UpdateInput = typeof UpdateInput.Type
export const Event = Project.Event
export const Vcs = Schema.Union([
Schema.Struct({
type: Schema.Literal("git"),
store: AbsolutePath,
}),
Schema.Struct({
type: Schema.Literal("hg"),
store: AbsolutePath,
}),
])
export const Vcs = Schema.Struct({
type: Project.Vcs,
store: AbsolutePath,
})
export type Vcs = typeof Vcs.Type
+1 -1
View File
@@ -12,7 +12,7 @@ type Transaction = Parameters<Parameters<DatabaseClient["transaction"]>[0]>[0]
export const ProjectTable = sqliteTable("project", {
id: text().$type<ProjectSchema.ID>().primaryKey(),
worktree: absoluteColumn().notNull(),
vcs: text().$type<"git" | "hg">(),
vcs: text().$type<ProjectSchema.Vcs["type"]>(),
name: text(),
icon_url: text(),
icon_url_override: text(),
-4
View File
@@ -95,10 +95,6 @@ export const layer = Layer.effect(
),
)
if (result.type === "complete") return
if (result.refreshLocation) {
const moved = yield* store.get(sessionID)
if (moved) yield* locations.invalidate(moved.location)
}
return yield* drain(sessionID, false, result.continuation, promotable)
})
}
+1 -1
View File
@@ -21,7 +21,7 @@ export type Continuation = { readonly step: number }
export type DrainResult =
| { readonly type: "complete" }
| { readonly type: "moved"; readonly continuation?: Continuation; readonly refreshLocation?: boolean }
| { readonly type: "moved"; readonly continuation?: Continuation }
/** Runs one local continuation from already-recorded Session history. */
export interface Interface {
+5 -25
View File
@@ -10,13 +10,10 @@ import {
type ProviderErrorEvent,
type ToolCall,
} from "@opencode-ai/ai"
import path from "path"
import { Cause, Config, Data, Effect, Exit, Fiber, FiberMap, Layer, Option, Pull, Schedule, Stream } from "effect"
import { Database } from "../../database/database.js"
import { Bus } from "../../bus.js"
import { Permission } from "../../permission.js"
import { Project } from "../../project.js"
import { RelativePath } from "../../schema.js"
import { QuestionTool } from "../../tool/plugin/question.js"
import { InstructionState } from "../instruction-state.js"
import { SessionCompaction } from "../compaction.js"
@@ -33,7 +30,6 @@ import { Service, type Continuation } from "./index.js"
import { createLLMEventPublisher, type StepRecord } from "./publish-llm-event.js"
import { Snapshot } from "../../snapshot.js"
import { makeLocationNode } from "@opencode-ai/util/effect/app-node"
import { FSUtil } from "@opencode-ai/util/fs-util"
import { llmClient } from "../../effect/app-node-platform.js"
import { StepFailedError } from "../error.js"
import { toSessionError } from "../to-session-error.js"
@@ -131,8 +127,6 @@ const layer = Layer.effect(
Service,
Effect.gen(function* () {
const bus = yield* Bus.Service
const fs = yield* FSUtil.Service
const projects = yield* Project.Service
const llm = yield* LLMClient.Service
const store = yield* SessionStore.Service
const context = yield* SessionContext.Service
@@ -198,8 +192,7 @@ const layer = Layer.effect(
force = false
continue
}
const moved = yield* runPendingMove(input.sessionID, "input")
if (moved) return { type: "moved" as const, ...moved }
if (yield* runPendingMove(input.sessionID, "input")) return { type: "moved" as const }
if (!force && !continuation && !(yield* SessionInbox.has(db, input.sessionID, promotable)))
return { type: "complete" as const }
const result = yield* runSteps(input.sessionID, continuation, promotable)
@@ -239,8 +232,7 @@ const layer = Layer.effect(
// steered compaction ends the turn instead of issuing an input-free model call.
while (true) {
if (yield* runPendingCompaction(sessionID, "steer")) continue
const moved = yield* runPendingMove(sessionID, "steer")
if (moved) return { type: "moved" as const, continuation: next, ...moved }
if (yield* runPendingMove(sessionID, "steer")) return { type: "moved" as const, continuation: next }
if (!first && !next && !(yield* SessionInbox.has(db, sessionID, "steer")))
return { type: "complete" as const }
const result = yield* runStep(sessionID, promotable, step)
@@ -688,16 +680,6 @@ const layer = Layer.effect(
Effect.gen(function* () {
const pending = yield* SessionInbox.nextPromotable(db, sessionID, promotable)
if (pending?.type !== "move") return false
const project = pending.payload.location.workspaceID
? undefined
: yield* projects.resolve(pending.payload.location.directory)
const subpath = project
? RelativePath.make(
path
.relative(project.directory, yield* fs.resolve(pending.payload.location.directory))
.replaceAll("\\", "/"),
)
: pending.payload.subpath
yield* modelTransport.close(sessionID)
yield* bus.publishAll([
[SessionEvent.InboxDelivered, { sessionID, inboxID: pending.id }],
@@ -706,12 +688,12 @@ const layer = Layer.effect(
{
sessionID,
location: pending.payload.location,
projectID: project?.id ?? pending.payload.projectID,
subpath,
projectID: pending.payload.projectID,
subpath: pending.payload.subpath,
},
],
])
return { refreshLocation: project !== undefined && project.id !== pending.payload.projectID }
return true
}),
)
})
@@ -750,8 +732,6 @@ export const node = makeLocationNode({
layer,
deps: [
Bus.node,
FSUtil.node,
Project.node,
llmClient,
SessionContext.node,
SessionModelRequest.node,
+1 -1
View File
@@ -73,7 +73,7 @@ const layer = Layer.effect(
})
const selected = () => {
const value = state.get()
const id = value.selection ?? vcs?.type
const id = value.selection ?? location.vcsBackend ?? vcs?.type
return id ? value.providers.get(id) : undefined
}
const protect = <A>(provider: VcsDefinition, operation: string, effect: Effect.Effect<A, unknown>, fallback: A) =>
@@ -22,6 +22,8 @@ test("parcel patterns ignore built-in folders at any depth", async () => {
"nested/node_modules/package/index.js",
"nested/.git",
"nested/.git/HEAD",
"nested/.jj",
"nested/.jj/repo/op_store/operations/current",
"nested/dist",
"nested/dist/index.js",
]) {
+1
View File
@@ -140,6 +140,7 @@ export function host(overrides: Overrides = {}): Plugin.Context {
generate: overrides.session?.generate ?? (() => Effect.die("unused session.generate")),
command: overrides.session?.command ?? (() => Effect.die("unused session.command")),
rename: overrides.session?.rename ?? (() => Effect.die("unused session.rename")),
move: overrides.session?.move ?? (() => Effect.die("unused session.move")),
synthetic: overrides.session?.synthetic ?? (() => Effect.die("unused session.synthetic")),
interrupt: overrides.session?.interrupt ?? (() => Effect.die("unused session.interrupt")),
wait: overrides.session?.wait ?? (() => Effect.die("unused session.wait")),
@@ -137,6 +137,7 @@ describe("fromPromise", () => {
switchAgent: (input) => Effect.sync(() => seen.push(input)),
switchModel: (input) => Effect.sync(() => seen.push(input)),
rename: (input) => Effect.sync(() => seen.push(input)),
move: (input) => Effect.sync(() => seen.push(input)),
wait: (input) => Effect.sync(() => seen.push(input)),
},
})
@@ -157,6 +158,9 @@ describe("fromPromise", () => {
}),
).toBeUndefined()
expect(await ctx.session.rename({ sessionID: "ses_success", title: "Renamed" })).toBeUndefined()
expect(
await ctx.session.move({ sessionID: "ses_success", directory: "/destination", delivery: "queue" }),
).toBeUndefined()
expect(await ctx.session.wait({ sessionID: "ses_success" })).toBeUndefined()
},
}),
@@ -169,6 +173,11 @@ describe("fromPromise", () => {
model: { providerID: Provider.ID.make("openai"), id: Model.ID.make("gpt-5") },
},
{ sessionID: Session.ID.make("ses_success"), title: "Renamed" },
{
sessionID: Session.ID.make("ses_success"),
directory: AbsolutePath.make("/destination"),
delivery: "queue",
},
{ sessionID: Session.ID.make("ses_success") },
])
}),
+258
View File
@@ -10,6 +10,7 @@ import { Database } from "@opencode-ai/core/database/database"
import { Project } from "@opencode-ai/core/project"
import { ProjectSchema } from "@opencode-ai/core/project/schema"
import { ProjectTable } from "@opencode-ai/core/project/sql"
import { WorktreeTable } from "@opencode-ai/core/worktree/sql"
import { AbsolutePath } from "@opencode-ai/core/schema"
import { Hash } from "@opencode-ai/util/hash"
import { tmpdir } from "./fixture/tmpdir"
@@ -170,6 +171,106 @@ describe("Project.resolve", () => {
}),
)
it.live("discovers repository markers from automatically loaded plugins", () =>
Effect.gen(function* () {
const tmp = yield* Effect.acquireRelease(
Effect.promise(() => tmpdir()),
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
)
yield* Effect.promise(async () => {
await fs.mkdir(path.join(tmp.path, ".opencode", "plugins"), { recursive: true })
await fs.mkdir(path.join(tmp.path, ".svn"))
await fs.mkdir(path.join(tmp.path, "nested", "directory"), { recursive: true })
await Bun.write(
path.join(tmp.path, ".opencode", "plugins", "svn.ts"),
'export default { id: "svn", vcs: { markers: [".svn"] }, setup() {} }',
)
})
const project = yield* Project.Service
const result = yield* project.resolve(abs(path.join(tmp.path, "nested", "directory")))
expect(result.directory).toBe(abs(tmp.path))
expect(result.canonical).toBe(abs(tmp.path))
expect(result.vcs).toEqual({ type: "svn", store: abs(path.join(tmp.path, ".svn")) })
expect(result.id).not.toBe(Project.ID.global)
expect((yield* project.list()).find((item) => item.id === result.id)?.vcs).toBe("svn")
}),
)
it.live("discovers repository markers from configured plugin files", () =>
Effect.gen(function* () {
const tmp = yield* Effect.acquireRelease(
Effect.promise(() => tmpdir()),
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
)
yield* Effect.promise(async () => {
await fs.mkdir(path.join(tmp.path, ".pijul"))
await Bun.write(path.join(tmp.path, "opencode.jsonc"), '{ "plugins": ["./pijul.ts"] }')
await Bun.write(
path.join(tmp.path, "pijul.ts"),
'export default { id: "custom.pijul", vcs: { id: "pijul", markers: [".pijul"] }, setup() {} }',
)
})
const project = yield* Project.Service
const result = yield* project.resolve(abs(tmp.path))
expect(result.directory).toBe(abs(tmp.path))
expect(result.vcs?.type).toBe("pijul")
}),
)
it.live("prefers a nested plugin repository over its parent git repository", () =>
Effect.gen(function* () {
const tmp = yield* Effect.acquireRelease(
Effect.promise(() => tmpdir()),
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
)
const nested = path.join(tmp.path, "nested")
yield* Effect.promise(async () => {
await initRepo(tmp.path, { commit: true })
await fs.mkdir(path.join(tmp.path, ".opencode", "plugins"), { recursive: true })
await fs.mkdir(path.join(nested, ".svn"), { recursive: true })
await Bun.write(
path.join(tmp.path, ".opencode", "plugins", "svn.ts"),
'export default { id: "svn", vcs: { markers: [".svn"] }, setup() {} }',
)
})
const project = yield* Project.Service
const result = yield* project.resolve(abs(nested))
expect(result.directory).toBe(abs(nested))
expect(result.vcs?.type).toBe("svn")
}),
)
it.live("preserves git identity when a plugin marker shares its repository", () =>
Effect.gen(function* () {
const tmp = yield* Effect.acquireRelease(
Effect.promise(() => tmpdir()),
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
)
yield* Effect.promise(async () => {
await initRepo(tmp.path, { commit: true })
await fs.mkdir(path.join(tmp.path, ".opencode", "plugins"), { recursive: true })
await fs.mkdir(path.join(tmp.path, ".jj"))
await Bun.write(
path.join(tmp.path, ".opencode", "plugins", "jj.ts"),
'export default { id: "jj", vcs: { markers: [".jj"] }, setup() {} }',
)
})
const project = yield* Project.Service
const result = yield* project.resolve(abs(tmp.path))
expect(result.id).toBe(Project.ID.make(yield* Effect.promise(() => rootCommit(tmp.path))))
expect(result.vcs?.type).toBe("git")
expect(result.vcsBackend).toBe("jj")
}),
)
it.live("repository markers override markerless directory projects", () =>
Effect.gen(function* () {
const tmp = yield* Effect.acquireRelease(
@@ -425,6 +526,163 @@ describe("Project.resolve", () => {
}),
)
const itJj = Bun.which("jj") ? it : { live: it.live.skip }
itJj.live("detects standalone Jujutsu repositories from nested directories", () =>
Effect.gen(function* () {
const tmp = yield* Effect.acquireRelease(
Effect.promise(() => tmpdir()),
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
)
yield* Effect.promise(async () => {
await $`jj git init --no-colocate`.cwd(tmp.path).quiet()
await fs.mkdir(path.join(tmp.path, "a", "b"), { recursive: true })
})
const project = yield* Project.Service
const result = yield* project.resolve(abs(path.join(tmp.path, "a", "b")))
expect(result.vcs?.type).toBe("jj")
expect(result.directory).toBe(yield* real(tmp.path))
expect(result.canonical).toBe(result.directory)
expect(result.id).not.toBe(Project.ID.global)
expect((yield* project.resolve(abs(tmp.path))).id).toBe(result.id)
}),
)
it.live("ignores incomplete Jujutsu metadata", () =>
Effect.gen(function* () {
const tmp = yield* Effect.acquireRelease(
Effect.promise(() => tmpdir()),
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
)
yield* Effect.promise(() => fs.mkdir(path.join(tmp.path, ".jj")))
const project = yield* Project.Service
expect((yield* project.resolve(abs(tmp.path))).vcs).toBeUndefined()
yield* Effect.promise(() => fs.writeFile(path.join(tmp.path, ".jj", "repo"), " \n"))
expect((yield* project.resolve(abs(tmp.path))).vcs).toBeUndefined()
yield* Effect.promise(() => fs.writeFile(path.join(tmp.path, ".jj", "repo"), "../missing"))
expect((yield* project.resolve(abs(tmp.path))).vcs).toBeUndefined()
yield* Effect.promise(() => initRepo(tmp.path, { commit: true }))
expect((yield* project.resolve(abs(tmp.path))).vcs?.type).toBe("git")
}),
)
itJj.live("preserves Git project identity in colocated Jujutsu repositories", () =>
Effect.gen(function* () {
const tmp = yield* Effect.acquireRelease(
Effect.promise(() => tmpdir()),
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
)
yield* Effect.promise(async () => {
await initRepo(tmp.path, { commit: true, remote: "git@github.com:owner/repo.git" })
await $`jj git init --colocate`.cwd(tmp.path).quiet()
})
const project = yield* Project.Service
const result = yield* project.resolve(abs(tmp.path))
expect(result.id).toBe(remoteID("github.com/owner/repo"))
expect(result.vcs?.type).toBe("git")
expect(result.directory).toBe(yield* real(tmp.path))
}),
)
itJj.live("shares standalone Jujutsu identity and canonical root across workspaces", () =>
Effect.gen(function* () {
const tmp = yield* Effect.acquireRelease(
Effect.promise(() => tmpdir()),
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
)
const main = path.join(tmp.path, "main")
const secondary = path.join(tmp.path, "secondary")
yield* Effect.promise(async () => {
await fs.mkdir(main)
await $`jj git init --no-colocate`.cwd(main).quiet()
await $`jj workspace add ${secondary}`.cwd(main).quiet()
})
const project = yield* Project.Service
const first = yield* project.resolve(abs(main))
const second = yield* project.resolve(abs(secondary))
expect(second.id).toBe(first.id)
expect(second.vcs?.type).toBe("jj")
expect(second.directory).toBe(yield* real(secondary))
expect(second.canonical).toBe(yield* real(main))
}),
)
itJj.live("shares colocated Git identity with secondary Jujutsu workspaces", () =>
Effect.gen(function* () {
const tmp = yield* Effect.acquireRelease(
Effect.promise(() => tmpdir()),
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
)
const main = path.join(tmp.path, "main")
const secondary = path.join(tmp.path, "secondary")
yield* Effect.promise(async () => {
await fs.mkdir(main)
await initRepo(main, { commit: true, remote: "git@github.com:owner/jj-workspaces.git" })
await $`jj git init --colocate`.cwd(main).quiet()
await $`jj workspace add ${secondary}`.cwd(main).quiet()
})
const project = yield* Project.Service
const first = yield* project.resolve(abs(main))
const second = yield* project.resolve(abs(secondary))
expect(second.id).toBe(first.id)
expect(second.vcs).toMatchObject({ type: "git" })
expect(second.vcsBackend).toBe("jj")
expect(second.directory).toBe(yield* real(secondary))
expect(second.canonical).toBe(yield* real(main))
const database = yield* Database.Service
const rows = yield* database.db.select().from(WorktreeTable).all()
expect(rows.find((item) => item.directory === second.directory)?.strategy).toBeNull()
}),
)
itJj.live("prefers a nested Jujutsu repository over its parent Git repository", () =>
Effect.gen(function* () {
const tmp = yield* Effect.acquireRelease(
Effect.promise(() => tmpdir()),
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
)
const nested = path.join(tmp.path, "nested")
yield* Effect.promise(async () => {
await initRepo(tmp.path, { commit: true })
await fs.mkdir(nested)
await $`jj git init --no-colocate`.cwd(nested).quiet()
})
const project = yield* Project.Service
const result = yield* project.resolve(abs(nested))
expect(result.vcs?.type).toBe("jj")
expect(result.directory).toBe(yield* real(nested))
}),
)
itJj.live("prefers a nested Git repository over its parent Jujutsu repository", () =>
Effect.gen(function* () {
const tmp = yield* Effect.acquireRelease(
Effect.promise(() => tmpdir()),
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
)
const nested = path.join(tmp.path, "nested")
yield* Effect.promise(async () => {
await $`jj git init --no-colocate`.cwd(tmp.path).quiet()
await fs.mkdir(nested)
await initRepo(nested, { commit: true })
})
const project = yield* Project.Service
const result = yield* project.resolve(abs(nested))
expect(result.vcs?.type).toBe("git")
expect(result.directory).toBe(yield* real(nested))
}),
)
it.live("prefers git when both git and mercurial metadata exist", () =>
Effect.gen(function* () {
const tmp = yield* Effect.acquireRelease(
+4 -44
View File
@@ -4,7 +4,6 @@ import { Database } from "@opencode-ai/core/database/database"
import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
import { LayerNode } from "@opencode-ai/util/effect/layer-node"
import { Bus } from "@opencode-ai/core/bus"
import { Location } from "@opencode-ai/core/location"
import { LocationServiceMap } from "@opencode-ai/core/location-service-map"
import type { LocationServices } from "@opencode-ai/core/location-services"
import { Project } from "@opencode-ai/core/project"
@@ -135,33 +134,6 @@ describe("SessionExecution lifecycle", () => {
}),
)
it.effect("rebuilds a moved destination after its project identity changes", () =>
Effect.gen(function* () {
const database = yield* Database.Service
const sessionID = Session.ID.make("ses_move_refresh")
yield* seedSessions(database, [sessionID])
const invalidated: string[] = []
const drained: string[] = []
const scope = yield* Scope.make()
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void))
const context = yield* buildExecution(
scope,
() =>
Effect.sync(() => {
drained.push("drained")
if (drained.length === 1) return { type: "moved" as const, refreshLocation: true }
}),
{ invalidated },
)
yield* Context.get(context, SessionExecution.Service).resume(sessionID)
expect(invalidated).toEqual(["/project"])
expect(drained).toHaveLength(2)
}),
)
it.effect("reports an idle interrupt as a no-op", () =>
Effect.gen(function* () {
const sessionID = Session.ID.make("ses_idle_cancel")
@@ -557,10 +529,8 @@ function attempts(database: Database.Service["Service"], sessionID: Session.ID)
/** Builds the local execution layer plus the restart actions against the test harness services. */
function buildExecution(
scope: Scope.Closeable,
drain: (
input: Parameters<SessionRunner.Interface["drain"]>[0],
) => Effect.Effect<void | SessionRunner.DrainResult, SessionRunner.RunError>,
options?: SessionRestart.Options & { readonly invalidated?: string[] },
drain: (input: Parameters<SessionRunner.Interface["drain"]>[0]) => Effect.Effect<void, SessionRunner.RunError>,
options?: SessionRestart.Options,
) {
return Effect.gen(function* () {
const database = yield* Database.Service
@@ -568,25 +538,15 @@ function buildExecution(
const store = yield* SessionStore.Service
const runner = Layer.succeed(
SessionRunner.Service,
SessionRunner.Service.of({
drain: (input) => drain(input).pipe(Effect.map((result) => result ?? { type: "complete" as const })),
}),
SessionRunner.Service.of({ drain: (input) => drain(input).pipe(Effect.as({ type: "complete" as const })) }),
)
const locations = Layer.effect(
LocationServiceMap.Service,
LayerMap.make(
(_location: Location.Ref) =>
() =>
// The local execution test only needs the Session runner from the Location graph.
// oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion
runner as unknown as Layer.Layer<LocationServices>,
).pipe(
Effect.map((map) => ({
...map,
invalidate: (location: Parameters<typeof map.invalidate>[0]) =>
map
.invalidate(location)
.pipe(Effect.tap(() => Effect.sync(() => options?.invalidated?.push(location.directory)))),
})),
),
)
return yield* Layer.buildWithScope(
+1 -100
View File
@@ -1,6 +1,4 @@
import { describe, expect, test } from "bun:test"
import fs from "fs/promises"
import path from "path"
import {
AIError,
LLMEvent,
@@ -30,7 +28,7 @@ import { EventTable } from "@opencode-ai/core/event/sql"
import { Project } from "@opencode-ai/core/project"
import { ProjectTable } from "@opencode-ai/core/project/sql"
import { Form } from "@opencode-ai/core/form"
import { AbsolutePath, RelativePath } from "@opencode-ai/core/schema"
import { AbsolutePath } from "@opencode-ai/core/schema"
import { Session } from "@opencode-ai/core/session"
import { Snapshot } from "@opencode-ai/core/snapshot"
import { SessionEvent } from "@opencode-ai/core/session/event"
@@ -41,7 +39,6 @@ import { SessionMessage } from "@opencode-ai/core/session/message"
import { SessionModelRequest } from "@opencode-ai/core/session/model-request"
import { SessionModelTransport } from "@opencode-ai/core/session/model-transport"
import { Money } from "@opencode-ai/schema/money"
import { Workspace } from "@opencode-ai/schema/workspace"
import { SessionProjector } from "@opencode-ai/core/session/projector"
import { SessionExecution } from "@opencode-ai/core/session/execution"
import { SessionRunCoordinator } from "@opencode-ai/core/session/run-coordinator"
@@ -84,8 +81,6 @@ import { TestClock } from "effect/testing"
import { HttpClientRequest, HttpClientResponse } from "effect/unstable/http"
import { asc, desc, eq } from "drizzle-orm"
import { testEffect } from "./lib/effect"
import { git } from "./fixture/git"
import { tmpdir } from "./fixture/tmpdir"
import { permissionLayer } from "./lib/permission"
import { agentHost, catalogHost, host } from "./plugin/host"
import { CodeModeInstructions } from "@opencode-ai/core/codemode/instructions"
@@ -445,7 +440,6 @@ const it = testEffect(
LayerNode.group([
Database.node,
Bus.node,
Project.node,
Form.node,
SessionProjector.node,
SessionStore.node,
@@ -1487,99 +1481,6 @@ describe("SessionRunnerLLM", () => {
}),
)
it.live("resolves a queued move's destination project when it is delivered", () =>
Effect.gen(function* () {
const session = yield* setup
const bus = yield* Bus.Service
const projects = yield* Project.Service
const db = (yield* Database.Service).db
const tmp = yield* Effect.acquireRelease(
Effect.promise(() => tmpdir()),
(directory) => Effect.promise(() => directory[Symbol.asyncDispose]()),
)
const root = path.join(tmp.path, "repository")
const alias = path.join(tmp.path, "alias")
const destination = AbsolutePath.make(path.join(alias, "packages", "app"))
yield* Effect.promise(() => fs.mkdir(path.join(root, "packages", "app"), { recursive: true }))
yield* Effect.promise(() => fs.symlink(root, alias, process.platform === "win32" ? "junction" : "dir"))
const previous = yield* projects.resolve(destination)
yield* SessionInbox.admit(db, bus, {
id: SessionMessage.ID.create(),
sessionID,
item: {
type: "move",
payload: {
location: Location.Ref.make({ directory: destination }),
projectID: previous.id,
subpath: RelativePath.make(""),
},
delivery: "queue",
},
})
yield* Effect.promise(() => git(root, "init"))
yield* Effect.promise(() =>
git(
root,
"-c",
"user.name=Test",
"-c",
"user.email=test@opencode.test",
"-c",
"commit.gpgsign=false",
"commit",
"--allow-empty",
"-m",
"root",
),
)
expect(yield* session.inbox(sessionID)).toMatchObject([{ payload: { projectID: previous.id } }])
yield* session.resume(sessionID)
const moved = yield* session.get(sessionID)
expect(moved).toMatchObject({
location: { directory: destination },
subpath: "packages/app",
})
expect(moved.projectID).not.toBe(previous.id)
expect(moved.projectID).toBe((yield* projects.resolve(destination)).id)
expect(yield* session.inbox(sessionID)).toEqual([])
}),
)
it.effect("preserves the admitted project when moving to an explicit workspace", () =>
Effect.gen(function* () {
const session = yield* setup
const bus = yield* Bus.Service
const db = (yield* Database.Service).db
yield* SessionInbox.admit(db, bus, {
id: SessionMessage.ID.create(),
sessionID,
item: {
type: "move",
payload: {
location: Location.Ref.make({
directory: AbsolutePath.make("/project"),
workspaceID: Workspace.ID.make("wrk_remote"),
}),
projectID: Project.ID.global,
subpath: RelativePath.make("remote/path"),
},
delivery: "queue",
},
})
yield* session.resume(sessionID)
expect(yield* session.get(sessionID)).toMatchObject({
projectID: Project.ID.global,
location: { directory: "/project", workspaceID: "wrk_remote" },
subpath: "remote/path",
})
}),
)
it.effect("preserves a tool continuation across a steered move", () =>
Effect.gen(function* () {
const session = yield* setup
+259
View File
@@ -0,0 +1,259 @@
import { $ } from "bun"
import { describe, expect } from "bun:test"
import fs from "fs/promises"
import path from "path"
import { Effect, Layer } from "effect"
import { LayerNode } from "@opencode-ai/util/effect/layer-node"
import { FSUtil } from "@opencode-ai/util/fs-util"
import { AppProcess } from "@opencode-ai/util/process"
import { Bus } from "@opencode-ai/core/bus"
import { Location } from "@opencode-ai/core/location"
import { AbsolutePath } from "@opencode-ai/core/schema"
import { Vcs } from "@opencode-ai/core/vcs"
import { VcsGitPlugin } from "@opencode-ai/core/plugin/vcs/git"
import { VcsJjPlugin } from "@opencode-ai/core/plugin/vcs/jj"
import { location } from "./fixture/location"
import { tmpdir } from "./fixture/tmpdir"
import { it } from "./lib/effect"
import { host } from "./plugin/host"
const describeJj = Bun.which("jj") ? describe : describe.skip
const provide = (directory: string, input: { worktree: string; colocated?: boolean }) =>
Effect.provide(
LayerNode.compile(LayerNode.group([Vcs.node, Bus.node, Location.node, AppProcess.node, FSUtil.node]), [
[
Location.node,
Layer.succeed(
Location.Service,
Location.Service.of({
...location(
{ directory: AbsolutePath.make(directory) },
{
projectDirectory: AbsolutePath.make(input.worktree),
vcs: input.colocated
? { type: "git", store: AbsolutePath.make(path.join(input.worktree, ".git")) }
: { type: "jj", store: AbsolutePath.make(path.join(input.worktree, ".jj", "repo")) },
},
),
...(input.colocated ? { vcsBackend: "jj" } : {}),
}),
),
],
]),
)
const withJj = <A, E, R>(
f: (directory: string) => Effect.Effect<A, E, R>,
options: { colocated?: boolean; nested?: string } = {},
) =>
Effect.acquireRelease(
Effect.promise(() => tmpdir()),
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
).pipe(
Effect.flatMap((tmp) =>
Effect.promise(async () => {
await jj(tmp.path, "git", "init", ...(options.colocated ? [] : ["--no-colocate"]))
if (options.nested) await fs.mkdir(path.join(tmp.path, options.nested), { recursive: true })
}).pipe(
Effect.andThen(
Effect.gen(function* () {
const vcs = yield* Vcs.Service
const context = host()
const scoped = { ...context, vcs: { ...context.vcs, transform: vcs.transform, reload: vcs.reload } }
if (options.colocated) yield* VcsGitPlugin.Plugin.effect(scoped)
yield* VcsJjPlugin.Plugin.effect(scoped)
return yield* f(tmp.path)
}).pipe(
provide(path.join(tmp.path, options.nested ?? ""), {
worktree: tmp.path,
colocated: options.colocated,
}),
),
),
),
),
)
async function jj(directory: string, ...args: string[]) {
await $`jj --quiet ${args}`.cwd(directory).quiet()
}
describeJj("Vcs jujutsu", () => {
it.live("reports modified, deleted, and added files", () =>
withJj((directory) =>
Effect.gen(function* () {
yield* Effect.promise(async () => {
await fs.writeFile(path.join(directory, "keep.txt"), "one\ntwo\n")
await fs.writeFile(path.join(directory, "gone.txt"), "bye\n")
await jj(directory, "commit", "-m", "initial")
await fs.writeFile(path.join(directory, "keep.txt"), "one\nthree\n")
await fs.rm(path.join(directory, "gone.txt"))
await fs.writeFile(path.join(directory, "new file.txt"), "hello\nworld\n")
})
const vcs = yield* Vcs.Service
expect(yield* vcs.status()).toEqual([
{ file: "gone.txt", additions: 0, deletions: 1, status: "deleted" },
{ file: "keep.txt", additions: 1, deletions: 1, status: "modified" },
{ file: "new file.txt", additions: 2, deletions: 0, status: "added" },
])
const diff = yield* vcs.diff("working")
expect(diff.map((item) => ({ file: item.file, status: item.status }))).toEqual([
{ file: "gone.txt", status: "deleted" },
{ file: "keep.txt", status: "modified" },
{ file: "new file.txt", status: "added" },
])
expect(diff[0].patch).toContain("-bye")
expect(diff[1].patch).toContain("+three")
expect(diff[2].patch).toContain("+hello")
}),
),
)
it.live("preserves patches and counts for filenames with tabs and newlines", () =>
withJj((directory) =>
Effect.gen(function* () {
yield* Effect.promise(async () => {
await fs.writeFile(path.join(directory, "line\nname.txt"), "first\nsecond\n")
await fs.writeFile(path.join(directory, "tab\tname.txt"), "third\n")
})
const vcs = yield* Vcs.Service
expect(yield* vcs.status()).toEqual([
{ file: "line\nname.txt", additions: 2, deletions: 0, status: "added" },
{ file: "tab\tname.txt", additions: 1, deletions: 0, status: "added" },
])
const diff = yield* vcs.diff("working")
expect(diff[0].patch).toContain("+first")
expect(diff[1].patch).toContain("+third")
}),
),
)
it.live("preserves rename destinations and their patches", () =>
withJj((directory) =>
Effect.gen(function* () {
yield* Effect.promise(async () => {
await fs.writeFile(path.join(directory, "before.txt"), "one\ntwo\n")
await jj(directory, "commit", "-m", "initial")
await fs.rename(path.join(directory, "before.txt"), path.join(directory, "after.txt"))
})
const vcs = yield* Vcs.Service
const diff = yield* vcs.diff("working")
expect(diff).toMatchObject([{ file: "after.txt", status: "modified", additions: 0, deletions: 0 }])
expect(diff[0].patch).toContain("rename to after.txt")
}),
),
)
it.live("prefers Jujutsu over Git in colocated repositories", () =>
withJj(
(directory) =>
Effect.gen(function* () {
yield* Effect.promise(async () => {
await fs.writeFile(path.join(directory, "file.txt"), "initial\n")
await jj(directory, "commit", "-m", "initial")
await jj(directory, "bookmark", "create", "feature", "-r", "@")
})
const vcs = yield* Vcs.Service
yield* vcs.reload()
expect(yield* vcs.info()).toEqual({ branch: { current: "feature", default: undefined } })
expect(yield* vcs.branches()).toEqual(["feature"])
}),
{ colocated: true },
),
)
it.live("lists and filters bookmarks without inventing an active bookmark", () =>
withJj((directory) =>
Effect.gen(function* () {
yield* Effect.promise(async () => {
await fs.writeFile(path.join(directory, "file.txt"), "initial\n")
await jj(directory, "commit", "-m", "initial")
await jj(directory, "bookmark", "create", "main", "-r", "@-")
await jj(directory, "bookmark", "create", "feature-one", "feature-two", "-r", "@-")
})
const vcs = yield* Vcs.Service
yield* vcs.reload()
expect(yield* vcs.info()).toEqual({ branch: { current: undefined, default: "main" } })
expect(yield* vcs.branches()).toEqual(["feature-one", "feature-two", "main"])
expect(yield* vcs.branches({ search: "FEATURE", limit: 1 })).toEqual(["feature-one"])
expect(yield* vcs.branches({ search: "*" })).toEqual([])
}),
),
)
it.live("uses the configured trunk bookmark instead of an unrelated main bookmark", () =>
withJj((directory) =>
Effect.gen(function* () {
yield* Effect.promise(async () => {
await fs.writeFile(path.join(directory, "file.txt"), "initial\n")
await jj(directory, "commit", "-m", "initial")
await jj(directory, "bookmark", "create", "main", "-r", "@-")
await fs.writeFile(path.join(directory, "file.txt"), "initial\nnext\n")
await jj(directory, "commit", "-m", "develop")
await jj(directory, "bookmark", "create", "develop", "-r", "@-")
await jj(directory, "config", "set", "--repo", 'revset-aliases."trunk()"', "develop")
})
const vcs = yield* Vcs.Service
yield* vcs.reload()
expect((yield* vcs.info()).branch.default).toBe("develop")
}),
),
)
it.live("scopes status and diffs to nested directories", () =>
withJj(
(directory) =>
Effect.gen(function* () {
yield* Effect.promise(async () => {
await fs.writeFile(path.join(directory, "outside.txt"), "outside\n")
await fs.writeFile(path.join(directory, "nested", "inside.txt"), "inside\n")
})
const vcs = yield* Vcs.Service
expect(yield* vcs.status()).toEqual([
{ file: "nested/inside.txt", additions: 1, deletions: 0, status: "added" },
])
expect((yield* vcs.diff("working")).map((item) => item.file)).toEqual(["nested/inside.txt"])
}),
{ nested: "nested" },
),
)
it.live("respects the diff context option", () =>
withJj((directory) =>
Effect.gen(function* () {
const body = Array.from({ length: 20 }, (_, index) => `line-${index}`).join("\n") + "\n"
yield* Effect.promise(async () => {
await fs.writeFile(path.join(directory, "file.txt"), body)
await jj(directory, "commit", "-m", "initial")
await fs.writeFile(path.join(directory, "file.txt"), body.replace("line-10", "changed"))
})
const vcs = yield* Vcs.Service
expect((yield* vcs.diff("working"))[0].patch).toContain("line-0")
const tight = yield* vcs.diff("working", { context: 1 })
expect(tight[0].patch).toContain("line-9")
expect(tight[0].patch).not.toContain("line-0")
}),
),
)
it.live("compares a change against the main bookmark fork point", () =>
withJj((directory) =>
Effect.gen(function* () {
yield* Effect.promise(async () => {
await fs.writeFile(path.join(directory, "file.txt"), "one\n")
await jj(directory, "commit", "-m", "initial")
await jj(directory, "bookmark", "create", "main", "-r", "@-")
})
const vcs = yield* Vcs.Service
expect(yield* vcs.diff("branch")).toEqual([])
yield* Effect.promise(() => fs.writeFile(path.join(directory, "file.txt"), "one\ntwo\n"))
const diff = yield* vcs.diff("branch")
expect(diff.map((item) => ({ file: item.file, status: item.status }))).toEqual([
{ file: "file.txt", status: "modified" },
])
expect(diff[0].patch).toContain("+two")
}),
),
)
})
+2
View File
@@ -1,6 +1,7 @@
import type { GenerateApi, PluginApi } from "@opencode-ai/client/effect/api"
import type { Effect, Scope } from "effect"
import type { PluginOptions } from "../options.js"
import type { VcsDiscovery } from "../vcs.js"
import type { App } from "../app.js"
import type { AgentDomain } from "./agent.js"
import type { AISDKDomain } from "./aisdk.js"
@@ -45,6 +46,7 @@ export interface Context {
export interface Plugin<R = Scope.Scope> {
readonly id: string
readonly tui?: boolean
readonly vcs?: VcsDiscovery
readonly effect: (context: Context) => Effect.Effect<void, never, R>
}
+1
View File
@@ -57,6 +57,7 @@ export type SessionDomain = Pick<
| "synthetic"
| "interrupt"
| "rename"
| "move"
| "wait"
| "context"
> & {
+2
View File
@@ -69,6 +69,7 @@ export function fromPromise(plugin: Plugin) {
return define({
id: plugin.id,
tui: plugin.tui,
vcs: plugin.vcs,
effect: (host) =>
Effect.gen(function* () {
const [{ ClientApi }, { OpenCodeEvent }] = yield* Effect.promise(() =>
@@ -366,6 +367,7 @@ export function fromPromise(plugin: Plugin) {
synthetic: adaptApiMethod(SessionEndpoints["session.synthetic"], host.session.synthetic),
interrupt: adaptApiMethod(SessionEndpoints["session.interrupt"], host.session.interrupt),
rename: adaptApiMethod(SessionEndpoints["session.rename"], host.session.rename),
move: adaptApiMethod(SessionEndpoints["session.move"], host.session.move),
wait: adaptApiMethod(SessionEndpoints["session.wait"], host.session.wait),
context: adaptApiMethod(SessionEndpoints["session.context"], host.session.context),
},
+2
View File
@@ -1,5 +1,6 @@
import type { GenerateApi, PluginApi } from "@opencode-ai/client/promise/api"
import type { PluginOptions } from "../options.js"
import type { VcsDiscovery } from "../vcs.js"
import type { App } from "../app.js"
import type { AgentDomain } from "./agent.js"
import type { AISDKDomain } from "./aisdk.js"
@@ -46,6 +47,7 @@ export type Cleanup = () => Promise<void> | void
export interface Plugin {
readonly id: string
readonly tui?: boolean
readonly vcs?: VcsDiscovery
readonly setup: (context: Context) => Promise<Cleanup | void> | Cleanup | void
}
+1
View File
@@ -57,6 +57,7 @@ export type SessionDomain = Pick<
| "synthetic"
| "interrupt"
| "rename"
| "move"
| "wait"
| "context"
> & {
+4
View File
@@ -0,0 +1,4 @@
export interface VcsDiscovery {
readonly id?: string
readonly markers: readonly string[]
}
@@ -1,4 +1,5 @@
import { expect, test } from "bun:test"
import { Effect } from "effect"
import { Agent } from "@opencode-ai/schema/agent"
import { Command } from "@opencode-ai/schema/command"
import { Connection } from "@opencode-ai/schema/connection"
@@ -49,6 +50,13 @@ test.each([
])
})
test.each([
["effect", Plugin.Plugin.define({ id: "svn", vcs: { markers: [".svn"] }, effect: () => Effect.void })],
["promise", PromisePlugin.Plugin.define({ id: "svn", vcs: { markers: [".svn"] }, setup() {} })],
])("%s plugin definitions retain repository markers", (_name, plugin) => {
expect(plugin.vcs).toEqual({ markers: [".svn"] })
})
test("tui entrypoint exposes the plugin definition", () => {
const plugin = TuiPlugin.Plugin.define({ id: "demo", setup() {} })
expect(plugin.id).toBe("demo")
+3 -1
View File
@@ -8,7 +8,9 @@ import { ProjectID } from "./project-id.js"
export const ID = ProjectID
export type ID = typeof ID.Type
export const Vcs = Schema.Literals(["git", "hg"]).annotate({ identifier: "Project.Vcs" })
export const Vcs = Schema.String.check(Schema.isPattern(/^[a-z][a-z0-9._-]*$/)).annotate({
identifier: "Project.Vcs",
})
export const Current = Schema.Struct({
id: ID,
directory: AbsolutePath,
@@ -284,19 +284,7 @@
[data-component="collapsible"].tool-collapsible:not([data-rail="false"]) {
> [data-slot="collapsible-content"] {
position: relative;
margin-inline-start: 12px;
padding-inline-start: 16px;
&::before {
content: "";
position: absolute;
inset-inline-start: 0;
top: 0;
bottom: 12px;
width: 0.5px;
background-color: var(--v2-border-border-muted, rgba(0, 0, 0, 0.08));
}
padding-inline-start: 12px;
}
}
@@ -263,6 +263,10 @@
}
}
[data-timeline-row="AssistantPart"][data-timeline-spacing="content"] [data-component="text-part"] {
margin-top: 0;
}
[data-component="reasoning-part"] {
width: 100%;
color: var(--v2-text-text-muted);
@@ -663,28 +667,66 @@
cursor: default;
[data-slot="context-tool-group-title"] {
display: flex;
align-items: center;
gap: 8px;
flex-shrink: 1;
min-width: 0;
}
[data-slot="context-tool-group-prefix"] {
flex-shrink: 0;
color: var(--v2-text-text-muted);
font-family: var(--v2-font-family-sans);
font-size: 13px;
font-weight: 440;
line-height: var(--line-height-compact);
letter-spacing: -0.04px;
}
[data-slot="basic-tool-tool-title"] {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
[data-component="tag"] {
flex-shrink: 0;
border: 0;
background: var(--v2-background-bg-layer-03);
}
[data-slot="collapsible-arrow"] {
color: var(--icon-weaker);
cursor: pointer;
}
}
[data-component="collapsed-tool-group"] > [data-component="collapsible"].tool-collapsible {
--tool-content-gap: 8px;
}
[data-component="context-tool-group-list"] {
/* The 28px compact trigger centers a 16px line box, already leaving 6px above this list. */
padding: 4px 0 0 12px;
padding: 0;
display: flex;
flex-direction: column;
/* 16px line boxes with 13px gaps reproduce the design's 29px row pitch for 13px solid rows. */
gap: 13px;
gap: 8px;
[data-slot="context-tool-group-item"] {
min-width: 0;
min-height: 28px;
display: flex;
flex-direction: column;
justify-content: center;
padding: 0;
opacity: 0.8;
> [data-component="tool-part-wrapper"] {
width: 100%;
}
> [data-component="tool-part-wrapper"] > [data-component="collapsible"] > [data-slot="collapsible-trigger"] {
height: 28px;
}
[data-slot="basic-tool-tool-info-structured"] {
gap: 6px;
@@ -4,7 +4,7 @@
--card-pad-r: 0px;
&::before {
border-radius: 0;
display: none;
}
/* Figma's leading-none would clip Inter descenders at 13px; keep the compact metric. */
@@ -97,8 +97,7 @@ export function ToolErrorCard(props: ToolErrorCardProps) {
<div data-component="tool-trigger">
<div data-slot="basic-tool-tool-trigger-content">
<span data-slot="basic-tool-tool-indicator" data-component="tool-error-card-icon">
{/* 20px-viewBox path at 16px: 1.25 renders the 1px stroke Figma specifies. */}
<Icon name="circle-ban-sign" style={{ "stroke-width": 1.25 }} />
<Icon name="circle-exclamation" />
</span>
<div data-slot="basic-tool-tool-info">
<div data-slot="basic-tool-tool-info-structured">
@@ -26,7 +26,8 @@ describe("current content default open", () => {
test("uses the file-change disclosure preference", () => {
expect(currentContentDefaultOpen(tool("edit"), false, true)).toBe(true)
expect(currentContentDefaultOpen(tool("write"), false, false)).toBe(false)
expect(currentContentDefaultOpen(tool("patch"), false, false)).toBe(true)
expect(currentContentDefaultOpen(tool("patch"), false, false)).toBe(false)
expect(currentContentDefaultOpen(tool("patch"), false, true)).toBe(true)
})
test("collapses errored tools regardless of disclosure preferences", () => {
@@ -38,7 +38,7 @@ export function currentContentDefaultOpen(
// Errored tools render the error card, which starts collapsed.
if (content.state.status === "error") return false
if (content.name === "shell" || content.name === "execute") return shellExpanded
if (content.name === "patch") return true
if (content.name === "patch") return editExpanded
if (content.name !== "edit" && content.name !== "write") return undefined
if (!editExpanded) return false
const files = currentToolMetadata(content).files
+51 -11
View File
@@ -8,6 +8,7 @@ import type {
} from "@opencode-ai/client/promise"
import { Option, Schema } from "effect"
import { createMemo, type Accessor } from "solid-js"
import { currentContentDefaultOpen } from "../message/current-tool-state"
import { TimelineRow, type PartGroup, type PartRef, type TimelineRowMap } from "./timeline-row"
export { TimelineRow, type PartGroup, type PartRef, type TimelineRowMap }
@@ -18,13 +19,14 @@ type Content = SessionMessageAssistant["content"][number]
type GroupRow = Extract<TimelineRow.TimelineRow, { _tag: "AssistantPart" }>
type PriorGroup = { index: number; row: GroupRow }
const contextTools = new Set(["read", "glob", "grep", "list"])
const decodeJson = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown))
export type TimelineProjectionInput = {
sessionMessages: SessionMessageInfo[]
status: SessionStatus
showReasoningSummaries: boolean
shellToolDefaultOpen?: boolean
editToolDefaultOpen?: boolean
pendingUserMessageIDs?: ReadonlySet<string>
previousRows?: TimelineRow.TimelineRow[]
}
@@ -36,6 +38,8 @@ export function createTimelineProjection(input: TimelineProjectionInput) {
input.showReasoningSummaries,
input.status,
input.pendingUserMessageIDs,
input.shellToolDefaultOpen ?? false,
input.editToolDefaultOpen ?? false,
)
const rows = reuseTimelineRows(input.previousRows, projection.rows)
const rowByKey = new Map(rows.map((row) => [TimelineRow.key(row), row] as const))
@@ -67,6 +71,8 @@ export function createReactiveTimelineProjection(input: {
sessionMessages: Accessor<SessionMessageInfo[]>
status: Accessor<SessionStatus>
showReasoningSummaries: Accessor<boolean>
shellToolDefaultOpen?: Accessor<boolean>
editToolDefaultOpen?: Accessor<boolean>
pendingUserMessageIDs?: Accessor<ReadonlySet<string>>
}) {
const sessionMessageByID = createMemo(
@@ -80,6 +86,8 @@ export function createReactiveTimelineProjection(input: {
input.showReasoningSummaries(),
input.status(),
input.pendingUserMessageIDs?.(),
input.shellToolDefaultOpen?.() ?? false,
input.editToolDefaultOpen?.() ?? false,
),
)
const activeMessageID = createMemo(() => projection().activeMessageID)
@@ -128,6 +136,8 @@ export namespace Timeline {
showReasoning: boolean,
status: SessionStatus,
pendingUserMessageIDs?: ReadonlySet<string>,
shellToolDefaultOpen = false,
editToolDefaultOpen = false,
) {
type Turn = {
id: string
@@ -204,6 +214,8 @@ export namespace Timeline {
showReasoning,
status,
turn.id === activeMessageID,
shellToolDefaultOpen,
editToolDefaultOpen,
)
}),
],
@@ -218,6 +230,8 @@ export namespace Timeline {
showReasoning: boolean,
status: SessionStatus,
isActive: boolean,
shellToolDefaultOpen = false,
editToolDefaultOpen = false,
) {
const rows: TimelineRow.TimelineRow[] = []
const assistantMessages = entries.flatMap((entry) => (entry.type === "assistant" ? [entry.message] : []))
@@ -237,6 +251,7 @@ export namespace Timeline {
if (userMessage) rows.push(new TimelineRow.UserMessage({ userMessageID: turnID }))
let assistantGroupIndex = 0
let previousAssistantTool = false
// An assistant message can produce several rows because its content parts are
// rendered separately. Notices end a segment so none of those rows cross it.
const appendAssistantSegment = (messages: SessionMessageAssistant[]) => {
@@ -248,17 +263,23 @@ export namespace Timeline {
const interruptedAt = messages.findIndex((message) => isInterrupted(message.error))
const before = interruptedAt < 0 ? refs : refs.filter((ref) => ref.messageIndex <= interruptedAt)
const after = interruptedAt < 0 ? [] : refs.filter((ref) => ref.messageIndex > interruptedAt)
const appendGroups = (items: typeof refs) =>
groupContent(items).forEach((group) => {
const appendGroups = (items: typeof refs) => {
let offset = 0
groupContent(items, shellToolDefaultOpen, editToolDefaultOpen).forEach((group) => {
const tool = group.type !== "part" || items[offset]?.content.type === "tool"
offset += group.type === "part" ? 1 : group.refs.length
rows.push(
new TimelineRow.AssistantPart({
userMessageID: turnID,
group,
previousAssistantPart: assistantGroupIndex > 0,
spacing: assistantGroupIndex > 0 ? (previousAssistantTool && tool ? "tool" : "content") : undefined,
}),
)
assistantGroupIndex += 1
previousAssistantTool = tool
})
}
appendGroups(before)
if (interruptedAt >= 0) {
@@ -444,6 +465,7 @@ function stabilizeGroupKey(
return new TimelineRow.AssistantPart({
userMessageID: row.userMessageID,
previousAssistantPart: row.previousAssistantPart,
spacing: row.spacing,
group: { ...row.group, key: existing.row.group.key },
})
}
@@ -462,7 +484,11 @@ function renderable(content: Content, showReasoning: boolean) {
return true
}
function groupContent(items: { messageID: string; partID: string; content: Content }[]): PartGroup[] {
function groupContent(
items: { messageID: string; partID: string; content: Content }[],
shellToolDefaultOpen: boolean,
editToolDefaultOpen: boolean,
): PartGroup[] {
const groups: PartGroup[] = []
let adjacent: { type: "context" | "patch" | "edit"; refs: PartRef[] } | undefined
const flush = () => {
@@ -482,13 +508,7 @@ function groupContent(items: { messageID: string; partID: string; content: Conte
items.forEach((item) => {
const type =
item.content.type === "tool" && contextTools.has(item.content.name) && !hasLoadedFiles(item.content)
? "context"
: item.content.type === "tool" && item.content.name === "patch" && item.content.state.status !== "error"
? "patch"
: item.content.type === "tool" && item.content.name === "edit" && item.content.state.status !== "error"
? "edit"
: undefined
item.content.type === "tool" ? toolGroupType(item.content, shellToolDefaultOpen, editToolDefaultOpen) : undefined
if (type) {
if (adjacent?.type !== type) flush()
adjacent ??= { type, refs: [] }
@@ -506,6 +526,26 @@ function groupContent(items: { messageID: string; partID: string; content: Conte
return groups
}
function toolGroupType(content: Extract<Content, { type: "tool" }>, shellExpanded: boolean, editExpanded: boolean) {
if (content.name === "question" || hasLoadedFiles(content)) return undefined
if (content.state.status === "error") {
if ((content.name === "shell" || content.name === "execute") && shellExpanded) return undefined
if ((content.name === "edit" || content.name === "write" || content.name === "patch") && editExpanded)
return undefined
return "context"
}
if (
(content.state.status !== "completed" ||
("metadata" in content.state && content.state.metadata?.status === "running")) &&
(content.name === "shell" || content.name === "execute" || content.name === "subagent")
)
return undefined
if (currentContentDefaultOpen(content, shellExpanded, editExpanded) !== true) return "context"
if (content.name === "patch") return "patch"
if (content.name === "edit") return "edit"
return undefined
}
function hasLoadedFiles(content: Extract<Content, { type: "tool" }>) {
if (content.name !== "read" || content.state.status !== "completed") return false
const loaded = content.state.metadata?.loaded
@@ -514,7 +514,9 @@ describe("current session timeline rows", () => {
assistant("msg_assistant_3", "grep"),
] satisfies SessionMessageInfo[]
const keys = Timeline.constructSessionMessageRows(source, false, { type: "idle" }).rows.map(TimelineRow.key)
const keys = Timeline.constructSessionMessageRows(source, false, { type: "idle" }, undefined, true).rows.map(
TimelineRow.key,
)
expect(keys).toEqual([
"user-message:msg_user",
@@ -595,7 +597,7 @@ describe("current session timeline rows", () => {
},
] satisfies SessionMessageInfo[]
const result = Timeline.constructSessionMessageRows(source, false, { type: "idle" })
const result = Timeline.constructSessionMessageRows(source, false, { type: "idle" }, undefined, false, true)
const groups = result.rows.flatMap((row) => (row._tag === "AssistantPart" ? [row.group] : []))
expect(groups).toEqual([
@@ -628,6 +630,224 @@ describe("current session timeline rows", () => {
])
})
test("groups every consecutive collapsed tool in chronological order", () => {
const source = [
{ id: "msg_user", type: "user", text: "work", time: { created: 1 } },
{
id: "msg_assistant",
type: "assistant",
agent: "build",
model: { id: "model", providerID: "provider" },
content: [
...["shell", "subagent", "patch", "shell", "edit", "write", "grep"].map(
(name, index): SessionMessageAssistantTool => ({
type: "tool" as const,
id: `tool_${index}`,
name,
state: {
status: "completed" as const,
input: {},
content: [{ type: "text" as const, text: "done" }],
metadata: {},
},
time: { created: index + 2, completed: index + 3 },
}),
),
{ type: "text" as const, text: "finished" },
{
type: "tool" as const,
id: "tool_after_text",
name: "shell",
state: {
status: "completed" as const,
input: {},
content: [{ type: "text" as const, text: "done" }],
metadata: {},
},
time: { created: 10, completed: 11 },
},
],
time: { created: 2 },
},
] satisfies SessionMessageInfo[]
const groups = Timeline.constructSessionMessageRows(source, false, { type: "idle" }).rows.flatMap((row) =>
row._tag === "AssistantPart" ? [row.group] : [],
)
expect(groups.map((group) => group.type)).toEqual(["context", "part", "context"])
expect(groups[0]?.type === "context" ? groups[0].refs.map((ref) => ref.partID) : []).toEqual([
"tool_0",
"tool_1",
"tool_2",
"tool_3",
"tool_4",
"tool_5",
"tool_6",
])
expect(groups[2]?.type === "context" ? groups[2].refs.map((ref) => ref.partID) : []).toEqual(["tool_after_text"])
})
test.each([
{ shell: false, edit: false, types: ["context"] },
{ shell: true, edit: false, types: ["part", "context"] },
{ shell: false, edit: true, types: ["context", "file", "part", "file", "context"] },
{ shell: true, edit: true, types: ["part", "file", "part", "file", "context"] },
])("keeps tools expanded by settings outside collapsed groups ($shell, $edit)", ({ shell, edit, types }) => {
const source = [
{ id: "msg_user", type: "user", text: "work", time: { created: 1 } },
{
id: "msg_assistant",
type: "assistant",
agent: "build",
model: { id: "model", providerID: "provider" },
content: ["shell", "edit", "write", "patch", "read"].map(
(name, index): SessionMessageAssistantTool => ({
type: "tool" as const,
id: `tool_${name}`,
name,
state: {
status: "completed" as const,
input: {},
content: [{ type: "text" as const, text: "done" }],
metadata: {},
},
time: { created: index + 2, completed: index + 3 },
}),
),
time: { created: 2 },
},
] satisfies SessionMessageInfo[]
const rows = Timeline.constructSessionMessageRows(source, false, { type: "idle" }, undefined, shell, edit).rows
expect(rows.flatMap((row) => (row._tag === "AssistantPart" ? [row.group.type] : []))).toEqual([...types])
})
test("keeps active and background work visible outside collapsed stacks", () => {
const source: SessionMessageInfo[] = [
{ id: "msg_user", type: "user", text: "work", time: { created: 1 } },
{
id: "msg_assistant",
type: "assistant",
agent: "build",
model: { id: "model", providerID: "provider" },
content: [
{
type: "tool",
id: "tool_running_shell",
name: "shell",
state: { status: "running", input: {}, metadata: {} },
time: { created: 2 },
},
{
type: "tool",
id: "tool_background_agent",
name: "subagent",
state: {
status: "completed",
input: {},
content: [{ type: "text", text: "running" }],
metadata: { status: "running" },
},
time: { created: 3, completed: 4 },
},
{
type: "tool",
id: "tool_completed_shell",
name: "shell",
state: {
status: "completed",
input: {},
content: [{ type: "text", text: "done" }],
metadata: {},
},
time: { created: 5, completed: 6 },
},
],
time: { created: 2 },
},
]
expect(
Timeline.constructSessionMessageRows(source, false, { type: "busy" }).rows.flatMap((row) =>
row._tag === "AssistantPart" ? [row.group.type] : [],
),
).toEqual(["part", "part", "context"])
})
test("keeps failed calls inside a collapsed mixed-tool stack", () => {
const source: SessionMessageInfo[] = [
{ id: "msg_user", type: "user", text: "search", time: { created: 1 } },
{
id: "msg_assistant",
type: "assistant",
agent: "build",
model: { id: "model", providerID: "provider" },
content: [
{
type: "tool",
id: "tool_glob_failed",
name: "glob",
state: {
status: "error",
input: { pattern: "*.ts" },
error: { type: "ToolError", message: "Invalid tool input" },
metadata: {},
},
time: { created: 2, completed: 3 },
},
{
type: "tool",
id: "tool_grep_failed",
name: "grep",
state: {
status: "error",
input: { pattern: "value" },
error: { type: "ToolError", message: "Search timed out" },
metadata: {},
},
time: { created: 4, completed: 5 },
},
{
type: "tool",
id: "tool_shell_failed",
name: "shell",
state: {
status: "error",
input: { command: "exit 1" },
error: { type: "ToolError", message: "Command failed" },
metadata: {},
},
time: { created: 6, completed: 7 },
},
],
time: { created: 2, completed: 8 },
},
]
const groups = Timeline.constructSessionMessageRows(source, false, { type: "idle" }).rows.flatMap((row) =>
row._tag === "AssistantPart" ? [row.group] : [],
)
expect(groups).toEqual([
{
type: "context",
key: "context:msg_assistant:tool_glob_failed",
refs: [
{ messageID: "msg_assistant", partID: "tool_glob_failed" },
{ messageID: "msg_assistant", partID: "tool_grep_failed" },
{ messageID: "msg_assistant", partID: "tool_shell_failed" },
],
},
])
expect(
Timeline.constructSessionMessageRows(source, false, { type: "idle" }, undefined, true).rows.flatMap((row) =>
row._tag === "AssistantPart" ? [row.group.type] : [],
),
).toEqual(["context", "part"])
})
test("places a divider after interrupted output unless the turn compacts", () => {
const messages = [
{ id: "msg_user", type: "user", text: "continue", time: { created: 1 } },
@@ -229,10 +229,12 @@ export function createSessionTimelineRowRenderer(input: {
id={props.row._tag === "UserMessage" ? input.anchor?.(props.row.userMessageID) : undefined}
data-message-id={props.row.userMessageID}
data-timeline-row={props.row._tag}
data-timeline-spacing={props.row._tag === "AssistantPart" ? props.row.spacing : undefined}
classList={{
"min-w-0 w-full max-w-full": true,
"md:max-w-[1000px] md:mx-auto": input.centered?.(),
"pt-3": props.row._tag === "AssistantPart" && props.row.previousAssistantPart,
"pt-2": props.row._tag === "AssistantPart" && props.row.spacing === "tool",
"pt-4": props.row._tag === "AssistantPart" && props.row.spacing === "content",
}}
>
<div data-component="session-turn" class="min-w-0 w-full relative" style={{ height: "auto" }}>
@@ -22,6 +22,8 @@ export function SessionTimeline(props: SessionTimelineProps) {
sessionMessages: () => props.document.messages,
status: () => props.document.status,
showReasoningSummaries: () => props.showReasoningSummaries ?? true,
shellToolDefaultOpen: () => props.shellToolDefaultOpen ?? false,
editToolDefaultOpen: () => props.editToolDefaultOpen ?? false,
})
const [toolOpen, setToolOpen] = createStore<Record<string, boolean | undefined>>({})
const renderer = createSessionTimelineRowRenderer({
@@ -49,6 +49,7 @@ export namespace TimelineRow {
userMessageID: string
group: PartGroup
previousAssistantPart: boolean
spacing?: "tool" | "content"
}> {}
export class Thinking extends Data.TaggedClass("Thinking")<{
@@ -118,6 +119,7 @@ export type TimelineRowMap = {
userMessageID: string
group: PartGroup
previousAssistantPart: boolean
spacing?: "tool" | "content"
}
Thinking: { userMessageID: string; reasoningHeading?: string }
Retry: { userMessageID: string }
+81 -52
View File
@@ -20,6 +20,7 @@ import { useFileComponent } from "@opencode-ai/ui/context/file"
import { type UiI18n, useI18n } from "@opencode-ai/ui/context/i18n"
import { BasicTool, GenericTool } from "../components/basic-tool"
import { Accordion } from "@opencode-ai/ui/accordion"
import { Badge } from "@opencode-ai/ui/badge"
import { StickyAccordionHeader } from "@opencode-ai/ui/sticky-accordion-header"
import { Collapsible } from "@opencode-ai/ui/collapsible"
import { FileIcon } from "@opencode-ai/ui/file-icon"
@@ -32,13 +33,16 @@ import { checksum } from "@opencode-ai/util/encode"
import { Tooltip } from "@opencode-ai/ui/tooltip"
import { IconButton } from "@opencode-ai/ui/icon-button"
import { TextShimmer } from "@opencode-ai/ui/text-shimmer"
import { AnimatedCountList } from "../components/tool-count-summary"
import { ToolStatusTitle } from "../components/tool-status-title"
import { changedFileDiff, patchFileGroups } from "../components/apply-patch-file"
import { animate } from "motion"
import { SessionProgressIndicatorV2 } from "../v2/components/session-progress-indicator-v2"
import type { SessionMessageAssistantTool, SessionMessageShell } from "@opencode-ai/client/promise"
import { currentToolInput, currentToolMetadata } from "../message/current-tool-state"
import {
currentToolError,
currentToolInput,
currentToolMetadata,
currentToolOutput,
} from "../message/current-tool-state"
import { writeClipboard } from "../message/message-content"
function ShellSubmessage(props: { text: string; animate?: boolean }) {
@@ -477,50 +481,50 @@ export function CurrentContextToolGroup(props: {
() =>
props.busy || props.tools.some((tool) => tool.state.status === "streaming" || tool.state.status === "running"),
)
const summary = createMemo(() => ({
read: props.tools.filter((tool) => tool.name === "read").length,
search: props.tools.filter((tool) => tool.name === "glob" || tool.name === "grep").length,
list: props.tools.filter((tool) => tool.name === "list").length,
}))
const names = createMemo(() =>
[
...new Set(
props.tools.map((tool) => {
const input = currentToolInput(tool)
if (tool.name === "skill") return i18n.t("ui.tool.skill")
if (tool.name === "subagent" && typeof input.agent === "string" && input.agent)
return input.agent[0]!.toUpperCase() + input.agent.slice(1)
return getToolInfo(tool.name, input, currentToolMetadata(tool)).title
}),
),
].join(", "),
)
const label = createMemo(() => {
const tools = names()
const text = i18n.t("ui.messagePart.tools.used", { tools })
const index = text.indexOf(tools)
return { text, before: text.slice(0, index).trim(), after: text.slice(index + tools.length).trim() }
})
const change = (open: boolean) => {
props.onOpenChange(open)
props.onSizeChange?.()
}
return (
<div data-timeline-part-ids={props.tools.map((tool) => tool.id).join(",")}>
<div data-component="collapsed-tool-group" data-timeline-part-ids={props.tools.map((tool) => tool.id).join(",")}>
<BasicTool
icon="glasses"
status={pending() ? "running" : "completed"}
compact
rail={false}
allowOpenWhilePending
open={props.open}
onOpenChange={change}
trigger={
<div data-component="context-tool-group-trigger">
<span data-slot="context-tool-group-title" class="min-w-0 flex items-center gap-2">
<span data-slot="basic-tool-tool-title" class="shrink-0">
<ToolStatusTitle
active={pending()}
activeText={i18n.t("ui.sessionTurn.status.gatheringContext")}
doneText={i18n.t("ui.sessionTurn.status.gatheredContext")}
split={false}
/>
</span>
<span
data-slot="basic-tool-tool-subtitle"
class="min-w-0 overflow-hidden text-ellipsis whitespace-nowrap"
>
<AnimatedCountList
items={[
{ key: "ui.messagePart.context.read", count: summary().read },
{ key: "ui.messagePart.context.search", count: summary().search },
{ key: "ui.messagePart.context.list", count: summary().list },
]}
fallback=""
/>
</span>
<div data-component="context-tool-group-trigger" aria-label={label().text}>
<span data-slot="context-tool-group-title">
<Show when={label().before}>
{(before) => <span data-slot="context-tool-group-prefix">{before()}</span>}
</Show>
<span data-slot="basic-tool-tool-title">{names()}</span>
<Show when={label().after}>
{(after) => <span data-slot="context-tool-group-prefix">{after()}</span>}
</Show>
<Badge>{props.tools.length}</Badge>
</span>
</div>
}
@@ -529,32 +533,57 @@ export function CurrentContextToolGroup(props: {
<Index each={props.tools}>
{(tool) => {
const trigger = createMemo(() => currentContextToolTrigger(tool(), i18n))
const running = () => tool().state.status === "streaming" || tool().state.status === "running"
return (
<div data-slot="context-tool-group-item">
<div data-component="tool-trigger">
<div data-slot="basic-tool-tool-trigger-content">
<div data-slot="basic-tool-tool-info">
<div data-slot="basic-tool-tool-info-structured">
<div data-slot="basic-tool-tool-info-main">
<span data-slot="basic-tool-tool-title">
<TextShimmer text={trigger().title} active={running()} />
</span>
<Show when={trigger().subtitle}>
<span data-slot="basic-tool-tool-subtitle">{trigger().subtitle}</span>
<Show
when={tool().state.status !== "error" && ["read", "glob", "grep", "list"].includes(tool().name)}
fallback={
<ToolDisplay
id={tool().id}
tool={tool().name}
input={currentToolInput(tool())}
metadata={currentToolMetadata(tool())}
output={currentToolOutput(tool())}
error={currentToolError(tool())}
status={tool().state.status}
defaultOpen={false}
deferContent
virtualizeDiff={false}
onContentRendered={props.onSizeChange}
/>
}
>
<div data-component="tool-trigger">
<div data-slot="basic-tool-tool-trigger-content">
<div data-slot="basic-tool-tool-info">
<div data-slot="basic-tool-tool-info-structured">
<div data-slot="basic-tool-tool-info-main">
<span data-slot="basic-tool-tool-title">
<TextShimmer
text={trigger().title}
active={tool().state.status === "streaming" || tool().state.status === "running"}
/>
</span>
<Show when={trigger().subtitle}>
{(subtitle) => <span data-slot="basic-tool-tool-subtitle">{subtitle()}</span>}
</Show>
<For each={trigger().args}>
{(arg) => <span data-slot="basic-tool-tool-arg">{arg}</span>}
</For>
</div>
<Show when={trigger().matches}>
{(matches) => (
<>
<span data-slot="context-tool-group-dot" />
<span data-slot="context-tool-group-matches">{matches()}</span>
</>
)}
</Show>
<For each={trigger().args}>
{(arg) => <span data-slot="basic-tool-tool-arg">{arg}</span>}
</For>
</div>
<Show when={trigger().matches}>
<span data-slot="context-tool-group-dot" />
<span data-slot="context-tool-group-matches">{trigger().matches}</span>
</Show>
</div>
</div>
</div>
</div>
</Show>
</div>
)
}}
+1 -1
View File
@@ -17,7 +17,7 @@ export async function localProjectDirectory(cwd: string) {
const repositories = await Promise.all(
directories.map((directory) =>
Promise.all(
[".git", ".hg"].map((name) =>
[".git", ".hg", ".jj"].map((name) =>
stat(path.join(directory, name)).then(
() => true,
(error) => (isMissingPath(error) ? false : Promise.reject(error)),
@@ -68,6 +68,18 @@ test("uses an Hg root for a missing project plugin directory", async () => {
)
})
test("uses a Jujutsu root for a missing project plugin directory", async () => {
await using tmp = await tmpdir()
const project = path.join(tmp.path, "repo")
const cwd = path.join(project, "package")
await mkdir(path.join(project, ".jj"), { recursive: true })
await mkdir(cwd, { recursive: true })
expect(await tuiPluginDirectories(cwd, path.join(tmp.path, "config"))).toContain(
path.join(project, ".opencode", "plugins", "tui"),
)
})
test("truncates fractional mtimes in fresh specifiers", () => {
// A dot in the query makes Bun's compiled binaries skip runtime plugin
// hooks for the import, breaking JSX/solid rewriting for external plugins.
+1
View File
@@ -110,6 +110,7 @@ const source = {
"ui.messagePart.context.list.other": "{{count}} lists",
"ui.messagePart.context.match.one": "({{count}} match)",
"ui.messagePart.context.match.other": "({{count}} matches)",
"ui.messagePart.tools.used": "Used {{tools}}",
"ui.list.loading": "Loading",
"ui.list.empty": "No results",
+4
View File
@@ -32,6 +32,10 @@ const icons = {
viewBox: "0 0 16 16",
body: `<path d="M6.33345 6.33349V5.00015H9.66679V7.00015L8.00015 8.00015V9.66679M8.27485 11.6819H7.71897M14.4446 8.00011C14.4446 11.5593 11.5593 14.4446 8.00011 14.4446C4.44094 14.4446 1.55566 11.5593 1.55566 8.00011C1.55566 4.44094 4.44094 1.55566 8.00011 1.55566C11.5593 1.55566 14.4446 4.44094 14.4446 8.00011Z" stroke="currentColor" stroke-linecap="square"/>`,
},
"circle-exclamation": {
viewBox: "0 0 16 16",
body: `<path d="M7.9987 5.50016V8.50016M7.9987 10.5002V10.5068M14.1654 8.00016C14.1654 11.4059 11.4045 14.1668 7.9987 14.1668C6.29582 14.1668 4.75415 13.4766 3.63821 12.3607C2.52226 11.2447 1.83203 9.70304 1.83203 8.00016C1.83203 4.59441 4.59294 1.8335 7.9987 1.8335C9.70158 1.8335 11.2432 2.52372 12.3592 3.63967C13.4751 4.75562 14.1654 6.29728 14.1654 8.00016Z" stroke="currentColor" stroke-linecap="square"/>`,
},
"sidebar-right": {
viewBox: "0 0 20 20",
body: `<path d="M2.91536 2.91406H2.36536V2.36406H2.91536V2.91406ZM2.91536 17.0807V17.6307H2.36536V17.0807H2.91536ZM17.082 17.0807H17.632V17.6307H17.082V17.0807ZM17.082 2.91406V2.36406H17.632V2.91406H17.082ZM6.9987 2.91406H6.4487V2.36406H6.9987V2.91406ZM6.9987 17.0807V17.6307H6.4487V17.0807H6.9987ZM2.91536 2.91406H3.46536V17.0807H2.91536H2.36536V2.91406H2.91536ZM2.91536 17.0807V16.5307H17.082V17.0807V17.6307H2.91536V17.0807ZM17.082 17.0807H16.532V2.91406H17.082H17.632V17.0807H17.082ZM17.082 2.91406V3.46406H2.91536V2.91406V2.36406H17.082V2.91406ZM6.9987 2.91406H7.5487V17.0807H6.9987H6.4487V2.91406H6.9987ZM17.082 17.0807L17.082 17.6307L6.9987 17.6307V17.0807V16.5307L17.082 16.5307L17.082 17.0807ZM6.9987 2.91406V2.36406H17.082V2.91406V3.46406H6.9987V2.91406Z" fill="currentColor"/>`,