mirror of
https://gitee.com/zhangsken/opencode.git
synced 2026-11-20 00:21:44 +08:00
Compare commits
15 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 69e9cc80a4 | |||
| a1cb005799 | |||
| 19833ad1fd | |||
| cb852434b1 | |||
| b3733e9517 | |||
| 331f4ecd2f | |||
| ecaa914b79 | |||
| 4f8dea674a | |||
| 4bf5269c4c | |||
| c9d240704d | |||
| c9df4ba80d | |||
| ac71a55294 | |||
| f84d927e07 | |||
| d431fedce5 | |||
| e536b9627e |
@@ -415,10 +415,7 @@ const lowerMessages = Effect.fn("BedrockConverse.lowerMessages")(function* (
|
||||
|
||||
// System prompts share the cache-point convention: emit the text block, then
|
||||
// optionally a positional `cachePoint` marker.
|
||||
const lowerSystem = (
|
||||
breakpoints: BedrockCache.Breakpoints,
|
||||
system: ReadonlyArray<LLMRequest["system"][number]>,
|
||||
) => {
|
||||
const lowerSystem = (breakpoints: BedrockCache.Breakpoints, system: ReadonlyArray<LLMRequest["system"][number]>) => {
|
||||
const content = system
|
||||
.filter((part) => part.text.length > 0)
|
||||
.flatMap((part) => textWithCache(breakpoints, part.text, part.cache))
|
||||
@@ -508,7 +505,6 @@ const mapUsage = (usage: BedrockUsageSchema | undefined, providerMetadataKey: st
|
||||
interface ParserState {
|
||||
readonly providerMetadataKey: string
|
||||
readonly tools: ToolStream.State<number>
|
||||
readonly finishedTools: ReadonlySet<number>
|
||||
// Bedrock splits the finish into `messageStop` (carries `stopReason`) and
|
||||
// `metadata` (carries usage). Hold both in state so `onHalt` can emit exactly
|
||||
// one finish after both chunks have had a chance to arrive.
|
||||
@@ -620,16 +616,14 @@ const step = (state: ParserState, event: BedrockEvent) =>
|
||||
}
|
||||
|
||||
if (event.contentBlockDelta?.delta?.toolUse) {
|
||||
const index = event.contentBlockDelta.contentBlockIndex
|
||||
if (state.finishedTools.has(index)) return [state, []] as const
|
||||
const result = ToolStream.appendExisting(
|
||||
ADAPTER,
|
||||
// A delta for a block that is not open, whether it already stopped or never
|
||||
// started, has nothing to attach to and is dropped.
|
||||
const result = ToolStream.append(
|
||||
state.tools,
|
||||
index,
|
||||
event.contentBlockDelta.contentBlockIndex,
|
||||
event.contentBlockDelta.delta.toolUse.input,
|
||||
"Bedrock Converse tool delta is missing its tool call",
|
||||
)
|
||||
if (ToolStream.isError(result)) return yield* result
|
||||
if (!result) return [state, []] as const
|
||||
const events: LLMEvent[] = []
|
||||
const lifecycle = result.events.length ? Lifecycle.stepStart(state.lifecycle, events) : state.lifecycle
|
||||
events.push(...result.events)
|
||||
@@ -668,7 +662,6 @@ const step = (state: ParserState, event: BedrockEvent) =>
|
||||
state.hasToolCalls,
|
||||
lifecycle,
|
||||
tools: result.tools,
|
||||
finishedTools: resultEvents.length > 0 ? new Set([...state.finishedTools, index]) : state.finishedTools,
|
||||
reasoningSignatures: Object.fromEntries(
|
||||
Object.entries(state.reasoningSignatures).filter(([key]) => key !== String(index)),
|
||||
),
|
||||
@@ -765,7 +758,6 @@ export const protocol = Protocol.make({
|
||||
initial: (request) => ({
|
||||
providerMetadataKey: request.model.route.providerMetadataKey ?? String(request.model.provider),
|
||||
tools: ToolStream.empty<number>(),
|
||||
finishedTools: new Set<number>(),
|
||||
finishReason: undefined,
|
||||
usage: undefined,
|
||||
hasToolCalls: false,
|
||||
|
||||
@@ -433,7 +433,6 @@ export interface ParserState {
|
||||
type ReasoningSummaryStatus = "active" | "can-conclude" | "concluded"
|
||||
|
||||
interface ReasoningStreamItem {
|
||||
readonly open: boolean
|
||||
readonly encryptedContent: string | null | undefined
|
||||
// Keyed by the wire protocol's numeric `summary_index`. JS object keys coerce to
|
||||
// strings, but typing the map as `Record<number, ...>` documents intent
|
||||
@@ -950,7 +949,7 @@ export const normalize = (state: ParserState, input: Event): NormalizedEvent =>
|
||||
|
||||
const startReasoningSummaryPart = (state: ParserState, itemID: string, index: number): StepResult => {
|
||||
const item = state.reasoningItems[itemID]
|
||||
if (!item?.open || index === 0 || item.summaryParts[index] !== undefined) return [state, NO_EVENTS]
|
||||
if (!item || index === 0 || item.summaryParts[index] !== undefined) return [state, NO_EVENTS]
|
||||
|
||||
const events: LLMEvent[] = []
|
||||
const lifecycle = Object.entries(item.summaryParts)
|
||||
@@ -990,7 +989,7 @@ const startReasoningSummaryPart = (state: ParserState, itemID: string, index: nu
|
||||
|
||||
export const onReasoningDelta = (state: ParserState, event: Event, itemID: string): StepResult => {
|
||||
const item = state.reasoningItems[itemID]
|
||||
if (!event.delta || !item?.open) return [state, NO_EVENTS]
|
||||
if (!event.delta || !item) return [state, NO_EVENTS]
|
||||
const index = event.summary_index ?? 0
|
||||
if (item.summaryParts[index] === "concluded") return [state, NO_EVENTS]
|
||||
const [started, emitted] = startReasoningSummaryPart(state, itemID, index)
|
||||
@@ -1015,7 +1014,7 @@ export const onReasoningDelta = (state: ParserState, event: Event, itemID: strin
|
||||
// as a single delta unless that summary index already streamed one.
|
||||
export const onReasoningDone = (state: ParserState, event: Event, itemID: string): StepResult => {
|
||||
const item = state.reasoningItems[itemID]
|
||||
if (!item?.open || typeof event.text !== "string") return [state, NO_EVENTS]
|
||||
if (!item || typeof event.text !== "string") return [state, NO_EVENTS]
|
||||
const index = event.summary_index ?? 0
|
||||
if (item.deltaIndexes.has(index)) return [state, NO_EVENTS]
|
||||
return onReasoningDelta(state, { ...event, delta: event.text }, itemID)
|
||||
@@ -1074,7 +1073,6 @@ const onOutputItemAdded = (state: ParserState, event: NormalizedEvent): StepResu
|
||||
reasoningItems: {
|
||||
...state.reasoningItems,
|
||||
[item.id]: {
|
||||
open: true,
|
||||
encryptedContent: item.encrypted_content,
|
||||
summaryParts: { 0: "active" },
|
||||
deltaIndexes: new Set(),
|
||||
@@ -1112,7 +1110,7 @@ const onReasoningSummaryPartAdded = (state: ParserState, event: Event): StepResu
|
||||
const onReasoningSummaryPartDone = (state: ParserState, event: Event): StepResult => {
|
||||
if (event.item_id === undefined || event.summary_index === undefined) return [state, NO_EVENTS]
|
||||
const item = state.reasoningItems[event.item_id]
|
||||
if (!item?.open) return [state, NO_EVENTS]
|
||||
if (!item) return [state, NO_EVENTS]
|
||||
if (item.summaryParts[event.summary_index] !== "active") return [state, NO_EVENTS]
|
||||
return [
|
||||
{
|
||||
@@ -1247,7 +1245,6 @@ const onOutputItemDone = Effect.fn("OpenResponses.onOutputItemDone")(function* (
|
||||
}
|
||||
|
||||
if (item.type === "reasoning") {
|
||||
if (state.reasoningItems[item.id]?.open === false) return [state, NO_EVENTS] satisfies StepResult
|
||||
const metadata = reasoningMetadata(state, item)
|
||||
const summaryParts: ReadonlyArray<unknown> = Array.isArray(item.summary) ? item.summary : []
|
||||
const summary: Array<string | undefined> = []
|
||||
@@ -1274,53 +1271,14 @@ const onOutputItemDone = Effect.fn("OpenResponses.onOutputItemDone")(function* (
|
||||
const finalText = fragments.length === 1 ? itemText : summary[Number(index)]
|
||||
lifecycle = Lifecycle.reasoningEnd(lifecycle, events, `${item.id}:${index}`, metadata, finalText || undefined)
|
||||
}
|
||||
return [
|
||||
{
|
||||
...state,
|
||||
lifecycle,
|
||||
reasoningItems: {
|
||||
...state.reasoningItems,
|
||||
[item.id]: {
|
||||
...reasoningItem,
|
||||
open: false,
|
||||
encryptedContent: item.encrypted_content ?? reasoningItem.encryptedContent,
|
||||
},
|
||||
},
|
||||
},
|
||||
events,
|
||||
] satisfies StepResult
|
||||
const reasoningItems = { ...state.reasoningItems }
|
||||
delete reasoningItems[item.id]
|
||||
return [{ ...state, lifecycle, reasoningItems }, events] satisfies StepResult
|
||||
}
|
||||
if (!state.lifecycle.reasoning.has(item.id)) {
|
||||
const lifecycle = Lifecycle.stepStart(state.lifecycle, events)
|
||||
events.push(LLMEvent.reasoningStart({ id: item.id, providerMetadata: metadata }))
|
||||
events.push(
|
||||
LLMEvent.reasoningEnd({
|
||||
id: item.id,
|
||||
providerMetadata: metadata,
|
||||
text: itemText,
|
||||
}),
|
||||
)
|
||||
return [
|
||||
{
|
||||
...state,
|
||||
lifecycle,
|
||||
reasoningItems: {
|
||||
...state.reasoningItems,
|
||||
[item.id]: {
|
||||
open: false,
|
||||
encryptedContent: item.encrypted_content,
|
||||
summaryParts: { 0: "concluded" },
|
||||
deltaIndexes: new Set(),
|
||||
},
|
||||
},
|
||||
},
|
||||
events,
|
||||
] satisfies StepResult
|
||||
}
|
||||
return [
|
||||
{ ...state, lifecycle: Lifecycle.reasoningEnd(state.lifecycle, events, item.id, metadata) },
|
||||
events,
|
||||
] satisfies StepResult
|
||||
const lifecycle = Lifecycle.stepStart(state.lifecycle, events)
|
||||
events.push(LLMEvent.reasoningStart({ id: item.id, providerMetadata: metadata }))
|
||||
events.push(LLMEvent.reasoningEnd({ id: item.id, providerMetadata: metadata, text: itemText }))
|
||||
return [{ ...state, lifecycle }, events] satisfies StepResult
|
||||
}
|
||||
|
||||
return [state, NO_EVENTS] satisfies StepResult
|
||||
|
||||
@@ -159,6 +159,17 @@ export const appendOrStart = <K extends StreamKey>(
|
||||
return appendTool(tools, key, tool, delta.text)
|
||||
}
|
||||
|
||||
/**
|
||||
* Append argument text to a started tool. Returns `undefined` when no tool is
|
||||
* open under `key`, for protocols that ignore deltas without a matching block.
|
||||
*/
|
||||
export const append = <K extends StreamKey>(tools: State<K>, key: K, text: string): AppendOutcome<K> | undefined => {
|
||||
const current = tools[key]
|
||||
if (!current) return undefined
|
||||
if (text.length === 0) return { tools, tool: current, events: [] }
|
||||
return appendTool(tools, key, { ...current, input: `${current.input}${text}` }, text)
|
||||
}
|
||||
|
||||
/**
|
||||
* Append argument text to a tool that must already have been started. This keeps
|
||||
* protocols honest when their stream grammar promises a start event before any
|
||||
@@ -170,12 +181,7 @@ export const appendExisting = <K extends StreamKey>(
|
||||
key: K,
|
||||
text: string,
|
||||
missingToolMessage: string,
|
||||
): AppendOutcome<K> | AIError => {
|
||||
const current = tools[key]
|
||||
if (!current) return eventError(route, missingToolMessage)
|
||||
if (text.length === 0) return { tools, tool: current, events: [] }
|
||||
return appendTool(tools, key, { ...current, input: `${current.input}${text}` }, text)
|
||||
}
|
||||
): AppendOutcome<K> | AIError => append(tools, key, text) ?? eventError(route, missingToolMessage)
|
||||
|
||||
/**
|
||||
* Finalize one pending tool call: parse the accumulated raw JSON, remove it
|
||||
|
||||
@@ -713,9 +713,10 @@ describe("Bedrock Converse route", () => {
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("ignores late tool deltas after contentBlockStop", () =>
|
||||
it.effect("ignores tool deltas without an open tool block", () =>
|
||||
Effect.gen(function* () {
|
||||
const body = eventStreamBody(
|
||||
["contentBlockDelta", { contentBlockIndex: 5, delta: { toolUse: { input: "{}" } } }],
|
||||
[
|
||||
"contentBlockStart",
|
||||
{
|
||||
@@ -745,27 +746,6 @@ describe("Bedrock Converse route", () => {
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("rejects tool deltas without contentBlockStart", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* LLMClient.generate(baseRequest).pipe(
|
||||
Effect.provide(
|
||||
fixedBytes(
|
||||
eventStreamBody(
|
||||
["contentBlockDelta", { contentBlockIndex: 0, delta: { toolUse: { input: "{}" } } }],
|
||||
["messageStop", { stopReason: "tool_use" }],
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.flip,
|
||||
)
|
||||
|
||||
expect(error).toMatchObject({
|
||||
reason: { _tag: "InvalidProviderOutput" },
|
||||
message: "Bedrock Converse tool delta is missing its tool call",
|
||||
})
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("recovers incomplete tool input at finalization", () =>
|
||||
Effect.gen(function* () {
|
||||
const body = eventStreamBody(
|
||||
|
||||
@@ -71,7 +71,7 @@ function expectLifecycle(events: ReadonlyArray<LLMEvent>, completed: boolean) {
|
||||
}
|
||||
|
||||
describe("Open Responses basic-item lifecycles", () => {
|
||||
it.effect("closes implicit summary boundaries and ignores late events for completed reasoning", () =>
|
||||
it.effect("closes implicit summary boundaries", () =>
|
||||
Effect.gen(function* () {
|
||||
const item = { type: "reasoning", id: "rs_1", encrypted_content: "encrypted-state" }
|
||||
const events = yield* collect(
|
||||
@@ -90,12 +90,6 @@ describe("Open Responses basic-item lifecycles", () => {
|
||||
delta: "Third",
|
||||
},
|
||||
{ type: "response.output_item.done", item },
|
||||
{ type: "response.output_item.done", item },
|
||||
{ type: "response.output_item.added", item },
|
||||
{ type: "response.reasoning_summary_part.added", item_id: "rs_1", summary_index: 3 },
|
||||
{ type: "response.reasoning_summary_text.delta", item_id: "rs_1", summary_index: 3, delta: "late" },
|
||||
{ type: "response.reasoning_summary_text.done", item_id: "rs_1", summary_index: 2, text: "late final" },
|
||||
{ type: "response.reasoning_summary_part.done", item_id: "rs_1", summary_index: 3 },
|
||||
completed,
|
||||
)
|
||||
|
||||
@@ -129,7 +123,7 @@ describe("Open Responses basic-item lifecycles", () => {
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("preserves done-only reasoning text and encryption without replaying late events", () =>
|
||||
it.effect("preserves done-only reasoning text and encryption", () =>
|
||||
Effect.gen(function* () {
|
||||
const item = {
|
||||
type: "reasoning",
|
||||
@@ -139,11 +133,6 @@ describe("Open Responses basic-item lifecycles", () => {
|
||||
}
|
||||
const events = yield* collect(
|
||||
{ type: "response.output_item.done", item },
|
||||
{ type: "response.output_item.done", item },
|
||||
{ type: "response.output_item.added", item },
|
||||
{ type: "response.reasoning_summary_text.delta", item_id: "rs_1", delta: "late" },
|
||||
{ type: "response.reasoning_summary_part.added", item_id: "rs_1", summary_index: 1 },
|
||||
{ type: "response.reasoning_summary_text.done", item_id: "rs_1", summary_index: 1, text: "late final" },
|
||||
completed,
|
||||
// Route termination must also prevent events after response completion.
|
||||
{ type: "response.output_item.added", item: { type: "reasoning", id: "rs_after" } },
|
||||
|
||||
@@ -2861,7 +2861,6 @@ describe("OpenAI Responses route", () => {
|
||||
{ type: "response.output_item.added", item: { type: "reasoning", id: "rs_1" } },
|
||||
{ type: "response.reasoning_summary_text.delta", item_id: "rs_1", summary_index: 0, delta: "Think" },
|
||||
{ type: "response.output_item.done", item: { type: "reasoning", id: "rs_1" } },
|
||||
{ type: "response.output_item.done", item: { type: "reasoning", id: "rs_1" } },
|
||||
{
|
||||
type: "response.output_item.added",
|
||||
item: { type: "function_call", id: "fc_1", call_id: "call_1", name: "lookup", arguments: "" },
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { expect, story } from "../../storybook/playwright/story"
|
||||
|
||||
for (const theme of ["light", "dark"]) {
|
||||
story(`keeps the Open in border visible without hovering (${theme})`, async ({ mount, page }, testInfo) => {
|
||||
const component = await mount("ui-split-button--open-in", { globals: { theme } })
|
||||
const control = component.locator('[data-component="split-button-v2"]')
|
||||
await page.mouse.move(0, 0)
|
||||
await expect(control).toBeVisible()
|
||||
await expect(control).not.toHaveCSS("box-shadow", "none")
|
||||
const border = await control.evaluate((element) => getComputedStyle(element).boxShadow)
|
||||
|
||||
await component.getByRole("button", { name: "Open options" }).hover()
|
||||
await expect(control).toHaveCSS("box-shadow", border)
|
||||
await page.mouse.move(0, 0)
|
||||
await expect(control).toHaveCSS("box-shadow", border)
|
||||
await control.screenshot({ path: testInfo.outputPath(`open-in-${theme}.png`) })
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
import { base64Encode } from "@opencode-ai/util/encode"
|
||||
import { expect, test, type Locator } from "@playwright/test"
|
||||
import { mockOpenCodeServer } from "../utils/mock-server"
|
||||
import { expectSessionTitle } from "../utils/waits"
|
||||
|
||||
const directory = "C:/OpenCode/ReviewTogglePosition"
|
||||
const sessionID = "ses_review_toggle_position"
|
||||
const server = `http://${process.env.PLAYWRIGHT_SERVER_HOST ?? "127.0.0.1"}:${process.env.PLAYWRIGHT_SERVER_PORT ?? "4096"}`
|
||||
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await mockOpenCodeServer(page, {
|
||||
directory,
|
||||
project: {
|
||||
id: "proj_review_toggle_position",
|
||||
worktree: directory,
|
||||
vcs: "git",
|
||||
name: "review-toggle-position",
|
||||
time: { created: 1700000000000, updated: 1700000000000 },
|
||||
sandboxes: [],
|
||||
},
|
||||
provider: { all: [], connected: [], default: {} },
|
||||
sessions: [
|
||||
{
|
||||
id: sessionID,
|
||||
slug: "review-toggle-position",
|
||||
projectID: "proj_review_toggle_position",
|
||||
directory,
|
||||
title: "Review toggle position",
|
||||
version: "dev",
|
||||
time: { created: 1700000000000, updated: 1700000000000 },
|
||||
},
|
||||
],
|
||||
pageMessages: () => ({ items: [] }),
|
||||
})
|
||||
})
|
||||
|
||||
for (const width of [1000, 1440]) {
|
||||
for (const direction of ["ltr", "rtl"] as const) {
|
||||
test(`keeps the review toggle at the outer header edge (${width}px, ${direction})`, async ({ page }) => {
|
||||
await page.setViewportSize({ width, height: 900 })
|
||||
await page.goto(`/server/${base64Encode(server)}/session/${sessionID}`)
|
||||
await expectSessionTitle(page, "Review toggle position")
|
||||
await page.locator("html").evaluate((element, dir) => element.setAttribute("dir", dir), direction)
|
||||
|
||||
const toggle = page.getByRole("button", { name: "Toggle review", exact: true })
|
||||
const header = page.locator("[data-session-title]")
|
||||
const panel = page.locator("#review-panel")
|
||||
await expect(toggle).toHaveAttribute("aria-expanded", "false")
|
||||
const closed = await toggle.boundingBox()
|
||||
if (!closed) throw new Error("Review toggle bounds are unavailable")
|
||||
const headerBox = await header.boundingBox()
|
||||
if (!headerBox) throw new Error("Session header bounds are unavailable")
|
||||
expect(closed.y).toBeGreaterThanOrEqual(headerBox.y)
|
||||
expect(closed.y + closed.height).toBeLessThanOrEqual(headerBox.y + headerBox.height)
|
||||
|
||||
await toggle.click()
|
||||
await expect(toggle).toHaveAttribute("aria-expanded", "true")
|
||||
await expect(panel).toHaveAttribute("aria-hidden", "false")
|
||||
await expect(toggle).toHaveCount(1)
|
||||
await expect.poll(() => toggle.boundingBox()).toEqual(closed)
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const box = await panel.boundingBox()
|
||||
if (!box) return false
|
||||
return (
|
||||
closed.x >= box.x &&
|
||||
closed.x + closed.width <= box.x + box.width &&
|
||||
closed.y >= box.y &&
|
||||
closed.y + closed.height <= box.y + 52
|
||||
)
|
||||
})
|
||||
.toBe(true)
|
||||
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const box = await panel.locator('[data-slot="session-side-panel-actions"]').boundingBox()
|
||||
return box ? box.y + box.height / 2 : undefined
|
||||
})
|
||||
.toBe(closed.y + closed.height / 2)
|
||||
|
||||
await toggle.press("Enter")
|
||||
await expect(toggle).toHaveAttribute("aria-expanded", "false")
|
||||
await expect(toggle).toBeFocused()
|
||||
await expect(toggle).toHaveCount(1)
|
||||
await expect.poll(() => toggle.boundingBox()).toEqual(closed)
|
||||
})
|
||||
|
||||
test(`keeps terminal controls clear of the review toggle (${width}px, ${direction})`, async ({ page }) => {
|
||||
await page.setViewportSize({ width, height: 900 })
|
||||
const ptys: { id: string; title: string }[] = []
|
||||
const removed: string[] = []
|
||||
await page.route("**/api/pty**", async (route) => {
|
||||
const path = new URL(route.request().url()).pathname
|
||||
const location = { directory, project: { id: "proj_review_toggle_position", directory } }
|
||||
if (route.request().method() === "DELETE") {
|
||||
removed.push(path.split("/").at(-1)!)
|
||||
return route.fulfill({ status: 204 })
|
||||
}
|
||||
if (path.endsWith("/connect-token")) {
|
||||
return route.fulfill({ json: { location, data: { ticket: "e2e-ticket", expires_in: 60 } } })
|
||||
}
|
||||
if (path === "/api/pty" && route.request().method() === "POST") {
|
||||
const pty = { id: `pty_review_${ptys.length + 1}`, title: `Terminal ${ptys.length + 1}` }
|
||||
ptys.push(pty)
|
||||
return route.fulfill({ json: { location, data: pty } })
|
||||
}
|
||||
return route.fulfill({ json: { location, data: ptys.find((pty) => path.endsWith(pty.id)) ?? ptys } })
|
||||
})
|
||||
await page.routeWebSocket(/\/api\/pty\/pty_review_\d+\/connect/, () => undefined)
|
||||
await page.goto(`/server/${base64Encode(server)}/session/${sessionID}`)
|
||||
await expectSessionTitle(page, "Review toggle position")
|
||||
await page.locator("html").evaluate((element, dir) => element.setAttribute("dir", dir), direction)
|
||||
|
||||
const toggle = page.getByRole("button", { name: "Toggle review", exact: true })
|
||||
await expect(toggle).toHaveAttribute("aria-expanded", "false")
|
||||
await page.keyboard.press("Control+Backquote")
|
||||
const terminal = page.getByRole("region", { name: "Terminal", exact: true })
|
||||
await expect(terminal.getByRole("tab", { name: "Terminal 1", exact: true })).toHaveAttribute(
|
||||
"aria-selected",
|
||||
"true",
|
||||
)
|
||||
for (const number of [2, 3, 4]) {
|
||||
await terminal.getByRole("button", { name: "New terminal", exact: true }).click()
|
||||
await expect(terminal.getByRole("tab", { name: `Terminal ${number}`, exact: true })).toHaveAttribute(
|
||||
"aria-selected",
|
||||
"true",
|
||||
)
|
||||
}
|
||||
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const tabs = await terminal.getByRole("tablist").boundingBox()
|
||||
const button = await toggle.boundingBox()
|
||||
if (!tabs || !button) return false
|
||||
return direction === "rtl" ? tabs.x >= button.x + button.width : tabs.x + tabs.width <= button.x
|
||||
})
|
||||
.toBe(true)
|
||||
await expectTerminalControlsAligned(terminal, toggle)
|
||||
const fourth = terminal.locator('[data-slot="tabs-trigger-wrapper"][data-value="pty_review_4"]')
|
||||
await fourth.getByRole("button", { name: "Close terminal", exact: true }).click()
|
||||
await expect(terminal.getByRole("tab")).toHaveText(["Terminal 1", "Terminal 2", "Terminal 3"])
|
||||
expect(removed).toEqual(["pty_review_4"])
|
||||
await expect(toggle).toHaveAttribute("aria-expanded", "false")
|
||||
|
||||
await terminal.getByRole("button", { name: "New terminal", exact: true }).click()
|
||||
await expect(terminal.getByRole("tab", { name: "Terminal 5", exact: true })).toHaveAttribute(
|
||||
"aria-selected",
|
||||
"true",
|
||||
)
|
||||
await expect(toggle).toHaveAttribute("aria-expanded", "false")
|
||||
const position = await toggle.boundingBox()
|
||||
await toggle.click()
|
||||
await expect(toggle).toHaveAttribute("aria-expanded", "true")
|
||||
await expect(page.locator("#review-panel")).toHaveAttribute("aria-hidden", "false")
|
||||
await expect.poll(() => toggle.boundingBox()).toEqual(position)
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const actions = await page.locator('[data-slot="session-side-panel-actions"]').boundingBox()
|
||||
const button = await toggle.boundingBox()
|
||||
if (!actions || !button) return undefined
|
||||
return actions.y + actions.height / 2 - (button.y + button.height / 2)
|
||||
})
|
||||
.toBe(0)
|
||||
await toggle.press("Enter")
|
||||
await expect(toggle).toHaveAttribute("aria-expanded", "false")
|
||||
await expect(toggle).toBeFocused()
|
||||
await expect.poll(() => toggle.boundingBox()).toEqual(position)
|
||||
await expectTerminalControlsAligned(terminal, toggle)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async function expectTerminalControlsAligned(terminal: Locator, toggle: Locator) {
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const centers = await Promise.all(
|
||||
[terminal.getByRole("button", { name: "New terminal", exact: true }), toggle].map((button) =>
|
||||
button.locator("svg").evaluate((element) => {
|
||||
const svg = element as SVGSVGElement
|
||||
const path = svg.getBBox()
|
||||
return new DOMPoint(path.x + path.width / 2, path.y + path.height / 2).matrixTransform(svg.getScreenCTM()!)
|
||||
.y
|
||||
}),
|
||||
),
|
||||
)
|
||||
return centers[0]! - centers[1]!
|
||||
})
|
||||
.toBeCloseTo(0, 1)
|
||||
}
|
||||
@@ -24,7 +24,7 @@ for (const direction of ["ltr", "rtl"] as const) {
|
||||
const header = page.locator("[data-session-title]")
|
||||
const more = header.getByRole("button", { name: "More options", exact: true })
|
||||
const project = header.getByRole("button", { name: fixture.project.name, exact: true })
|
||||
const review = header.getByRole("button", { name: "Toggle review", exact: true })
|
||||
const review = page.getByRole("button", { name: "Toggle review", exact: true })
|
||||
const details = header.getByRole("button", { name: "Session details", exact: true })
|
||||
await expect(header.getByRole("heading")).toHaveText(fixture.expected.targetTitle)
|
||||
await page.evaluate((direction) => document.documentElement.setAttribute("dir", direction), direction)
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import { expect, test } from "@playwright/test"
|
||||
import { mockOpenCodeServer } from "../utils/mock-server"
|
||||
|
||||
const directory = "/tmp/settings-padding"
|
||||
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await mockOpenCodeServer(page, {
|
||||
directory,
|
||||
project: {
|
||||
id: "proj_settings_padding",
|
||||
canonical: directory,
|
||||
name: "Settings padding",
|
||||
vcs: "git",
|
||||
time: { created: 1700000000000, updated: 1700000000000 },
|
||||
},
|
||||
provider: { all: [], connected: [], default: {} },
|
||||
sessions: [],
|
||||
pageMessages: () => ({ items: [] }),
|
||||
})
|
||||
await page.route("https://api.github.com/repos/anomalyco/opencode/contributors?*", (route) =>
|
||||
route.fulfill({ json: [] }),
|
||||
)
|
||||
await page.goto("/")
|
||||
await page.getByRole("button", { name: "Settings", exact: true }).click()
|
||||
await expect(page.getByTestId("settings-screen")).toBeFocused()
|
||||
})
|
||||
|
||||
for (const viewport of [
|
||||
{ width: 1280, height: 720, bottom: false },
|
||||
{ width: 900, height: 600, bottom: false },
|
||||
{ width: 780, height: 600, bottom: false },
|
||||
{ width: 390, height: 844, bottom: false },
|
||||
{ width: 390, height: 844, bottom: true },
|
||||
]) {
|
||||
test.describe(`${viewport.width}px, ${viewport.bottom ? "bottom" : "top"} navigation`, () => {
|
||||
test.use({ viewport: { width: 1280, height: 720 }, contextOptions: { reducedMotion: "reduce" } })
|
||||
|
||||
test("every settings page leaves room below its final content", async ({ page }) => {
|
||||
await page.setViewportSize(viewport)
|
||||
const settings = page.getByTestId("settings-screen")
|
||||
const panel = settings.locator(":scope > .settings > .settings-panel:visible")
|
||||
if (viewport.bottom) {
|
||||
const toggle = settings.locator('[data-action="settings-mobile-titlebar-bottom"]')
|
||||
await toggle.locator('[data-slot="switch-control"]').click()
|
||||
await expect(toggle.getByRole("switch")).toBeChecked()
|
||||
}
|
||||
let current = "Preferences"
|
||||
for (const name of [
|
||||
"Preferences",
|
||||
"Appearance",
|
||||
"Notifications",
|
||||
"Shortcuts",
|
||||
"Servers",
|
||||
"Projects",
|
||||
"Worktrees",
|
||||
"Providers",
|
||||
"Models",
|
||||
"Extensions",
|
||||
"Experimental",
|
||||
"About",
|
||||
]) {
|
||||
if (viewport.width >= 816) await settings.getByRole("tab", { name, exact: true }).click()
|
||||
if (viewport.width < 816) {
|
||||
await settings.getByRole("button", { name: current, exact: true }).click()
|
||||
await page.getByRole("menuitemradio", { name, exact: true }).click()
|
||||
}
|
||||
current = name
|
||||
if (name === "About") await expect(panel.getByText("Released under the MIT License")).toBeVisible()
|
||||
if (name !== "About") {
|
||||
await expect(
|
||||
panel.getByRole("heading", { name: name === "Shortcuts" ? "Keyboard shortcuts" : name, exact: true }),
|
||||
).toBeVisible()
|
||||
}
|
||||
await panel.hover()
|
||||
await page.mouse.wheel(0, 10000)
|
||||
await expect
|
||||
.poll(() => panel.evaluate((el) => el.scrollHeight - el.clientHeight - el.scrollTop))
|
||||
.toBeLessThanOrEqual(1)
|
||||
await expect
|
||||
.poll(
|
||||
() =>
|
||||
panel.evaluate((el) => {
|
||||
const body = el.querySelector(".settings-tab-body, .settings-about-content")!
|
||||
return el.getBoundingClientRect().bottom - body.lastElementChild!.getBoundingClientRect().bottom
|
||||
}),
|
||||
{ message: `${name} bottom clearance` },
|
||||
)
|
||||
.toBeGreaterThanOrEqual(viewport.bottom ? 119.5 : 79.5)
|
||||
await expect
|
||||
.poll(() => page.getByRole("main").evaluate((el) => el.scrollWidth - el.clientWidth))
|
||||
.toBeLessThanOrEqual(1)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { expect, test } from "@playwright/test"
|
||||
import { mockOpenCodeServer } from "../utils/mock-server"
|
||||
|
||||
test.use({ contextOptions: { reducedMotion: "reduce" }, colorScheme: "dark" })
|
||||
|
||||
for (const viewport of [
|
||||
{ width: 1280, height: 720 },
|
||||
{ width: 900, height: 600 },
|
||||
{ width: 780, height: 600 },
|
||||
{ width: 390, height: 844 },
|
||||
]) {
|
||||
test(`preferences scroll only inside the panel at ${viewport.width}x${viewport.height}`, async ({ page }) => {
|
||||
const directory = "/tmp/settings-scroll"
|
||||
await mockOpenCodeServer(page, {
|
||||
directory,
|
||||
project: {
|
||||
id: "proj_settings_scroll",
|
||||
canonical: directory,
|
||||
name: "Settings scroll",
|
||||
vcs: "git",
|
||||
time: { created: 1700000000000, updated: 1700000000000 },
|
||||
},
|
||||
provider: { all: [], connected: [], default: {} },
|
||||
sessions: [],
|
||||
pageMessages: () => ({ items: [] }),
|
||||
})
|
||||
await page.goto("/")
|
||||
await page.getByRole("button", { name: "Settings", exact: true }).click()
|
||||
|
||||
const settings = page.getByTestId("settings-screen")
|
||||
const panel = settings.getByRole("tabpanel")
|
||||
const main = page.getByRole("main")
|
||||
const slider = settings.getByRole("slider", { name: "Timeline detail", exact: true })
|
||||
await expect(settings).toBeFocused()
|
||||
await page.setViewportSize(viewport)
|
||||
await expect(slider).toHaveAccessibleDescription(/Choose how much activity appears in the timeline/)
|
||||
await expect.poll(() => main.evaluate((el) => el.scrollHeight - el.clientHeight)).toBeLessThanOrEqual(1)
|
||||
|
||||
// Wheel over the outer gutter must not move the entire settings screen.
|
||||
await main.hover({ position: { x: 1, y: 200 } })
|
||||
await page.mouse.wheel(0, 10000)
|
||||
await panel.hover()
|
||||
await page.mouse.wheel(0, 10000)
|
||||
await expect.poll(() => panel.evaluate((el) => el.scrollTop)).toBeGreaterThan(0)
|
||||
await expect(main).toHaveJSProperty("scrollTop", 0)
|
||||
await expect(settings.getByRole("heading", { name: "Preferences", exact: true })).toBeInViewport()
|
||||
|
||||
await slider.scrollIntoViewIfNeeded()
|
||||
await slider.click()
|
||||
await page.keyboard.press("Home")
|
||||
await expect(slider).toHaveValue("0")
|
||||
await page.keyboard.press("ArrowRight")
|
||||
await expect(slider).toHaveValue("1")
|
||||
await expect(slider).toBeFocused()
|
||||
|
||||
await settings.getByRole("button", { name: "Advanced", exact: true }).click()
|
||||
await expect(
|
||||
settings.getByRole("group", { name: "Set placement and details for each activity category.", exact: true }),
|
||||
).toBeVisible()
|
||||
await panel.hover()
|
||||
await page.mouse.wheel(0, 10000)
|
||||
await expect
|
||||
.poll(() => panel.evaluate((el) => el.scrollHeight - el.clientHeight - el.scrollTop))
|
||||
.toBeLessThanOrEqual(1)
|
||||
await expect(main).toHaveJSProperty("scrollTop", 0)
|
||||
await expect.poll(() => main.evaluate((el) => el.scrollHeight - el.clientHeight)).toBeLessThanOrEqual(1)
|
||||
await expect(settings.getByRole("heading", { name: "Preferences", exact: true })).toBeInViewport()
|
||||
})
|
||||
}
|
||||
@@ -16,7 +16,6 @@ import { DialogConnectProvider } from "@/providers/connect/dialog"
|
||||
import { decode64 } from "@/runtime/persistence/base64"
|
||||
import { SettingsList } from "@/settings/list"
|
||||
import { SettingsRow } from "@/settings/row"
|
||||
import { compareModels } from "./order"
|
||||
import "@/settings/settings.css"
|
||||
|
||||
type ModelItem = ReturnType<ReturnType<typeof useLocal>["model"]["list"]>[number]
|
||||
@@ -46,7 +45,7 @@ export const DialogManageModels: Component = () => {
|
||||
items: () => local.model.list(),
|
||||
key: (x) => `${x.provider.id}:${x.id}`,
|
||||
filterKeys: ["provider.name", "name", "id"],
|
||||
sortBy: compareModels,
|
||||
sortBy: (a, b) => a.name.localeCompare(b.name),
|
||||
groupBy: (x) => x.provider.id,
|
||||
sortGroupsBy: (a, b) => {
|
||||
const aRank = popularProviders.indexOf(a.category)
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { compareModels, isFreeModel } from "./order"
|
||||
|
||||
describe("model ordering", () => {
|
||||
test("orders free first, then newest release, then name", () => {
|
||||
const items = [
|
||||
{ name: "A paid new", release_date: "2026-09-01", cost: { input: 1 } },
|
||||
{ name: "A free old", release_date: "2026-01-01", cost: { input: 0 } },
|
||||
{ name: "Z free new", release_date: "2026-08-01", cost: { input: 0 } },
|
||||
{ name: "A free new", release_date: "2026-08-01", cost: { input: 0 } },
|
||||
{ name: "A paid old", release_date: "2026-01-01", cost: { input: 1 } },
|
||||
].map((item) => ({ ...item, provider: { id: "opencode" } }))
|
||||
|
||||
expect(items.toSorted(compareModels).map((item) => item.name)).toEqual([
|
||||
"A free new",
|
||||
"Z free new",
|
||||
"A free old",
|
||||
"A paid new",
|
||||
"A paid old",
|
||||
])
|
||||
})
|
||||
|
||||
test("uses the existing free badge predicate, not zero cost on other providers", () => {
|
||||
expect(isFreeModel({ provider: { id: "opencode" } })).toBe(true)
|
||||
expect(isFreeModel({ provider: { id: "opencode" }, cost: { input: 0 } })).toBe(true)
|
||||
expect(isFreeModel({ provider: { id: "opencode" }, cost: { input: 1 } })).toBe(false)
|
||||
expect(isFreeModel({ provider: { id: "opencode-go" }, cost: { input: 0 } })).toBe(false)
|
||||
expect(isFreeModel({ provider: { id: "custom" } })).toBe(false)
|
||||
|
||||
const free = { provider: { id: "opencode" }, name: "Z missing cost", release_date: "2026-01-01" }
|
||||
const other = { provider: { id: "custom" }, name: "A zero cost", release_date: "2026-09-01", cost: { input: 0 } }
|
||||
expect([other, free].sort(compareModels)).toEqual([free, other])
|
||||
})
|
||||
|
||||
test("sorts missing and invalid release dates last with a name tie-breaker", () => {
|
||||
const items = [
|
||||
{ name: "B missing" },
|
||||
{ name: "C empty", release_date: "" },
|
||||
{ name: "A invalid", release_date: "not-a-date" },
|
||||
{ name: "Z dated", release_date: "2026-01-01" },
|
||||
].map((item) => ({ ...item, provider: { id: "opencode" } }))
|
||||
|
||||
expect(items.sort(compareModels).map((item) => item.name)).toEqual(["Z dated", "A invalid", "B missing", "C empty"])
|
||||
})
|
||||
|
||||
test("compares parsed instants rather than release date strings", () => {
|
||||
const older = { provider: { id: "custom" }, name: "A", release_date: "2026-08-02T00:00:00+10:00" }
|
||||
const newer = { provider: { id: "custom" }, name: "Z", release_date: "2026-08-01T20:00:00Z" }
|
||||
expect([older, newer].sort(compareModels)).toEqual([newer, older])
|
||||
})
|
||||
})
|
||||
@@ -1,17 +0,0 @@
|
||||
import { compareModelOrder } from "@opencode-ai/util/model-order"
|
||||
|
||||
type ModelOrderItem = {
|
||||
provider: { id: string }
|
||||
cost?: { input: number }
|
||||
release_date?: string
|
||||
name: string
|
||||
}
|
||||
|
||||
export const isFreeModel = (item: Pick<ModelOrderItem, "provider" | "cost">) =>
|
||||
item.provider.id === "opencode" && (!item.cost || item.cost.input === 0)
|
||||
|
||||
export const compareModels = (a: ModelOrderItem, b: ModelOrderItem) =>
|
||||
compareModelOrder(
|
||||
{ free: isFreeModel(a), released: Date.parse(a.release_date ?? "") || 0, name: a.name },
|
||||
{ free: isFreeModel(b), released: Date.parse(b.release_date ?? "") || 0, name: b.name },
|
||||
)
|
||||
@@ -21,10 +21,12 @@ import { handleDocumentSearchKeydown } from "@/shell/commands/search-keydown"
|
||||
import { createMenuDismissController } from "@/shell/commands/menu-dismiss"
|
||||
import { createEventListener } from "@solid-primitives/event-listener"
|
||||
import { matchesModelSearch } from "./search"
|
||||
import { compareModels, isFreeModel } from "./order"
|
||||
import { SettingsList } from "@/settings/list"
|
||||
import "@/settings/settings.css"
|
||||
|
||||
const isFree = (provider: string, cost: { input: number } | undefined) =>
|
||||
provider === "opencode" && (!cost || cost.input === 0)
|
||||
|
||||
type ModelState = ReturnType<typeof useLocal>["model"]
|
||||
type ModelItem = ReturnType<ModelState["list"]>[number]
|
||||
|
||||
@@ -62,13 +64,11 @@ const ModelList: Component<{
|
||||
const models = createMemo(() => controller.models(store.search))
|
||||
const groups = createMemo(() => controller.groups(models()))
|
||||
const expanded = (provider: string) => store.search.length > 0 || !store.collapsed[provider]
|
||||
const visibleModels = () => groups().flatMap((group) => (expanded(group.category) ? group.items : []))
|
||||
const visibleModels = () => models().filter((item) => expanded(item.provider.id))
|
||||
let scrollRef: HTMLDivElement | undefined
|
||||
|
||||
const setSearch = (value: string) => {
|
||||
const first = controller
|
||||
.groups(controller.models(value))
|
||||
.find((group) => value.length > 0 || !store.collapsed[group.category])?.items[0]
|
||||
const first = controller.models(value).find((item) => value.length > 0 || !store.collapsed[item.provider.id])
|
||||
setStore({ search: value, active: first ? modelKey(first) : "" })
|
||||
}
|
||||
const moveActive = (delta: number) => {
|
||||
@@ -187,12 +187,17 @@ const ModelList: Component<{
|
||||
gutter={12}
|
||||
openDelay={0}
|
||||
value={
|
||||
<ModelTooltip model={item} latest={item.latest} free={isFreeModel(item)} v2 />
|
||||
<ModelTooltip
|
||||
model={item}
|
||||
latest={item.latest}
|
||||
free={isFree(item.provider.id, item.cost)}
|
||||
v2
|
||||
/>
|
||||
}
|
||||
>
|
||||
<span class="min-w-0 truncate">{item.name}</span>
|
||||
</Tooltip>
|
||||
<Show when={isFreeModel(item)}>
|
||||
<Show when={isFree(item.provider.id, item.cost)}>
|
||||
<Badge class="shrink-0">{language.t("model.tag.free")}</Badge>
|
||||
</Show>
|
||||
<Show when={item.latest}>
|
||||
@@ -272,7 +277,7 @@ function createModelSelectorController(input: {
|
||||
const filtered = query
|
||||
? allModels().filter((item) => matchesModelSearch(query, [item.name, item.id, item.provider.name]))
|
||||
: allModels()
|
||||
return [...filtered].sort(compareModels)
|
||||
return [...filtered].sort((a, b) => a.name.localeCompare(b.name))
|
||||
},
|
||||
groups: (models: ModelItem[]) => {
|
||||
const byProvider = new Map<string, ModelItem[]>()
|
||||
@@ -309,7 +314,7 @@ function ModelSelectorPopoverView(props: {
|
||||
|
||||
const models = createMemo(() => props.models(store.search))
|
||||
const groups = createMemo(() => props.groups(models()))
|
||||
const keys = () => [...groups().flatMap((group) => group.items.map(modelKey)), manageKey]
|
||||
const keys = () => [...models().map(modelKey), manageKey]
|
||||
const initialActive = () => {
|
||||
const selected = props.current
|
||||
const options = keys()
|
||||
@@ -359,7 +364,7 @@ function ModelSelectorPopoverView(props: {
|
||||
queueMicrotask(() => activeItem()?.scrollIntoView({ block: "nearest" }))
|
||||
}
|
||||
const setSearch = (value: string) => {
|
||||
const first = props.groups(props.models(value))[0]?.items[0]
|
||||
const first = props.models(value)[0]
|
||||
setStore({ search: value, active: first ? modelKey(first) : manageKey })
|
||||
}
|
||||
|
||||
@@ -462,7 +467,14 @@ function ModelSelectorPopoverView(props: {
|
||||
placement="right-start"
|
||||
gutter={6}
|
||||
openDelay={0}
|
||||
value={<ModelTooltip model={item} latest={item.latest} free={isFreeModel(item)} v2 />}
|
||||
value={
|
||||
<ModelTooltip
|
||||
model={item}
|
||||
latest={item.latest}
|
||||
free={isFree(item.provider.id, item.cost)}
|
||||
v2
|
||||
/>
|
||||
}
|
||||
>
|
||||
<Menu.RadioItem
|
||||
value={modelKey(item)}
|
||||
@@ -477,7 +489,7 @@ function ModelSelectorPopoverView(props: {
|
||||
onSelect={() => selectModel(item)}
|
||||
>
|
||||
<span class="min-w-0 truncate leading-5">{item.name}</span>
|
||||
<Show when={isFreeModel(item)}>
|
||||
<Show when={isFree(item.provider.id, item.cost)}>
|
||||
<Badge class="shrink-0">{language.t("model.tag.free")}</Badge>
|
||||
</Show>
|
||||
<Show when={item.latest}>
|
||||
|
||||
@@ -11,7 +11,6 @@ import { useIntegrations } from "@/providers/catalog/integrations"
|
||||
import { decode64 } from "@/runtime/persistence/base64"
|
||||
import { useLanguage } from "@/runtime/i18n/language"
|
||||
import { ModelTooltip } from "./tooltip"
|
||||
import { compareModels, isFreeModel } from "./order"
|
||||
|
||||
type ModelState = ReturnType<typeof useLocal>["model"]
|
||||
const featuredProviders = ["opencode", "opencode-go", "openai", "anthropic", "google", "github-copilot"]
|
||||
@@ -30,7 +29,9 @@ export const DialogSelectModelUnpaid: Component<{ model?: ModelState }> = (props
|
||||
const c = model.current()
|
||||
return c ? `${c.provider.id}:${c.id}` : undefined
|
||||
})
|
||||
const freeModels = createMemo(() => model.list().filter(isFreeModel).sort(compareModels))
|
||||
const isFree = (item: ReturnType<ModelState["list"]>[number]) =>
|
||||
item.provider.id === "opencode" && (!item.cost || item.cost.input === 0)
|
||||
const freeModels = createMemo(() => model.list().filter(isFree))
|
||||
|
||||
const openProviders = (provider?: string) => {
|
||||
void import("@/providers/connect/dialog").then((x) => {
|
||||
@@ -93,7 +94,7 @@ export const DialogSelectModelUnpaid: Component<{ model?: ModelState }> = (props
|
||||
<ModelTooltip
|
||||
model={{ ...item, name: displayModelName(item.name) }}
|
||||
latest={item.latest}
|
||||
free={isFreeModel(item)}
|
||||
free={isFree(item)}
|
||||
v2
|
||||
/>
|
||||
}
|
||||
|
||||
@@ -427,11 +427,16 @@ export function SessionSidePanel(props: {
|
||||
</div>
|
||||
</Tabs.List>
|
||||
<div
|
||||
class="session-review-v2-open-in-app-slot shrink-0 flex items-center pr-3"
|
||||
data-slot="session-side-panel-actions"
|
||||
class="session-review-v2-open-in-app-slot self-start shrink-0 flex items-center gap-2 pe-3"
|
||||
classList={{ "h-[51px]": props.stacked, "h-12": !props.stacked }}
|
||||
onPointerDown={(event) => event.stopPropagation()}
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
>
|
||||
<OpenInAppButton directory={projectDirectory} />
|
||||
<Show when={reviewOpen()}>
|
||||
<div class="size-7 shrink-0" aria-hidden />
|
||||
</Show>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -3,6 +3,28 @@ import { Icon } from "@opencode-ai/ui/icon"
|
||||
import { IconButton } from "@opencode-ai/ui/icon-button"
|
||||
import { Keybind } from "@opencode-ai/ui/keybind"
|
||||
import { Tooltip } from "@opencode-ai/ui/tooltip"
|
||||
import { useCommand } from "@/shell/commands/command"
|
||||
import { reviewTooltipKeybind } from "@/shell/commands/tooltip-keybind"
|
||||
import { useLanguage } from "@/runtime/i18n/language"
|
||||
import { useSessionLayout } from "@/session/session-layout"
|
||||
|
||||
export function SessionReviewToggle() {
|
||||
const command = useCommand()
|
||||
const language = useLanguage()
|
||||
const { view } = useSessionLayout()
|
||||
|
||||
return (
|
||||
<SessionHeaderActions
|
||||
state={{
|
||||
reviewLabel: language.t("command.review.toggle"),
|
||||
reviewKeybind: reviewTooltipKeybind(command),
|
||||
reviewVisible: true,
|
||||
reviewOpened: view().reviewPanel.opened(),
|
||||
onReviewToggle: () => view().reviewPanel.toggle(),
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export type SessionHeaderActionsState = {
|
||||
reviewLabel: string
|
||||
|
||||
@@ -1,31 +1,19 @@
|
||||
import { createMemo, Show } from "solid-js"
|
||||
import { Show } from "solid-js"
|
||||
import { createMediaQuery } from "@solid-primitives/media"
|
||||
import { useCommand } from "@/shell/commands/command"
|
||||
import { useLanguage } from "@/runtime/i18n/language"
|
||||
import { useSettings } from "@/settings/model"
|
||||
import { useSessionLayout } from "@/session/session-layout"
|
||||
import { reviewTooltipKeybind } from "@/shell/commands/tooltip-keybind"
|
||||
import { StatusPopover } from "@/shell/status/status-popover"
|
||||
import { TitlebarRight } from "@/shell/titlebar/right-slot"
|
||||
import { Tooltip } from "@opencode-ai/ui/tooltip"
|
||||
import { SessionHeaderActions, type SessionHeaderActionsState } from "./session-header-actions"
|
||||
|
||||
export function SessionHeader() {
|
||||
const command = useCommand()
|
||||
const language = useLanguage()
|
||||
const settings = useSettings()
|
||||
const { view } = useSessionLayout()
|
||||
|
||||
const isDesktop = createMediaQuery("(min-width: 768px)")
|
||||
|
||||
const actions = createMemo<SessionHeaderActionsState>(() => ({
|
||||
reviewLabel: language.t("command.review.toggle"),
|
||||
reviewKeybind: reviewTooltipKeybind(command),
|
||||
reviewVisible: isDesktop(),
|
||||
reviewOpened: view().reviewPanel.opened(),
|
||||
onReviewToggle: () => view().reviewPanel.toggle(),
|
||||
}))
|
||||
|
||||
return (
|
||||
<>
|
||||
<TitlebarRight>
|
||||
@@ -35,7 +23,9 @@ export function SessionHeader() {
|
||||
</Tooltip>
|
||||
</Show>
|
||||
</TitlebarRight>
|
||||
<SessionHeaderActions state={actions()} />
|
||||
<Show when={isDesktop() && !view().reviewPanel.opened()}>
|
||||
<div class="size-7 shrink-0" aria-hidden />
|
||||
</Show>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -28,6 +28,7 @@ import { SessionContextTab } from "./files/session-context-tab"
|
||||
import { createSessionTimelineInteraction } from "./timeline/interaction"
|
||||
import { ActiveSessionComposerRegion, createActiveSessionRegion } from "./composer/region"
|
||||
import { SessionIdentityHeader } from "./session-identity-header"
|
||||
import { SessionReviewToggle } from "./header/session-header-actions"
|
||||
import { createAnimatedPresence } from "@/runtime/animated-presence"
|
||||
|
||||
const SessionMobileFiles = lazy(async () => {
|
||||
@@ -274,10 +275,19 @@ export function SessionScreen(props: { session: SessionModel }) {
|
||||
<>
|
||||
<div class="flex-1 min-h-0 flex flex-col gap-2 px-2 pb-[var(--shell-bottom-inset,8px)] pt-[var(--shell-top-inset,8px)]">
|
||||
<div ref={screen.panel.ref} class="relative flex-1 min-h-0 flex flex-col md:flex-row gap-2">
|
||||
{/* Keep the control outside panel animations; the terminal's 52px header includes a 1px divider. */}
|
||||
<Show when={isDesktop() && messagesReady() && session.identity.params.id}>
|
||||
<div
|
||||
class="absolute end-3 top-0 z-30 flex items-center"
|
||||
classList={{ "h-[51px]": sideTerminalVisible(), "h-12": !sideTerminalVisible() }}
|
||||
data-slot="session-review-toggle"
|
||||
>
|
||||
<SessionReviewToggle />
|
||||
</div>
|
||||
</Show>
|
||||
<div
|
||||
classList={{
|
||||
"@container relative z-10 min-w-0 shrink-0 flex flex-col min-h-0 h-full flex-1 md:flex-none transition-[width]":
|
||||
true,
|
||||
"@container relative z-10 min-w-0 shrink-0 flex flex-col min-h-0 h-full flex-1 md:flex-none transition-[width]": true,
|
||||
"duration-[240ms] ease-[cubic-bezier(0.22,1,0.36,1)] will-change-[width] motion-reduce:transition-none":
|
||||
!screen.size.active() && sidePresence.animate(),
|
||||
"transition-none": screen.size.active() || !sidePresence.animate(),
|
||||
@@ -408,6 +418,7 @@ export function SessionScreen(props: { session: SessionModel }) {
|
||||
present={store.sideTerminalPresent}
|
||||
animate={sidePresence.animate() || sideMotion().animateTerminal}
|
||||
contentHeight={screen.side.terminal.contentHeight()}
|
||||
reserveReviewToggle={!screen.side.region.open()}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -45,6 +45,7 @@ export function TerminalPanel(
|
||||
contentHeight?: string
|
||||
embedded?: boolean
|
||||
animate?: boolean
|
||||
reserveReviewToggle?: boolean
|
||||
} = {},
|
||||
) {
|
||||
const terminal = useTerminal()
|
||||
@@ -249,7 +250,10 @@ export function TerminalPanel(
|
||||
when={terminal.ready() || store.surfaces.length > 0}
|
||||
fallback={
|
||||
<div class="flex flex-col h-full pointer-events-none">
|
||||
<div class="h-10 flex items-center gap-2 px-2 border-b border-border-weaker-base bg-v2-background-bg-base overflow-hidden">
|
||||
<div
|
||||
class="h-10 flex items-center gap-2 px-2 border-b border-border-weaker-base bg-v2-background-bg-base overflow-hidden"
|
||||
classList={{ "pe-12": props.reserveReviewToggle }}
|
||||
>
|
||||
<For each={handoff()}>
|
||||
{(title) => (
|
||||
<div class="px-2 py-1 rounded-md bg-surface-base text-14-regular text-text-weak truncate max-w-40">
|
||||
@@ -291,46 +295,53 @@ export function TerminalPanel(
|
||||
}}
|
||||
>
|
||||
<div class="flex flex-col h-full">
|
||||
<Tabs
|
||||
variant="panel"
|
||||
value={terminal.active()}
|
||||
onChange={(id) => terminal.open(id)}
|
||||
class="!h-[52px] !flex-none"
|
||||
>
|
||||
<Tabs.List
|
||||
ref={tabList}
|
||||
onPointerDown={(event: PointerEvent & { currentTarget: HTMLDivElement }) => {
|
||||
const active = document.activeElement
|
||||
if (event.target === active) return
|
||||
if (active instanceof HTMLInputElement && event.currentTarget.contains(active)) active.blur()
|
||||
}}
|
||||
<div class="h-[52px] shrink-0 flex border-b border-border-weaker-base">
|
||||
<Tabs
|
||||
variant="panel"
|
||||
value={terminal.active()}
|
||||
onChange={(id) => terminal.open(id)}
|
||||
class="!h-full min-w-0 !flex-1"
|
||||
>
|
||||
<For each={all()}>
|
||||
{(pty, index) => <SortableTerminalTab terminal={pty} index={index()} onClose={close} />}
|
||||
</For>
|
||||
<div class="h-full flex items-center justify-center">
|
||||
<Tooltip
|
||||
value={
|
||||
<>
|
||||
{language.t("command.terminal.new")}
|
||||
<Show when={newTerminalKeybind().length > 0}>
|
||||
<Keybind keys={newTerminalKeybind()} variant="neutral" />
|
||||
</Show>
|
||||
</>
|
||||
}
|
||||
placement="bottom"
|
||||
class="flex items-center"
|
||||
>
|
||||
<IconButton
|
||||
icon={<Icon name="plus-small" size="large" />}
|
||||
variant="ghost"
|
||||
onClick={() => terminal.new({ focus: true })}
|
||||
aria-label={language.t("command.terminal.new")}
|
||||
/>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</Tabs.List>
|
||||
</Tabs>
|
||||
<Tabs.List
|
||||
ref={tabList}
|
||||
class="!border-b-0"
|
||||
onPointerDown={(event: PointerEvent & { currentTarget: HTMLDivElement }) => {
|
||||
const active = document.activeElement
|
||||
if (event.target === active) return
|
||||
if (active instanceof HTMLInputElement && event.currentTarget.contains(active)) active.blur()
|
||||
}}
|
||||
>
|
||||
<For each={all()}>
|
||||
{(pty, index) => <SortableTerminalTab terminal={pty} index={index()} onClose={close} />}
|
||||
</For>
|
||||
<div class="h-full flex items-center justify-center">
|
||||
<Tooltip
|
||||
value={
|
||||
<>
|
||||
{language.t("command.terminal.new")}
|
||||
<Show when={newTerminalKeybind().length > 0}>
|
||||
<Keybind keys={newTerminalKeybind()} variant="neutral" />
|
||||
</Show>
|
||||
</>
|
||||
}
|
||||
placement="bottom"
|
||||
class="flex items-center"
|
||||
>
|
||||
<IconButton
|
||||
icon={<Icon name="plus-small" size="large" />}
|
||||
variant="ghost"
|
||||
onClick={() => terminal.new({ focus: true })}
|
||||
aria-label={language.t("command.terminal.new")}
|
||||
/>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</Tabs.List>
|
||||
</Tabs>
|
||||
{/* Reserve outside the scroll viewport so overflowing tabs cannot cover the toggle. */}
|
||||
<Show when={props.reserveReviewToggle}>
|
||||
<div class="w-12 shrink-0" aria-hidden />
|
||||
</Show>
|
||||
</div>
|
||||
<div class="flex-1 min-h-0 relative">
|
||||
<For each={store.surfaces}>
|
||||
{(surface) => (
|
||||
|
||||
@@ -9,7 +9,6 @@ import { Schema } from "effect"
|
||||
import { Persistence } from "@/runtime/persistence/schema"
|
||||
import { useLanguage } from "@/runtime/i18n/language"
|
||||
import { useModels } from "@/providers/models/models"
|
||||
import { compareModels } from "@/providers/models/order"
|
||||
import { useServerSDK } from "@/runtime/server/client"
|
||||
import { popularProviders } from "@/providers/catalog/providers"
|
||||
import { Persist, persisted } from "@/runtime/persistence/storage"
|
||||
@@ -40,7 +39,7 @@ export const SettingsModels: Component = () => {
|
||||
items: (_filter) => models.list(),
|
||||
key: (x) => `${x.provider.id}:${x.id}`,
|
||||
filterKeys: ["provider.name", "name", "id"],
|
||||
sortBy: compareModels,
|
||||
sortBy: (a, b) => a.name.localeCompare(b.name),
|
||||
groupBy: (x) => x.provider.id,
|
||||
sortGroupsBy: (a, b) => {
|
||||
const aIndex = popularProviders.indexOf(a.category)
|
||||
|
||||
@@ -60,7 +60,6 @@
|
||||
|
||||
.settings-screen .settings-tab-body {
|
||||
padding-inline: 0;
|
||||
padding-bottom: var(--settings-bottom-inset, 0px);
|
||||
}
|
||||
|
||||
.settings-nav {
|
||||
@@ -98,6 +97,7 @@
|
||||
|
||||
.settings-about-content {
|
||||
display: flex;
|
||||
flex-shrink: 0;
|
||||
width: 100%;
|
||||
max-width: 560px;
|
||||
min-height: 462px;
|
||||
@@ -105,7 +105,7 @@
|
||||
align-items: center;
|
||||
justify-content: flex-start;
|
||||
gap: 24px;
|
||||
padding-block: 80px 32px;
|
||||
padding-block: 80px calc(80px + var(--settings-bottom-inset, 0px));
|
||||
color: var(--v2-text-text-muted);
|
||||
font-size: 13px;
|
||||
font-weight: 440;
|
||||
@@ -273,7 +273,7 @@
|
||||
flex-direction: column;
|
||||
gap: 36px;
|
||||
width: 100%;
|
||||
padding: 0 40px 40px;
|
||||
padding: 0 40px calc(80px + var(--settings-bottom-inset, 0px));
|
||||
}
|
||||
|
||||
[data-slot="settings-row-description"] a.settings-link {
|
||||
@@ -1170,7 +1170,7 @@
|
||||
}
|
||||
|
||||
.settings-tab-body.settings-workspaces {
|
||||
padding: 0 20px 24px;
|
||||
padding-inline: 20px;
|
||||
}
|
||||
|
||||
.settings-workspaces-toolbar,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
[data-component="timeline-detail-control"] {
|
||||
position: relative;
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
flex-direction: column;
|
||||
@@ -105,7 +106,6 @@
|
||||
[data-slot="timeline-detail-advanced"] {
|
||||
margin-top: 4px;
|
||||
padding-top: 8px;
|
||||
border-top: 0.5px solid var(--v2-border-border-base);
|
||||
}
|
||||
|
||||
[data-slot="timeline-detail-advanced"] > [data-slot="collapsible-trigger"] {
|
||||
|
||||
@@ -442,9 +442,11 @@ export function Titlebar(props: {
|
||||
"pt-[max(0px,calc(8px-env(safe-area-inset-top,0px)))]": !bottom() && !windows(),
|
||||
"pb-[max(0px,calc(8px-env(safe-area-inset-bottom,0px)))]": bottom(),
|
||||
"pl-4": macTrafficLights(),
|
||||
// Center the 20px app icon over the sidebar's 16px icon column.
|
||||
"ps-3.5": windows(),
|
||||
}}
|
||||
>
|
||||
<Show when={!mobile() && !props.verticalTabs}>
|
||||
<Show when={!mobile() && (!props.verticalTabs || windows())}>
|
||||
<ChannelIndicator horizontal debugTools={props.debugTools} />
|
||||
</Show>
|
||||
<Show when={windows() || linux()}>
|
||||
@@ -641,7 +643,9 @@ export function Titlebar(props: {
|
||||
data-tauri-drag-region
|
||||
/>
|
||||
</Show>
|
||||
<ChannelIndicator sidebar debugTools={props.debugTools} />
|
||||
<Show when={!windows()}>
|
||||
<ChannelIndicator sidebar debugTools={props.debugTools} />
|
||||
</Show>
|
||||
{homeButton(true)}
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -1,6 +1,16 @@
|
||||
export * as SessionCompaction from "./compaction.js"
|
||||
|
||||
import { LLMClient, LLMEvent, LLMRequest, Message, type ContentPart } from "@opencode-ai/ai"
|
||||
import {
|
||||
AIError,
|
||||
InvalidProviderOutputError,
|
||||
UnknownProviderError,
|
||||
isContextOverflowFailure,
|
||||
LLMClient,
|
||||
LLMEvent,
|
||||
LLMRequest,
|
||||
Message,
|
||||
type ContentPart,
|
||||
} from "@opencode-ai/ai"
|
||||
import { Agent } from "@opencode-ai/schema/agent"
|
||||
import { SessionError } from "@opencode-ai/schema/session-error"
|
||||
import { Context, Effect, Layer, Stream } from "effect"
|
||||
@@ -12,6 +22,7 @@ import type { SessionContext } from "./context.js"
|
||||
import type { SessionMessage } from "./message.js"
|
||||
import { SessionModelRequest } from "./model-request.js"
|
||||
import type { SessionRunnerModel } from "./runner/model.js"
|
||||
import { SessionRunnerRetry } from "./runner/retry.js"
|
||||
import { SessionSchema } from "./schema.js"
|
||||
import { toSessionError } from "./to-session-error.js"
|
||||
import { Token } from "../util/token.js"
|
||||
@@ -405,68 +416,105 @@ export const layer = Layer.effect(
|
||||
],
|
||||
},
|
||||
})
|
||||
// Ignored tool calls never enter the follow-up history or need fabricated results.
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
chunks.length = 0
|
||||
providerState = undefined
|
||||
yield* llm
|
||||
.stream(
|
||||
attempt === 0
|
||||
? prepared.request
|
||||
: LLMRequest.update(prepared.request, {
|
||||
messages: [
|
||||
...prepared.request.messages,
|
||||
Message.user(
|
||||
"The previous response did not fill in the required summary template. Do not call tools. Return the summary as text using the exact section headings from the template.",
|
||||
),
|
||||
],
|
||||
}),
|
||||
prepared.options,
|
||||
)
|
||||
.pipe(
|
||||
Stream.runForEach((event) => {
|
||||
if (LLMEvent.is.providerError(event))
|
||||
failure = {
|
||||
type: event.classification === "context-overflow" ? "provider.invalid-request" : "provider.error",
|
||||
message: event.message,
|
||||
}
|
||||
if (LLMEvent.is.textDelta(event)) {
|
||||
chunks.push(event.text)
|
||||
return bus.publish(SessionEvent.Compaction.Delta, {
|
||||
sessionID: context.session.id,
|
||||
text: event.text,
|
||||
})
|
||||
}
|
||||
if (LLMEvent.is.stepFinish(event)) {
|
||||
providerState =
|
||||
event.providerMetadata?.[
|
||||
context.model.model.route.providerMetadataKey ?? context.model.model.provider
|
||||
]
|
||||
const step = SessionUsage.record(event.usage, context.model.cost)
|
||||
usage = usage ? SessionUsage.add(usage, step) : step
|
||||
}
|
||||
return Effect.void
|
||||
}),
|
||||
Effect.catchTag("AI.Error", (error) =>
|
||||
Effect.sync(() => {
|
||||
failure = toSessionError(error)
|
||||
}),
|
||||
const retry = yield* SessionRunnerRetry.policy(context.session.id)
|
||||
// Both requests share the retry allowance; rejected output never enters the reminder request.
|
||||
for (const request of [
|
||||
prepared.request,
|
||||
LLMRequest.update(prepared.request, {
|
||||
messages: [
|
||||
...prepared.request.messages,
|
||||
Message.user(
|
||||
"The previous response did not fill in the required summary template. Do not call tools. Return the summary as text using the exact section headings from the template.",
|
||||
),
|
||||
Effect.onInterrupt(() =>
|
||||
recordUsage.pipe(
|
||||
Effect.andThen(
|
||||
input.reason === "auto"
|
||||
? failed({
|
||||
sessionID: context.session.id,
|
||||
reason: input.reason,
|
||||
error: { type: "compaction.interrupted", message: "Compaction was interrupted" },
|
||||
inputID: input.inputID,
|
||||
}).pipe(Effect.asVoid)
|
||||
: Effect.void,
|
||||
),
|
||||
],
|
||||
}),
|
||||
]) {
|
||||
yield* Stream.suspend(() => {
|
||||
chunks.length = 0
|
||||
providerState = undefined
|
||||
failure = undefined
|
||||
return llm.stream(request, prepared.options)
|
||||
}).pipe(
|
||||
Stream.runForEach((event) => {
|
||||
if (LLMEvent.is.providerError(event))
|
||||
failure = {
|
||||
type: event.classification === "context-overflow" ? "provider.invalid-request" : "provider.error",
|
||||
message: event.message,
|
||||
}
|
||||
if (LLMEvent.is.textDelta(event)) {
|
||||
chunks.push(event.text)
|
||||
return bus.publish(SessionEvent.Compaction.Delta, {
|
||||
sessionID: context.session.id,
|
||||
text: event.text,
|
||||
})
|
||||
}
|
||||
if (LLMEvent.is.stepFinish(event)) {
|
||||
providerState =
|
||||
event.providerMetadata?.[context.model.model.route.providerMetadataKey ?? context.model.model.provider]
|
||||
const step = SessionUsage.record(event.usage, context.model.cost)
|
||||
usage = usage ? SessionUsage.add(usage, step) : step
|
||||
}
|
||||
if (LLMEvent.is.finish(event)) {
|
||||
if (event.reason.normalized === "length")
|
||||
failure = { type: "compaction.failed", message: "Compaction summary reached the output token limit" }
|
||||
if (event.reason.normalized === "content-filter")
|
||||
failure = {
|
||||
type: "provider.content-filter",
|
||||
message: "Compaction summary was blocked by the provider",
|
||||
}
|
||||
if (event.reason.normalized === "unknown")
|
||||
return Effect.fail(
|
||||
new AIError({
|
||||
reason: new InvalidProviderOutputError({
|
||||
message: "The provider response ended with an unknown finish reason.",
|
||||
classification: "incomplete-stream",
|
||||
}),
|
||||
}),
|
||||
)
|
||||
if (event.reason.normalized === "error")
|
||||
return Effect.fail(
|
||||
new AIError({ reason: new UnknownProviderError({ message: "Compaction generation failed" }) }),
|
||||
)
|
||||
}
|
||||
return Effect.void
|
||||
}),
|
||||
Effect.retry({
|
||||
while: (cause) =>
|
||||
Effect.gen(function* () {
|
||||
if (isContextOverflowFailure(cause)) return false
|
||||
const decision = yield* retry({
|
||||
cause,
|
||||
error: toSessionError(cause),
|
||||
agent: Agent.ID.make("compaction"),
|
||||
model: context.model.ref,
|
||||
hook: prepared.retry,
|
||||
retry: SessionRunnerRetry.isRetryable(cause),
|
||||
})
|
||||
if (!decision.retry) return false
|
||||
yield* Effect.sleep(decision.delay)
|
||||
return true
|
||||
}),
|
||||
}),
|
||||
Effect.catchTag("AI.Error", (error) =>
|
||||
Effect.sync(() => {
|
||||
failure = toSessionError(error)
|
||||
}),
|
||||
),
|
||||
Effect.onInterrupt(() =>
|
||||
recordUsage.pipe(
|
||||
Effect.andThen(
|
||||
input.reason === "auto"
|
||||
? failed({
|
||||
sessionID: context.session.id,
|
||||
reason: input.reason,
|
||||
error: { type: "compaction.interrupted", message: "Compaction was interrupted" },
|
||||
inputID: input.inputID,
|
||||
}).pipe(Effect.asVoid)
|
||||
: Effect.void,
|
||||
),
|
||||
),
|
||||
)
|
||||
),
|
||||
)
|
||||
if (failure || hasSummarySection(chunks.join(""))) break
|
||||
}
|
||||
yield* recordUsage
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
export * as SessionRunnerLLM from "./llm.js"
|
||||
|
||||
import { Message } from "@opencode-ai/ai"
|
||||
import { and, desc, eq, sql } from "drizzle-orm"
|
||||
import { Cause, Effect, Exit, FiberMap, Layer } from "effect"
|
||||
import { Database } from "../../database/database.js"
|
||||
import { Bus } from "../../bus.js"
|
||||
@@ -15,6 +16,7 @@ import { SessionModelTransport } from "../model-transport.js"
|
||||
import { SessionMessage } from "../message.js"
|
||||
import { SessionSchema } from "../schema.js"
|
||||
import { SessionStore } from "../store.js"
|
||||
import { SessionMessageTable } from "../sql.js"
|
||||
import { SessionTitle } from "../title.js"
|
||||
import { DrainResult, Service, type Interface } from "./index.js"
|
||||
import { Snapshot } from "../../snapshot.js"
|
||||
@@ -59,6 +61,7 @@ const layer = Layer.effect(
|
||||
if (promotable === "steer" && pending.delivery === "queue" && !control) return DrainResult.Complete()
|
||||
}
|
||||
yield* plugins.awaitActivation
|
||||
yield* settleStaleCompactions(sessionID)
|
||||
yield* settleStaleToolCalls(sessionID)
|
||||
|
||||
const advanceToStep = Effect.fn("SessionRunner.advanceToStep")(() =>
|
||||
@@ -276,6 +279,36 @@ const layer = Layer.effect(
|
||||
}
|
||||
})
|
||||
|
||||
const settleStaleCompactions = Effect.fn("SessionRunner.settleStaleCompactions")(function* (
|
||||
sessionID: SessionSchema.ID,
|
||||
) {
|
||||
// A process death skips compaction finalizers. Include orphans behind a
|
||||
// completed checkpoint, and settle newest first to match event projection.
|
||||
const rows = yield* db
|
||||
.select()
|
||||
.from(SessionMessageTable)
|
||||
.where(
|
||||
and(
|
||||
eq(SessionMessageTable.session_id, sessionID),
|
||||
eq(SessionMessageTable.type, "compaction"),
|
||||
sql`json_extract(${SessionMessageTable.data}, '$.status') = 'running'`,
|
||||
),
|
||||
)
|
||||
.orderBy(desc(SessionMessageTable.seq))
|
||||
.all()
|
||||
.pipe(Effect.orDie)
|
||||
for (const row of rows) {
|
||||
const message = yield* SessionHistory.decodeMessageRow(row)
|
||||
if (message.type !== "compaction") continue
|
||||
yield* bus.publish(SessionEvent.Compaction.Failed, {
|
||||
sessionID,
|
||||
reason: message.reason,
|
||||
inputID: message.id,
|
||||
error: { type: "compaction.interrupted", message: "Compaction was interrupted" },
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
const settleStaleToolCalls = Effect.fn("SessionRunner.settleStaleToolCalls")(function* (
|
||||
sessionID: SessionSchema.ID,
|
||||
) {
|
||||
|
||||
@@ -78,11 +78,11 @@ const schedule = Schedule.max([Schedule.exponential("2 seconds"), Schedule.recur
|
||||
}),
|
||||
)
|
||||
|
||||
export const make = (bus: Bus.Interface, sessionID: SessionSchema.ID) =>
|
||||
export const policy = (sessionID: SessionSchema.ID) =>
|
||||
Effect.gen(function* () {
|
||||
const step = yield* Schedule.toStep(schedule)
|
||||
let attempt = 1
|
||||
const decide = (input: Input) =>
|
||||
return (input: Input) =>
|
||||
Effect.gen(function* () {
|
||||
const now = yield* Clock.currentTimeMillis
|
||||
const next = yield* step(now, input).pipe(Pull.catchDone(() => Effect.succeed(undefined)))
|
||||
@@ -104,6 +104,11 @@ export const make = (bus: Bus.Interface, sessionID: SessionSchema.ID) =>
|
||||
Number.isFinite(event.decision.delay) && event.decision.delay >= 0 ? Math.ceil(event.decision.delay) : delay
|
||||
return { retry: true as const, attempt, delay: normalized }
|
||||
})
|
||||
})
|
||||
|
||||
export const make = (bus: Bus.Interface, sessionID: SessionSchema.ID) =>
|
||||
Effect.gen(function* () {
|
||||
const decide = yield* policy(sessionID)
|
||||
const wait = (input: {
|
||||
readonly decision: Decision
|
||||
readonly assistantMessageID: SessionMessage.ID
|
||||
|
||||
@@ -69,12 +69,16 @@ async function createRegistryFixture(directory: string) {
|
||||
await Bun.$`tar -czf package.tgz package`.cwd(root)
|
||||
tarballs.set(version, await Bun.file(path.join(root, "package.tgz")).bytes())
|
||||
}
|
||||
const state = { latest: "1.0.0" }
|
||||
const state = { latest: "1.0.0", audits: 0 }
|
||||
const server = Bun.serve({
|
||||
hostname: "127.0.0.1",
|
||||
port: 0,
|
||||
fetch(request) {
|
||||
const url = new URL(request.url)
|
||||
if (url.pathname.startsWith("/-/npm/v1/security/")) {
|
||||
state.audits++
|
||||
return Response.json({})
|
||||
}
|
||||
if (decodeURIComponent(url.pathname) === "/@fixture/registry-plugin")
|
||||
return Response.json({
|
||||
name: "@fixture/registry-plugin",
|
||||
@@ -97,7 +101,7 @@ async function createRegistryFixture(directory: string) {
|
||||
await fs.mkdir(root, { recursive: true })
|
||||
await Bun.write(
|
||||
path.join(root, ".npmrc"),
|
||||
`@fixture:registry=${server.url}\ncache=${path.join(directory, "npm-cache")}\nfetch-retries=0\naudit=false\n`,
|
||||
`registry=${server.url}\n@fixture:registry=${server.url}\ncache=${path.join(directory, "npm-cache")}\nfetch-retries=0\naudit=true\n`,
|
||||
)
|
||||
return root
|
||||
},
|
||||
@@ -359,6 +363,25 @@ describe("Npm.resolve", () => {
|
||||
})
|
||||
|
||||
describe("Npm.check and Npm.update", () => {
|
||||
test("installs and updates without requesting registry audits", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
await using registry = await createRegistryFixture(tmp.path)
|
||||
const cache = path.join(tmp.path, "cache")
|
||||
const spec = "@fixture/registry-plugin@latest"
|
||||
await registry.configure(cache, spec)
|
||||
|
||||
await Effect.gen(function* () {
|
||||
const npm = yield* Npm.Service
|
||||
expect((yield* npm.add(spec)).version).toBe("1.0.0")
|
||||
expect(registry.state.audits).toBe(0)
|
||||
|
||||
registry.state.latest = "1.1.0"
|
||||
expect((yield* npm.update(spec)).version).toBe("1.1.0")
|
||||
expect(registry.state.audits).toBe(0)
|
||||
expect((yield* npm.resolve(spec)).version).toBe("1.1.0")
|
||||
}).pipe(Effect.scoped, Effect.provide(npmLayer(cache)), Effect.runPromise)
|
||||
})
|
||||
|
||||
test("checks a mutable registry target without mutation and explicitly updates it", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
await using registry = await createRegistryFixture(tmp.path)
|
||||
|
||||
@@ -4,6 +4,10 @@ import path from "path"
|
||||
import { Global } from "@opencode-ai/util/global"
|
||||
|
||||
describe("Core test environment", () => {
|
||||
test("disables public npm security audits", () => {
|
||||
expect(process.env.NPM_CONFIG_AUDIT).toBe("false")
|
||||
})
|
||||
|
||||
test("isolates global home and XDG roots", () => {
|
||||
const home = process.env.OPENCODE_TEST_HOME
|
||||
expect(home).toBeDefined()
|
||||
|
||||
@@ -1 +1,2 @@
|
||||
process.env.OPENCODE_DB = ":memory:"
|
||||
process.env.NPM_CONFIG_AUDIT = "false"
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import {
|
||||
AIError,
|
||||
HttpContext,
|
||||
LLMEvent,
|
||||
LLMRequest,
|
||||
Message,
|
||||
@@ -2260,21 +2261,151 @@ describe("SessionRunnerLLM", () => {
|
||||
}
|
||||
}
|
||||
|
||||
scenario("preserves typed provider failures from manual compaction", function* (s) {
|
||||
scenario("restarts compaction drafts after transient failures and unsuccessful finishes", function* (s) {
|
||||
yield* s.llm.push(TestLLM.text("Earlier answer", "text-manual-failure-history"))
|
||||
yield* s.runPrompt("Earlier question")
|
||||
|
||||
yield* s.llm.push(Stream.fail(providerUnavailable()))
|
||||
s.requests.length = 0
|
||||
const hooks = yield* PluginHooks.Service
|
||||
const retries: PluginHooks.Domains["session"]["retry"][] = []
|
||||
yield* hooks.register("session", "retry", (event) =>
|
||||
Effect.sync(() => {
|
||||
retries.push({ ...event })
|
||||
event.decision = { retry: true, delay: 0 }
|
||||
}),
|
||||
)
|
||||
const draft = TestLLM.complete(
|
||||
{
|
||||
reason: { normalized: "unknown" },
|
||||
usage: { nonCachedInputTokens: 10 },
|
||||
providerMetadata: { openai: { responseId: "discarded-draft" } },
|
||||
},
|
||||
LLMEvent.textDelta({ id: "draft", text: "## Objective\n- Partial draft" }),
|
||||
)
|
||||
yield* s.llm.push(
|
||||
TestLLM.failAfter(streamDisconnected(), ...draft.slice(0, -1)),
|
||||
draft,
|
||||
TestLLM.complete(
|
||||
{ reason: { normalized: "error" } },
|
||||
LLMEvent.textDelta({ id: "failed", text: "## Objective\n- Failed draft" }),
|
||||
),
|
||||
Stream.fail(rateLimited(60_000)),
|
||||
TestLLM.textWithUsage("## Objective\n- Accepted summary", "accepted", 30),
|
||||
)
|
||||
const compaction = yield* s.session.compact({ sessionID })
|
||||
yield* s.resume
|
||||
|
||||
expect(s.requests).toHaveLength(5)
|
||||
for (const request of s.requests) expect(request).toEqual(s.requests[0])
|
||||
expect(retries.map((event) => event.attempt)).toEqual([2, 3, 4, 5])
|
||||
expect(retries.every((event) => event.sessionID === sessionID && event.agent === "compaction")).toBe(true)
|
||||
expect(retries[3].decision).toEqual({ retry: true, delay: 60_000 })
|
||||
expect((yield* s.messages).find((message) => message.id === compaction.id)).toMatchObject({
|
||||
status: "completed",
|
||||
summary: "## Objective\n- Accepted summary",
|
||||
})
|
||||
expect(JSON.stringify(yield* s.messages)).not.toContain("discarded-draft")
|
||||
expect((yield* s.session.get(sessionID))?.tokens.input).toBe(50)
|
||||
})
|
||||
|
||||
scenario("bounds compaction network retries across a template correction", function* (s) {
|
||||
yield* s.llm.push(TestLLM.text("Earlier answer", "history"))
|
||||
yield* s.runPrompt("Earlier question")
|
||||
s.requests.length = 0
|
||||
const hooks = yield* PluginHooks.Service
|
||||
const attempts: number[] = []
|
||||
yield* hooks.register("session", "retry", (event) =>
|
||||
Effect.sync(() => {
|
||||
attempts.push(event.attempt)
|
||||
expect(event.decision).toMatchObject({ retry: true })
|
||||
event.decision = { retry: true, delay: 0 }
|
||||
}),
|
||||
)
|
||||
yield* s.llm.push(Stream.fail(providerUnavailable()), TestLLM.text("Not a summary", "invalid"))
|
||||
yield* s.llm.always(Stream.fail(providerUnavailable()))
|
||||
const compaction = yield* s.session.compact({ sessionID })
|
||||
yield* s.resume
|
||||
|
||||
expect(attempts).toEqual([2, 3, 4, 5])
|
||||
expect(s.requests).toHaveLength(6)
|
||||
expect((yield* s.messages).find((message) => message.id === compaction.id)).toMatchObject({
|
||||
type: "compaction",
|
||||
status: "failed",
|
||||
error: { type: "provider.transport", message: "Provider unavailable" },
|
||||
})
|
||||
expect((yield* s.context).some((message) => message.type === "user" && message.text === "Earlier question")).toBe(
|
||||
true,
|
||||
)
|
||||
})
|
||||
|
||||
for (const header of [false, true]) {
|
||||
scenario(`stops compaction retries through the ${header ? "provider header" : "retry hook"}`, function* (s) {
|
||||
yield* s.llm.push(TestLLM.text("Earlier answer", "history"))
|
||||
yield* s.runPrompt("Earlier question")
|
||||
s.requests.length = 0
|
||||
const hooks = yield* PluginHooks.Service
|
||||
yield* hooks.register("session", "retry", (event) =>
|
||||
Effect.sync(() => {
|
||||
expect(event.decision.retry).toBe(!header)
|
||||
event.decision = { retry: false }
|
||||
}),
|
||||
)
|
||||
yield* s.llm.push(
|
||||
Stream.fail(
|
||||
header
|
||||
? new AIError({
|
||||
reason: new TransportError({
|
||||
message: "Connection closed",
|
||||
transport: "http",
|
||||
operation: "read",
|
||||
http: new HttpContext({
|
||||
url: "https://example.com",
|
||||
status: 200,
|
||||
headers: { "x-should-retry": "false" },
|
||||
}),
|
||||
}),
|
||||
})
|
||||
: incompleteStream(),
|
||||
),
|
||||
)
|
||||
const compaction = yield* s.session.compact({ sessionID })
|
||||
yield* s.resume
|
||||
|
||||
expect(s.requests).toHaveLength(1)
|
||||
expect((yield* s.messages).find((message) => message.id === compaction.id)).toMatchObject({
|
||||
status: "failed",
|
||||
error: { type: header ? "provider.transport" : "provider.invalid-output" },
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
for (const response of ["length", "content-filter", "context overflow"] as const) {
|
||||
scenario(`rejects compaction ${response} without retrying or committing its draft`, function* (s) {
|
||||
yield* s.llm.push(TestLLM.text("Earlier answer", "history"))
|
||||
yield* s.runPrompt("Earlier question")
|
||||
s.requests.length = 0
|
||||
yield* s.llm.push(
|
||||
response === "context overflow"
|
||||
? Stream.fail(
|
||||
new AIError({
|
||||
reason: new InvalidRequestError({ message: "Too long", classification: "context-overflow" }),
|
||||
}),
|
||||
)
|
||||
: TestLLM.complete(
|
||||
{ reason: { normalized: response } },
|
||||
LLMEvent.textDelta({ id: "truncated", text: "## Objective\n- Incomplete summary" }),
|
||||
),
|
||||
)
|
||||
const compaction = yield* s.session.compact({ sessionID })
|
||||
yield* s.resume
|
||||
|
||||
expect(s.requests).toHaveLength(1)
|
||||
expect((yield* s.messages).find((message) => message.id === compaction.id)).toMatchObject({ status: "failed" })
|
||||
yield* s.llm.push(TestLLM.text("Continued", "continued"))
|
||||
yield* s.runPrompt("Continue")
|
||||
expect(userTexts(s.requests[1])).toContain("Earlier question")
|
||||
expect(JSON.stringify(s.requests[1])).not.toContain("Incomplete summary")
|
||||
})
|
||||
}
|
||||
|
||||
scenario("records cancelled manual compaction without surfacing an internal failure", function* (s) {
|
||||
yield* s.llm.push(TestLLM.text("Earlier answer", "text-manual-interrupt-history"))
|
||||
yield* s.runPrompt("Earlier question")
|
||||
@@ -3472,6 +3603,83 @@ describe("SessionRunnerLLM", () => {
|
||||
expect(userTexts(s.requests[1])).toEqual(["Start working", "Recover with this"])
|
||||
})
|
||||
|
||||
scenario("settles abandoned compactions before continuing after a process crash", function* (s) {
|
||||
yield* s.runPrompt("History before the crash")
|
||||
const first = SessionMessage.ID.create()
|
||||
const completed = SessionMessage.ID.create()
|
||||
const last = SessionMessage.ID.create()
|
||||
yield* s.bus.publish(SessionEvent.Compaction.Started, {
|
||||
sessionID,
|
||||
reason: "manual",
|
||||
inputID: first,
|
||||
recent: "",
|
||||
})
|
||||
yield* s.bus.publish(SessionEvent.Compaction.Started, {
|
||||
sessionID,
|
||||
reason: "manual",
|
||||
inputID: completed,
|
||||
recent: "",
|
||||
})
|
||||
yield* s.bus.publish(SessionEvent.Compaction.Ended, {
|
||||
sessionID,
|
||||
reason: "manual",
|
||||
text: "## Objective\n- Earlier completed checkpoint",
|
||||
recent: "",
|
||||
})
|
||||
yield* s.bus.publish(SessionEvent.Compaction.Started, {
|
||||
sessionID,
|
||||
reason: "auto",
|
||||
inputID: last,
|
||||
recent: "",
|
||||
})
|
||||
|
||||
// These starts have no terminal events, as after SIGKILL. The older orphan
|
||||
// is outside model-visible history; recovery must settle it as well.
|
||||
expect(
|
||||
(yield* s.messages).filter((message) => message.type === "compaction" && message.status === "running"),
|
||||
).toHaveLength(2)
|
||||
yield* s.llm.push(TestLLM.text("Recovered response", "recovered"))
|
||||
const run = yield* s.resumePaused
|
||||
expect((yield* s.messages).filter((message) => message.type === "compaction").toReversed()).toMatchObject([
|
||||
{ id: first, status: "failed", reason: "manual", error: { type: "compaction.interrupted" } },
|
||||
{ id: completed, status: "completed", summary: "## Objective\n- Earlier completed checkpoint" },
|
||||
{ id: last, status: "failed", reason: "auto", error: { type: "compaction.interrupted" } },
|
||||
])
|
||||
yield* run.finish
|
||||
|
||||
yield* s.llm.push(TestLLM.text("## Objective\n- New checkpoint", "new-summary"))
|
||||
const next = yield* s.session.compact({ sessionID })
|
||||
yield* s.session.wait(sessionID)
|
||||
expect((yield* s.messages).find((message) => message.id === next.id)).toMatchObject({
|
||||
status: "completed",
|
||||
summary: "## Objective\n- New checkpoint",
|
||||
})
|
||||
expect(
|
||||
(yield* s.messages).filter((message) => message.type === "compaction" && message.status === "running"),
|
||||
).toHaveLength(0)
|
||||
})
|
||||
|
||||
scenario("settles an abandoned compaction before delivering another manual compaction", function* (s) {
|
||||
yield* s.runPrompt("History before the crash")
|
||||
const previous = SessionMessage.ID.create()
|
||||
yield* s.bus.publish(SessionEvent.Compaction.Started, {
|
||||
sessionID,
|
||||
reason: "manual",
|
||||
inputID: previous,
|
||||
recent: "",
|
||||
})
|
||||
yield* s.llm.push(TestLLM.text("## Objective\n- New checkpoint", "new-summary"))
|
||||
const gate = yield* s.llm.gate
|
||||
const next = yield* s.session.compact({ sessionID })
|
||||
yield* gate.started
|
||||
expect((yield* s.messages).filter((message) => message.type === "compaction").toReversed()).toMatchObject([
|
||||
{ id: previous, status: "failed", error: { type: "compaction.interrupted" } },
|
||||
{ id: next.id, status: "running" },
|
||||
])
|
||||
yield* gate.release
|
||||
yield* s.session.wait(sessionID)
|
||||
})
|
||||
|
||||
scenario("durably fails local tools left running by a prior process before continuing", function* (s) {
|
||||
yield* s.admit("Recover interrupted tool")
|
||||
yield* SessionInbox.promote(s.db, s.bus, sessionID, "steer")
|
||||
|
||||
@@ -203,6 +203,8 @@ export namespace Frontend {
|
||||
"ui.focus",
|
||||
"ui.click",
|
||||
"ui.click.semantic",
|
||||
"ui.mouse",
|
||||
"ui.recording.pointer",
|
||||
"ui.resize",
|
||||
"ui.matches",
|
||||
"ui.state",
|
||||
@@ -228,12 +230,39 @@ export namespace Frontend {
|
||||
})
|
||||
export interface SemanticClickTarget extends Schema.Schema.Type<typeof SemanticClickTarget> {}
|
||||
|
||||
const MousePosition = {
|
||||
x: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
|
||||
y: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
|
||||
modifiers: Schema.optionalKey(
|
||||
Schema.Struct({
|
||||
shift: Schema.optionalKey(Schema.Boolean),
|
||||
alt: Schema.optionalKey(Schema.Boolean),
|
||||
ctrl: Schema.optionalKey(Schema.Boolean),
|
||||
}),
|
||||
),
|
||||
}
|
||||
export const MouseParams = Schema.Union([
|
||||
Schema.Struct({ ...MousePosition, action: Schema.Literal("move") }),
|
||||
Schema.Struct({
|
||||
...MousePosition,
|
||||
action: Schema.Literals(["down", "up"]),
|
||||
button: Schema.optionalKey(Schema.Literals(["left", "middle", "right"])),
|
||||
}),
|
||||
Schema.Struct({
|
||||
...MousePosition,
|
||||
action: Schema.Literal("scroll"),
|
||||
direction: Schema.Literals(["up", "down", "left", "right"]),
|
||||
}),
|
||||
])
|
||||
export type MouseParams = Schema.Schema.Type<typeof MouseParams>
|
||||
|
||||
export const Action = Schema.Union([
|
||||
Schema.Struct({ type: Schema.Literal("ui.type"), text: Schema.String }),
|
||||
Schema.Struct({ type: Schema.Literal("ui.press"), key: Schema.String, modifiers: Schema.optional(KeyModifiers) }),
|
||||
Schema.Struct({ type: Schema.Literal("ui.enter") }),
|
||||
Schema.Struct({ type: Schema.Literal("ui.arrow"), direction: Schema.Literals(["up", "down", "left", "right"]) }),
|
||||
Schema.Struct({ type: Schema.Literal("ui.focus"), target: Schema.Number }),
|
||||
Schema.Struct({ type: Schema.Literal("ui.mouse"), params: MouseParams }),
|
||||
Schema.Struct({
|
||||
type: Schema.Literal("ui.click"),
|
||||
target: Schema.Number,
|
||||
@@ -375,6 +404,7 @@ export namespace Frontend {
|
||||
Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal("ui.arrow"), params: ArrowParams }),
|
||||
Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal("ui.focus"), params: FocusParams }),
|
||||
Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal("ui.click"), params: ClickParams }),
|
||||
Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal("ui.mouse"), params: MouseParams }),
|
||||
Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal("ui.resize"), params: ResizeParams }),
|
||||
Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal("ui.matches"), params: MatchesParams }),
|
||||
Schema.Struct({
|
||||
@@ -631,6 +661,7 @@ export const UiRpcs = RpcGroup.make(
|
||||
request("ui.arrow", { payload: Frontend.ArrowParams, success: Frontend.State }),
|
||||
request("ui.focus", { payload: Frontend.FocusParams, success: Frontend.State }),
|
||||
request("ui.click", { payload: Frontend.ClickParams, success: Frontend.State }),
|
||||
request("ui.mouse", { payload: Frontend.MouseParams, success: Frontend.State }),
|
||||
request("ui.resize", { payload: Frontend.ResizeParams, success: Frontend.State }),
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { BoxRenderable, TextRenderable } from "@opentui/core"
|
||||
import { Effect } from "effect"
|
||||
import { SimulationActions } from "../src/frontend/actions"
|
||||
import { SimulationRenderer } from "../src/frontend/renderer"
|
||||
|
||||
// One warmup, seven measured batches. Real mouse dispatch and rendering included.
|
||||
await Effect.runPromise(
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const renderer = yield* SimulationRenderer.create({})
|
||||
const label = new TextRenderable(renderer, { content: "Clicks: 0" })
|
||||
let clicks = 0
|
||||
const button = new BoxRenderable(renderer, {
|
||||
width: 20,
|
||||
height: 1,
|
||||
onMouseUp: () => {
|
||||
label.content = `Clicks: ${++clicks}`
|
||||
},
|
||||
})
|
||||
button.add(label)
|
||||
renderer.root.add(button)
|
||||
const harness = SimulationActions.createHarness(renderer)
|
||||
yield* Effect.promise(() => harness.renderOnce())
|
||||
const samples: number[] = []
|
||||
for (let batch = 0; batch < 8; batch++) {
|
||||
const start = performance.now()
|
||||
for (let index = 0; index < 20; index++) {
|
||||
yield* SimulationActions.execute(harness, { type: "ui.click", target: button.num, x: 1, y: 0 })
|
||||
if (!harness.screen().includes(`Clicks: ${clicks}`)) throw new Error("click returned before painting")
|
||||
if (harness.mockMouse.getPressedButtons().length) throw new Error("click left a button held")
|
||||
}
|
||||
if (clicks !== (batch + 1) * 20) throw new Error("lost a native click")
|
||||
if (batch > 0) samples.push((performance.now() - start) / 20)
|
||||
}
|
||||
const median = samples.toSorted((a, b) => a - b)[3]
|
||||
if (median === undefined) throw new Error("missing benchmark samples")
|
||||
const mad = samples.map((value) => Math.abs(value - median)).sort((a, b) => a - b)[3]
|
||||
console.log(JSON.stringify({ metric: "simulation_click_ms", median, mad, samples, clicks }))
|
||||
console.log(`METRIC simulation_click_ms=${median.toFixed(3)}`)
|
||||
}),
|
||||
),
|
||||
)
|
||||
@@ -184,6 +184,32 @@ export const execute = Effect.fn("SimulationActions.execute")(function* (harness
|
||||
.find((item) => item.num === action.target)
|
||||
?.focus()
|
||||
break
|
||||
case "ui.mouse": {
|
||||
const params = action.params
|
||||
if (params.x >= harness.renderer.width || params.y >= harness.renderer.height)
|
||||
return yield* Effect.fail(new Error("mouse position must be within the terminal viewport"))
|
||||
const options = { modifiers: params.modifiers }
|
||||
SimulationRenderer.recordPointer(harness.renderer, params.action, params.x, params.y)
|
||||
switch (params.action) {
|
||||
case "move":
|
||||
yield* Effect.tryPromise(() => harness.mockMouse.moveTo(params.x, params.y, options))
|
||||
break
|
||||
case "down":
|
||||
yield* Effect.tryPromise(() =>
|
||||
harness.mockMouse.pressDown(params.x, params.y, mouseButton(params.button), options),
|
||||
)
|
||||
break
|
||||
case "up":
|
||||
yield* Effect.tryPromise(() =>
|
||||
harness.mockMouse.release(params.x, params.y, mouseButton(params.button), options),
|
||||
)
|
||||
break
|
||||
case "scroll":
|
||||
yield* Effect.tryPromise(() => harness.mockMouse.scroll(params.x, params.y, params.direction, options))
|
||||
break
|
||||
}
|
||||
break
|
||||
}
|
||||
case "ui.click": {
|
||||
const target = all(harness.renderer.root).find((item) => item.num === action.target)
|
||||
if (!target || !target.visible || target.isDestroyed)
|
||||
@@ -206,7 +232,11 @@ export const execute = Effect.fn("SimulationActions.execute")(function* (harness
|
||||
action.y >= target.height
|
||||
)
|
||||
return yield* Effect.fail(new Error("click position must be within the target element"))
|
||||
yield* Effect.tryPromise(() => harness.mockMouse.click(target.screenX + action.x, target.screenY + action.y))
|
||||
SimulationRenderer.recordPointer(harness.renderer, "click", target.screenX + action.x, target.screenY + action.y)
|
||||
// Opt out of test-helper pacing; retain its down/up ordering and the render below.
|
||||
yield* Effect.tryPromise(() =>
|
||||
harness.mockMouse.click(target.screenX + action.x, target.screenY + action.y, undefined, { delayMs: 0 }),
|
||||
)
|
||||
break
|
||||
}
|
||||
case "ui.resize":
|
||||
@@ -227,3 +257,7 @@ export const execute = Effect.fn("SimulationActions.execute")(function* (harness
|
||||
})
|
||||
|
||||
export * as SimulationActions from "./actions"
|
||||
|
||||
function mouseButton(button: "left" | "middle" | "right" = "left") {
|
||||
return ({ left: 0, middle: 1, right: 2 } as const)[button]
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { CliRenderer, CliRendererConfig } from "@opentui/core"
|
||||
import { createTestRenderer, type TestRendererSetup } from "@opentui/core/testing"
|
||||
import { Effect } from "effect"
|
||||
import { Timeline } from "../recording"
|
||||
import { Timeline, type Pointer } from "../recording"
|
||||
|
||||
const setups = new WeakMap<CliRenderer, TestRendererSetup>()
|
||||
const recordings = new WeakMap<CliRenderer, Timeline>()
|
||||
@@ -64,6 +64,10 @@ export function recordResize(renderer: CliRenderer, cols: number, rows: number)
|
||||
recordings.get(renderer)?.resize(cols, rows)
|
||||
}
|
||||
|
||||
export function recordPointer(renderer: CliRenderer, action: Pointer["action"], x: number, y: number) {
|
||||
recordings.get(renderer)?.pointer(action, x, y)
|
||||
}
|
||||
|
||||
export function setupFor(renderer: CliRenderer): TestRendererSetup | undefined {
|
||||
return setups.get(renderer)
|
||||
}
|
||||
|
||||
@@ -47,6 +47,8 @@ function handle(harness: Harness, request: SimulationProtocol.Frontend.Request,
|
||||
y: request.params.y,
|
||||
semantic: request.params.semantic,
|
||||
})
|
||||
case "ui.mouse":
|
||||
return SimulationActions.execute(harness, { type: "ui.mouse", params: request.params })
|
||||
case "ui.resize":
|
||||
return SimulationActions.execute(harness, {
|
||||
type: "ui.resize",
|
||||
|
||||
@@ -32,6 +32,14 @@ export interface Resize extends Schema.Schema.Type<typeof Resize> {}
|
||||
export const Event = Schema.Union([Header, Output, Resize])
|
||||
export type Event = Schema.Schema.Type<typeof Event>
|
||||
|
||||
export const Pointer = Schema.Struct({
|
||||
atMs: Schema.Number,
|
||||
action: Schema.Literals(["move", "down", "up", "click", "scroll"]),
|
||||
x: Schema.Number,
|
||||
y: Schema.Number,
|
||||
})
|
||||
export interface Pointer extends Schema.Schema.Type<typeof Pointer> {}
|
||||
|
||||
export class Timeline extends Writable {
|
||||
readonly isTTY = true
|
||||
readonly path: string
|
||||
@@ -41,6 +49,7 @@ export class Timeline extends Writable {
|
||||
private readonly started = performance.now()
|
||||
private readonly timestamps: number[] = []
|
||||
private done?: Promise<string>
|
||||
private pointers?: WriteStream
|
||||
|
||||
private constructor(path: string, cols: number, rows: number, output: WriteStream) {
|
||||
super()
|
||||
@@ -95,14 +104,27 @@ export class Timeline extends Writable {
|
||||
override _final(callback: (error?: Error | null) => void) {
|
||||
this.writeOutput(Buffer.alloc(0), this.elapsed(), (error) => {
|
||||
if (error) return callback(error)
|
||||
this.output.end(callback)
|
||||
this.output.end()
|
||||
this.pointers?.end()
|
||||
void Promise.all(this.streams().map((stream) => finished(stream, { cleanup: true }))).then(
|
||||
() => callback(),
|
||||
callback,
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
override _destroy(error: Error | null, callback: (error: Error | null) => void) {
|
||||
const streams = this.streams()
|
||||
const closed = streams.map((stream) => finished(stream, { cleanup: true }))
|
||||
streams.forEach((stream) => stream.destroy())
|
||||
// Destroy joins both children even when one failed before finish() began.
|
||||
void Promise.allSettled(closed).then(() => callback(error))
|
||||
}
|
||||
|
||||
finish() {
|
||||
if (this.done) return this.done
|
||||
this.end()
|
||||
this.done = finished(this).then(() => this.path)
|
||||
this.done = finished(this, { cleanup: true }).then(() => this.path)
|
||||
return this.done
|
||||
}
|
||||
|
||||
@@ -112,6 +134,21 @@ export class Timeline extends Writable {
|
||||
this.output.write(`${JSON.stringify(event)}\n`)
|
||||
}
|
||||
|
||||
// Input and terminal output share one monotonic clock. A sidecar leaves
|
||||
// the existing terminal timeline readable by older Drive releases.
|
||||
pointer(action: Pointer["action"], x: number, y: number) {
|
||||
if (this.writableEnded || this.destroyed) return
|
||||
if (!this.pointers) {
|
||||
this.pointers = createWriteStream(`${this.path.replace(/\.jsonl$/, "")}.pointers.jsonl`)
|
||||
this.pointers.on("error", (error) => this.destroy(error))
|
||||
}
|
||||
this.pointers.write(`${JSON.stringify({ atMs: this.elapsed(), action, x, y } satisfies Pointer)}\n`)
|
||||
}
|
||||
|
||||
private streams() {
|
||||
return this.pointers ? [this.output, this.pointers] : [this.output]
|
||||
}
|
||||
|
||||
private elapsed() {
|
||||
return Math.max(0, Math.round(performance.now() - this.started))
|
||||
}
|
||||
|
||||
@@ -103,6 +103,105 @@ test("clicks a target at relative coordinates through descendant text", async ()
|
||||
)
|
||||
})
|
||||
|
||||
test("unpaced clicks preserve native event order, button release and rendered state", async () => {
|
||||
await Effect.runPromise(
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const renderer = yield* SimulationRenderer.create({})
|
||||
const events: string[] = []
|
||||
const label = new TextRenderable(renderer, { content: "Not clicked" })
|
||||
let clicks = 0
|
||||
const button = new BoxRenderable(renderer, {
|
||||
id: "click-order",
|
||||
width: 20,
|
||||
height: 1,
|
||||
onMouseDown: () => {
|
||||
events.push("down")
|
||||
queueMicrotask(() => events.push("down microtask"))
|
||||
},
|
||||
onMouseUp: () => {
|
||||
events.push("up")
|
||||
label.content = `Clicks: ${++clicks}`
|
||||
},
|
||||
})
|
||||
button.add(label)
|
||||
renderer.root.add(button)
|
||||
const harness = createHarness(renderer)
|
||||
yield* Effect.promise(() => harness.renderOnce())
|
||||
|
||||
for (let index = 0; index < 5; index++) {
|
||||
const result = yield* execute(harness, { type: "ui.click", target: button.num, x: 1, y: 0 })
|
||||
expect(clicks).toBe(index + 1)
|
||||
expect(events.splice(0)).toEqual(["down", "down microtask", "up"])
|
||||
expect(harness.mockMouse.getPressedButtons()).toEqual([])
|
||||
expect(harness.screen()).toContain(`Clicks: ${index + 1}`)
|
||||
expect(result).toEqual(state(harness))
|
||||
}
|
||||
}),
|
||||
),
|
||||
)
|
||||
})
|
||||
|
||||
test("unpaced clicks retain native double-click text selection", async () => {
|
||||
await Effect.runPromise(
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const renderer = yield* SimulationRenderer.create({})
|
||||
const text = new TextRenderable(renderer, { content: "alpha beta", selectable: true })
|
||||
renderer.root.add(text)
|
||||
const harness = createHarness(renderer)
|
||||
yield* Effect.promise(() => harness.renderOnce())
|
||||
|
||||
yield* execute(harness, { type: "ui.click", target: text.num, x: 1, y: 0 })
|
||||
yield* execute(harness, { type: "ui.click", target: text.num, x: 1, y: 0 })
|
||||
expect(renderer.getSelection()?.getSelectedText()).toBe("alpha")
|
||||
expect(harness.mockMouse.getPressedButtons()).toEqual([])
|
||||
}),
|
||||
),
|
||||
)
|
||||
})
|
||||
|
||||
test("mouse input drives native hover, drag, buttons and scrolling at absolute coordinates", async () => {
|
||||
await Effect.runPromise(
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const renderer = yield* SimulationRenderer.create({})
|
||||
const events: Array<{ type: string; x: number; y: number; button: number }> = []
|
||||
const button = new BoxRenderable(renderer, {
|
||||
position: "absolute",
|
||||
left: 10,
|
||||
top: 5,
|
||||
width: 15,
|
||||
height: 3,
|
||||
onMouse: (event) => events.push({ type: event.type, x: event.x, y: event.y, button: event.button }),
|
||||
})
|
||||
renderer.root.add(button)
|
||||
const harness = createHarness(renderer)
|
||||
yield* Effect.promise(() => harness.renderOnce())
|
||||
yield* execute(harness, { type: "ui.mouse", params: { action: "move", x: 11, y: 6 } })
|
||||
yield* execute(harness, { type: "ui.mouse", params: { action: "move", x: 12, y: 6 } })
|
||||
expect(events.map((event) => event.type)).toContain("over")
|
||||
expect(events).toContainEqual(expect.objectContaining({ type: "move", x: 12, y: 6 }))
|
||||
yield* execute(harness, { type: "ui.mouse", params: { action: "down", x: 12, y: 6, button: "right" } })
|
||||
yield* execute(harness, { type: "ui.mouse", params: { action: "move", x: 13, y: 6 } })
|
||||
yield* execute(harness, { type: "ui.mouse", params: { action: "up", x: 13, y: 6, button: "right" } })
|
||||
expect(events).toContainEqual(expect.objectContaining({ type: "down", button: 2 }))
|
||||
expect(events).toContainEqual(expect.objectContaining({ type: "drag", x: 13, y: 6 }))
|
||||
expect(events).toContainEqual(expect.objectContaining({ type: "up", x: 13, y: 6, button: 2 }))
|
||||
expect(harness.mockMouse.getPressedButtons()).toEqual([])
|
||||
yield* execute(harness, { type: "ui.mouse", params: { action: "scroll", x: 12, y: 6, direction: "down" } })
|
||||
expect(events.map((event) => event.type)).toContain("scroll")
|
||||
yield* execute(harness, { type: "ui.mouse", params: { action: "move", x: 1, y: 1 } })
|
||||
expect(events.map((event) => event.type)).toContain("out")
|
||||
const error = yield* execute(harness, { type: "ui.mouse", params: { action: "move", x: 100, y: 40 } }).pipe(
|
||||
Effect.flip,
|
||||
)
|
||||
expect(error.message).toContain("within the terminal viewport")
|
||||
}),
|
||||
),
|
||||
)
|
||||
})
|
||||
|
||||
test("rejects a semantic click when the live identity does not match", async () => {
|
||||
await Effect.runPromise(
|
||||
Effect.scoped(
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
import { expect, test } from "bun:test"
|
||||
import { mkdtemp, rm } from "node:fs/promises"
|
||||
import { mkdir, mkdtemp, rm } from "node:fs/promises"
|
||||
import { WriteStream } from "node:fs"
|
||||
import { once } from "node:events"
|
||||
import { tmpdir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
import { TextRenderable } from "@opentui/core"
|
||||
import { createHarness, matches } from "../src/frontend/actions"
|
||||
import { SimulationRenderer } from "../src/frontend/renderer"
|
||||
import { Effect } from "effect"
|
||||
import { Timeline, type Event } from "../src/recording"
|
||||
import { Effect, Schema } from "effect"
|
||||
import { Timeline, Pointer, type Event } from "../src/recording"
|
||||
|
||||
test("streams ANSI chunks into a versioned JSONL timeline", async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "simulation-recording-"))
|
||||
@@ -37,6 +39,71 @@ test("streams ANSI chunks into a versioned JSONL timeline", async () => {
|
||||
}
|
||||
})
|
||||
|
||||
test("finishes the pointer sidecar on the output clock without changing the v1 timeline", async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "simulation-pointer-recording-"))
|
||||
try {
|
||||
const path = join(directory, "timeline.jsonl")
|
||||
const timeline = await Timeline.create(path, 80, 24)
|
||||
timeline.write("before")
|
||||
timeline.pointer("move", 12, 5)
|
||||
timeline.pointer("click", 15, 6)
|
||||
timeline.write("after")
|
||||
const first = timeline.finish()
|
||||
expect(timeline.finish()).toBe(first)
|
||||
expect(await first).toBe(path)
|
||||
timeline.pointer("move", 30, 10)
|
||||
const pointers = (await Bun.file(join(directory, "timeline.pointers.jsonl")).text())
|
||||
.trim()
|
||||
.split("\n")
|
||||
.map((line) => Schema.decodeUnknownSync(Schema.fromJsonString(Pointer))(line))
|
||||
expect(pointers.map(({ action, x, y }) => ({ action, x, y }))).toEqual([
|
||||
{ action: "move", x: 12, y: 5 },
|
||||
{ action: "click", x: 15, y: 6 },
|
||||
])
|
||||
const output = (await Bun.file(path).text())
|
||||
.trim()
|
||||
.split("\n")
|
||||
.map((line) => JSON.parse(line) as Event)
|
||||
const firstOutput = output[1]
|
||||
const lastOutput = output.at(-1)
|
||||
if (firstOutput?.type !== "output" || lastOutput?.type !== "output") throw new Error("missing output")
|
||||
expect(pointers[0]?.atMs).toBeGreaterThanOrEqual(firstOutput.at_ms)
|
||||
expect(pointers[1]?.atMs).toBeLessThanOrEqual(lastOutput.at_ms)
|
||||
expect(output.every((event) => ["header", "output", "resize"].includes(event.type))).toBe(true)
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test.each(["pointer", "output"])("joins both recording streams after an early %s failure", async (failed) => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "simulation-pointer-failure-"))
|
||||
try {
|
||||
const timeline = await Timeline.create(join(directory, "timeline.jsonl"), 80, 24)
|
||||
if (failed === "pointer") await mkdir(join(directory, "timeline.pointers.jsonl"))
|
||||
const error = new Promise<Error>((resolve) => timeline.once("error", resolve))
|
||||
timeline.pointer("move", 10, 5)
|
||||
const output: unknown = Reflect.get(timeline, "output")
|
||||
const pointers: unknown = Reflect.get(timeline, "pointers")
|
||||
if (!(output instanceof WriteStream) || !(pointers instanceof WriteStream)) throw new Error("missing owned streams")
|
||||
if (failed === "output") {
|
||||
if (pointers.pending) await once(pointers, "open")
|
||||
output.destroy(new Error("output failed"))
|
||||
}
|
||||
const failure = await error
|
||||
const finishing = timeline.finish()
|
||||
expect(timeline.finish()).toBe(finishing)
|
||||
await expect(finishing).rejects.toBe(failure)
|
||||
expect(output.closed).toBe(true)
|
||||
expect(pointers.closed).toBe(true)
|
||||
expect(Reflect.get(output, "fd")).toBeNull()
|
||||
expect(Reflect.get(pointers, "fd")).toBeNull()
|
||||
timeline.pointer("move", 99, 99)
|
||||
expect(timeline.finish()).toBe(finishing)
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("captures native renderer output and finishes on destroy", async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "simulation-renderer-recording-"))
|
||||
const path = join(directory, "timeline.jsonl")
|
||||
|
||||
@@ -4,8 +4,7 @@ import { DialogSelect } from "../ui/dialog-select"
|
||||
import { useDialog } from "../ui/dialog"
|
||||
import { DialogIntegration } from "./dialog-integration"
|
||||
import { DialogVariant } from "./dialog-variant"
|
||||
import { go } from "fuzzysort"
|
||||
import { compareModelOrder } from "@opencode-ai/util/model-order"
|
||||
import * as fuzzysort from "fuzzysort"
|
||||
import { useConnected } from "./use-connected"
|
||||
import { useData } from "../context/data"
|
||||
import { modelPreferenceKey } from "../model-preference"
|
||||
@@ -100,15 +99,11 @@ export function DialogModel(props: { providerID?: string }) {
|
||||
return false
|
||||
return true
|
||||
}),
|
||||
connected(),
|
||||
)
|
||||
|
||||
if (needle) {
|
||||
return prioritizeFavorites(
|
||||
sortModelOptions(
|
||||
go(needle, modelOptions, { keys: ["title", "category"] }).map((item) => item.obj),
|
||||
false,
|
||||
),
|
||||
fuzzysort.go(needle, modelOptions, { keys: ["title", "category"] }).map((item) => item.obj),
|
||||
favoritePriority,
|
||||
)
|
||||
}
|
||||
@@ -184,20 +179,19 @@ export function prioritizeFavorites<T extends { value: { providerID: string; mod
|
||||
}
|
||||
|
||||
export function sortModelOptions<
|
||||
T extends { providerID?: string; providerName?: string; releaseDate: number; title: string; footer?: string },
|
||||
>(options: T[], grouped = true) {
|
||||
T extends { providerID?: string; providerName?: string; releaseDate: string | number; title: string },
|
||||
>(options: T[]) {
|
||||
return options.toSorted((a, b) => {
|
||||
if (grouped) {
|
||||
const provider = Number(a.providerID !== "opencode") - Number(b.providerID !== "opencode")
|
||||
if (provider !== 0) return provider
|
||||
const provider = Number(a.providerID !== "opencode") - Number(b.providerID !== "opencode")
|
||||
if (provider !== 0) return provider
|
||||
|
||||
const name = (a.providerName ?? "").localeCompare(b.providerName ?? "")
|
||||
if (name !== 0) return name
|
||||
}
|
||||
return compareModelOrder(
|
||||
{ free: a.footer === "Free", released: a.releaseDate, name: a.title },
|
||||
{ free: b.footer === "Free", released: b.releaseDate, name: b.title },
|
||||
)
|
||||
const name = (a.providerName ?? "").localeCompare(b.providerName ?? "")
|
||||
if (name !== 0) return name
|
||||
|
||||
const release = Number(b.releaseDate) - Number(a.releaseDate)
|
||||
if (release !== 0) return release
|
||||
|
||||
return a.title.localeCompare(b.title)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
import { TextAttributes, type ScrollBoxRenderable } from "@opentui/core"
|
||||
import { useTerminalDimensions } from "@opentui/solid"
|
||||
import { isShellNotFoundError, type LocationRef, type ShellInfo } from "@opencode-ai/client"
|
||||
import { createEffect, createMemo, createSignal, onCleanup, Show, untrack } from "solid-js"
|
||||
import stripAnsi from "strip-ansi"
|
||||
import { useClient } from "../context/client"
|
||||
import { Keymap } from "../context/keymap"
|
||||
import { useTheme } from "../context/theme"
|
||||
import { useDialog } from "../ui/dialog"
|
||||
|
||||
const PAGE_BYTES = 64 * 1024
|
||||
|
||||
export function DialogShellOutput(props: { shell: ShellInfo; location: LocationRef }) {
|
||||
const client = useClient()
|
||||
const dialog = useDialog()
|
||||
const theme = useTheme("elevated")
|
||||
const dimensions = useTerminalDimensions()
|
||||
const [info, setInfo] = createSignal(props.shell)
|
||||
const [output, setOutput] = createSignal<string>()
|
||||
const [omitted, setOmitted] = createSignal(false)
|
||||
const [error, setError] = createSignal("")
|
||||
const text = createMemo(() => stripAnsi(output() ?? "").replace(/\r\n?/g, "\n"))
|
||||
const height = () => Math.max(3, Math.floor(dimensions().height * 0.6) - 6)
|
||||
let scroll: ScrollBoxRenderable | undefined
|
||||
|
||||
dialog.setSize("xlarge")
|
||||
dialog.setCentered(true)
|
||||
|
||||
createEffect(() => {
|
||||
// The running-shell inventory drops exited commands. Keep this view tied to
|
||||
// the opened ID and its original Location, not the list's current selection.
|
||||
const id = props.shell.id
|
||||
const location = { directory: props.location.directory, workspace: props.location.workspaceID }
|
||||
let cursor: number | undefined
|
||||
let disposed = false
|
||||
let missing = false
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
const load = async () => {
|
||||
if (untrack(info).status === "running") {
|
||||
const current = await client.api.shell.get({ id, location })
|
||||
if (disposed) return false
|
||||
setInfo(current.data)
|
||||
}
|
||||
if (cursor === undefined) {
|
||||
const head = await client.api.shell.output({ id, location, cursor: Number.MAX_SAFE_INTEGER })
|
||||
if (disposed) return false
|
||||
cursor = Math.max(0, head.data.size - PAGE_BYTES)
|
||||
setOmitted(cursor > 0)
|
||||
}
|
||||
const page = await client.api.shell.output({ id, location, cursor, limit: PAGE_BYTES })
|
||||
if (disposed) return false
|
||||
cursor = page.data.cursor
|
||||
setOutput((previous) => {
|
||||
const next = (previous ?? "") + page.data.output
|
||||
if (next.length > PAGE_BYTES) setOmitted(true)
|
||||
return next.slice(-PAGE_BYTES)
|
||||
})
|
||||
setError("")
|
||||
return cursor < page.data.size
|
||||
}
|
||||
|
||||
const poll = () => {
|
||||
void load()
|
||||
.catch((cause: unknown) => {
|
||||
if (disposed) return
|
||||
missing = isShellNotFoundError(cause)
|
||||
setError(missing ? "Shell output is no longer available." : "Unable to read shell output. Retrying…")
|
||||
})
|
||||
.then((more) => {
|
||||
// Poll only while the viewer is open, including after exit so the final
|
||||
// file flush is observed. Never overlap reads or reload earlier pages.
|
||||
if (!disposed && !missing) timer = setTimeout(poll, more ? 0 : 1_000)
|
||||
})
|
||||
}
|
||||
poll()
|
||||
onCleanup(() => {
|
||||
disposed = true
|
||||
clearTimeout(timer)
|
||||
})
|
||||
})
|
||||
|
||||
const status = () => {
|
||||
if (info().status === "running") return "Running"
|
||||
if (info().status === "timeout") return "Timed out"
|
||||
if (info().status === "killed") return "Killed"
|
||||
return info().exit === undefined ? "Exited" : `Exited · code ${info().exit}`
|
||||
}
|
||||
|
||||
Keymap.createLayer(() => ({
|
||||
mode: "modal",
|
||||
commands: [
|
||||
{ bind: "up", title: "Scroll output up", group: "Shell", run: () => scroll?.scrollBy(-1) },
|
||||
{ bind: "down", title: "Scroll output down", group: "Shell", run: () => scroll?.scrollBy(1) },
|
||||
{ bind: "pageup", title: "Previous output page", group: "Shell", run: () => scroll?.scrollBy(-height()) },
|
||||
{ bind: "pagedown", title: "Next output page", group: "Shell", run: () => scroll?.scrollBy(height()) },
|
||||
{ bind: "home", title: "First loaded output", group: "Shell", run: () => scroll?.scrollTo(0) },
|
||||
{ bind: "end", title: "Follow shell output", group: "Shell", run: () => scroll?.scrollTo(Infinity) },
|
||||
],
|
||||
}))
|
||||
|
||||
return (
|
||||
<box paddingLeft={2} paddingRight={2} paddingBottom={1} gap={1}>
|
||||
<box flexDirection="row" gap={2}>
|
||||
<text fg={theme.text.default} attributes={TextAttributes.BOLD} flexGrow={1}>
|
||||
Shell output
|
||||
</text>
|
||||
<text fg={theme.text.subdued}>{status()}</text>
|
||||
<text fg={theme.text.subdued} onMouseUp={() => dialog.clear()}>
|
||||
esc
|
||||
</text>
|
||||
</box>
|
||||
<text fg={theme.text.subdued} maxHeight={3} wrapMode="word">
|
||||
{props.shell.command}
|
||||
</text>
|
||||
<Show when={omitted()}>
|
||||
<text fg={theme.text.subdued}>Earlier output omitted · showing recent output</text>
|
||||
</Show>
|
||||
<scrollbox
|
||||
id="shell-output-scroll"
|
||||
ref={(value: ScrollBoxRenderable) => (scroll = value)}
|
||||
height={height()}
|
||||
stickyScroll
|
||||
stickyStart="bottom"
|
||||
scrollbarOptions={{ visible: false }}
|
||||
>
|
||||
<text fg={theme.text.default} wrapMode="word">
|
||||
{text() ||
|
||||
(output() === undefined
|
||||
? "Loading output…"
|
||||
: "No captured output. Output redirected to files is not shown here.")}
|
||||
</text>
|
||||
</scrollbox>
|
||||
<Show when={error()}>
|
||||
<text fg={theme.text.feedback.error.default}>{error()}</text>
|
||||
</Show>
|
||||
<box flexDirection="row" gap={2} flexWrap="wrap">
|
||||
<text fg={theme.text.subdued}>↑/↓ scroll</text>
|
||||
<text fg={theme.text.subdued}>end follow</text>
|
||||
<text fg={theme.text.subdued}>esc back</text>
|
||||
</box>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
@@ -87,7 +87,6 @@ export function Autocomplete(props: {
|
||||
index: 0,
|
||||
selected: 0,
|
||||
visible: false as AutocompleteRef["visible"],
|
||||
input: "keyboard" as "keyboard" | "mouse",
|
||||
})
|
||||
|
||||
const [positionTick, setPositionTick] = createSignal(0)
|
||||
@@ -151,14 +150,6 @@ export function Autocomplete(props: {
|
||||
setSearch(next ? next : "")
|
||||
})
|
||||
|
||||
// When the filter changes due to how TUI works, the mousemove might still be triggered
|
||||
// via a synthetic event as the layout moves underneath the cursor. This is a workaround to make sure the input mode remains keyboard so
|
||||
// that the mouseover event doesn't trigger when filtering.
|
||||
createEffect(() => {
|
||||
filter()
|
||||
setStore("input", "keyboard")
|
||||
})
|
||||
|
||||
function insertPart(
|
||||
text: string,
|
||||
part:
|
||||
@@ -724,7 +715,6 @@ export function Autocomplete(props: {
|
||||
title: "Previous autocomplete item",
|
||||
group: "Autocomplete",
|
||||
run() {
|
||||
setStore("input", "keyboard")
|
||||
move(-1)
|
||||
},
|
||||
},
|
||||
@@ -733,7 +723,6 @@ export function Autocomplete(props: {
|
||||
title: "Next autocomplete item",
|
||||
group: "Autocomplete",
|
||||
run() {
|
||||
setStore("input", "keyboard")
|
||||
move(1)
|
||||
},
|
||||
},
|
||||
@@ -942,17 +931,8 @@ export function Autocomplete(props: {
|
||||
: undefined
|
||||
}
|
||||
flexDirection="row"
|
||||
onMouseMove={() => {
|
||||
setStore("input", "mouse")
|
||||
}}
|
||||
onMouseOver={() => {
|
||||
if (store.input !== "mouse") return
|
||||
moveTo(index)
|
||||
}}
|
||||
onMouseDown={() => {
|
||||
setStore("input", "mouse")
|
||||
moveTo(index)
|
||||
}}
|
||||
onMouseMove={() => moveTo(index)}
|
||||
onMouseDown={() => moveTo(index)}
|
||||
onMouseUp={() => select()}
|
||||
>
|
||||
<text
|
||||
|
||||
@@ -244,6 +244,7 @@ export const Definitions = {
|
||||
"composer.subagent.interrupt": keybind("ctrl+d", "Interrupt subagent"),
|
||||
"composer.shell.up": keybind("up", "Previous shell"),
|
||||
"composer.shell.down": keybind("down", "Next shell"),
|
||||
"composer.shell.select": keybind("return", "View shell output"),
|
||||
"composer.shell.kill": keybind("ctrl+d", "Kill shell command"),
|
||||
"composer.terminal.up": keybind("up,k", "Previous terminal"),
|
||||
"composer.terminal.down": keybind("down,j", "Next terminal"),
|
||||
|
||||
@@ -75,7 +75,6 @@ export function runProviders(providers: CurrentProvider[], models: CurrentModel[
|
||||
const cost = defaultCost(model)
|
||||
provider.models[model.id] = {
|
||||
name: model.name,
|
||||
time: { released: model.time.released },
|
||||
cost: cost === undefined ? undefined : { input: cost },
|
||||
limit: { context: model.limit.context },
|
||||
status: model.status,
|
||||
|
||||
@@ -3,7 +3,6 @@ import { TextAttributes, type InputRenderable, type KeyEvent } from "@opentui/co
|
||||
import { useKeyboard, useRenderer, useTerminalDimensions, type JSX } from "@opentui/solid"
|
||||
import fuzzysort from "fuzzysort"
|
||||
import { createEffect, createMemo, createSignal, type Accessor } from "solid-js"
|
||||
import { compareModelOrder } from "@opencode-ai/util/model-order"
|
||||
import { Keymap } from "../context/keymap"
|
||||
import { Config } from "../config"
|
||||
import { OneCellSpinner } from "../component/one-cell-spinner"
|
||||
@@ -52,8 +51,6 @@ type ModelEntry = PanelEntry & {
|
||||
providerID: string
|
||||
modelID: string
|
||||
providerName: string
|
||||
free: boolean
|
||||
released: number
|
||||
current: boolean
|
||||
}
|
||||
|
||||
@@ -152,7 +149,6 @@ function createSearchablePanelController<T extends PanelEntry>(input: {
|
||||
onClose: () => void
|
||||
onSelect: (item: T) => void
|
||||
isCurrent?: (item: T) => boolean
|
||||
compare?: (a: T, b: T, query: string) => number
|
||||
closeOnFirstUp?: boolean
|
||||
onKey?: (event: KeyEvent, item: T | undefined) => boolean
|
||||
onRows?: (rows: number) => void
|
||||
@@ -166,12 +162,7 @@ function createSearchablePanelController<T extends PanelEntry>(input: {
|
||||
})
|
||||
let field: InputRenderable | undefined
|
||||
const [query, setQuery] = createSignal("")
|
||||
const items = createMemo<T[]>(() => {
|
||||
const text = query().trim()
|
||||
const matched = match(text, input.entries())
|
||||
const compare = input.compare
|
||||
return compare ? matched.toSorted((a, b) => compare(a, b, text)) : matched
|
||||
})
|
||||
const items = createMemo<T[]>(() => match(query(), input.entries()))
|
||||
const menu = createFooterMenuState({ count: () => items().length, limit: () => layout().limit })
|
||||
const selected = () => items()[menu.selected()]
|
||||
|
||||
@@ -1163,29 +1154,46 @@ export function RunModelSelectBody(props: {
|
||||
mono?: boolean
|
||||
}) {
|
||||
const entries = createMemo<ModelEntry[]>(() =>
|
||||
(props.providers() ?? []).flatMap((provider) =>
|
||||
Object.entries(provider.models)
|
||||
.filter(([, model]) => model.status !== "deprecated")
|
||||
.map(([modelID, model]) => {
|
||||
const title = model.name ?? modelID
|
||||
const current = props.current()?.providerID === provider.id && props.current()?.modelID === modelID
|
||||
const free = model.cost?.input === 0 && provider.id === "opencode"
|
||||
const footer = current ? "current" : free ? "Free" : title !== modelID ? modelID : undefined
|
||||
return {
|
||||
providerID: provider.id,
|
||||
modelID,
|
||||
providerName: provider.name,
|
||||
free,
|
||||
released: model.time?.released ?? 0,
|
||||
category: provider.name,
|
||||
display: title,
|
||||
footer,
|
||||
footerTone: current ? ("selection" as const) : undefined,
|
||||
keywords: `${provider.id} ${provider.name} ${modelID} ${title} ${footer ?? ""}`,
|
||||
current,
|
||||
}
|
||||
}),
|
||||
),
|
||||
(props.providers() ?? [])
|
||||
.flatMap((provider) =>
|
||||
Object.entries(provider.models)
|
||||
.filter(([, model]) => model.status !== "deprecated")
|
||||
.map(([modelID, model]) => {
|
||||
const title = model.name ?? modelID
|
||||
const current = props.current()?.providerID === provider.id && props.current()?.modelID === modelID
|
||||
const footer = current
|
||||
? "current"
|
||||
: model.cost?.input === 0 && provider.id === "opencode"
|
||||
? "Free"
|
||||
: title !== modelID
|
||||
? modelID
|
||||
: undefined
|
||||
return {
|
||||
providerID: provider.id,
|
||||
modelID,
|
||||
providerName: provider.name,
|
||||
category: provider.name,
|
||||
display: title,
|
||||
footer,
|
||||
footerTone: current ? ("selection" as const) : undefined,
|
||||
keywords: `${provider.id} ${provider.name} ${modelID} ${title} ${footer ?? ""}`,
|
||||
current,
|
||||
}
|
||||
}),
|
||||
)
|
||||
.sort((a, b) => {
|
||||
const provider = Number(a.providerID !== "opencode") - Number(b.providerID !== "opencode")
|
||||
if (provider !== 0) {
|
||||
return provider
|
||||
}
|
||||
|
||||
const name = a.providerName.localeCompare(b.providerName)
|
||||
if (name !== 0) {
|
||||
return name
|
||||
}
|
||||
|
||||
return a.display.localeCompare(b.display)
|
||||
}),
|
||||
)
|
||||
const controller = createSearchablePanelController({
|
||||
entries,
|
||||
@@ -1193,20 +1201,6 @@ export function RunModelSelectBody(props: {
|
||||
onClose: props.onClose,
|
||||
onSelect: (item) => props.onSelect({ providerID: item.providerID, modelID: item.modelID }),
|
||||
isCurrent: (item) => item.current,
|
||||
compare: (a, b, query) => {
|
||||
if (!query) {
|
||||
const provider = Number(a.providerID !== "opencode") - Number(b.providerID !== "opencode")
|
||||
if (provider !== 0) return provider
|
||||
|
||||
const name = a.providerName.localeCompare(b.providerName)
|
||||
if (name !== 0) return name
|
||||
}
|
||||
|
||||
return compareModelOrder(
|
||||
{ free: a.free, released: a.released, name: a.display },
|
||||
{ free: b.free, released: b.released, name: b.display },
|
||||
)
|
||||
},
|
||||
})
|
||||
|
||||
return (
|
||||
|
||||
@@ -438,7 +438,7 @@ export function RunFormBody(props: {
|
||||
flexDirection="row"
|
||||
gap={1}
|
||||
alignItems="flex-start"
|
||||
onMouseOver={() => setState((previous) => formSetSelected(previous, index()))}
|
||||
onMouseMove={() => setState((previous) => formSetSelected(previous, index()))}
|
||||
backgroundColor={active() ? props.theme.formfieldFocusedBg : "transparent"}
|
||||
onMouseUp={() => choose(index())}
|
||||
>
|
||||
|
||||
@@ -54,7 +54,7 @@ function buttons(
|
||||
paddingLeft={1}
|
||||
paddingRight={1}
|
||||
backgroundColor={option === selected ? theme.actionFocusedBg : transparent}
|
||||
onMouseOver={() => {
|
||||
onMouseMove={() => {
|
||||
if (!disabled) onHover(option)
|
||||
}}
|
||||
onMouseUp={() => {
|
||||
|
||||
@@ -58,9 +58,6 @@ export type RunCommand = {
|
||||
|
||||
type RunProviderModel = {
|
||||
name?: string
|
||||
time?: {
|
||||
released: number
|
||||
}
|
||||
cost?: {
|
||||
input: number
|
||||
}
|
||||
|
||||
@@ -6,6 +6,8 @@ import { useClient } from "../../../context/client"
|
||||
import { useTheme } from "../../../context/theme"
|
||||
import { Keymap } from "../../../context/keymap"
|
||||
import { useComposerTab } from "./index"
|
||||
import { useDialog } from "../../../ui/dialog"
|
||||
import { DialogShellOutput } from "../../../component/dialog-shell-output"
|
||||
|
||||
export function ShellTab(props: { sessionID: string }) {
|
||||
const data = useData()
|
||||
@@ -13,6 +15,7 @@ export function ShellTab(props: { sessionID: string }) {
|
||||
const theme = useTheme()
|
||||
const composer = useComposerTab()
|
||||
const shortcuts = Keymap.useShortcuts()
|
||||
const dialog = useDialog()
|
||||
|
||||
const entries = createMemo(() =>
|
||||
data.shell.listBySession(props.sessionID).filter((shell) => shell.status === "running"),
|
||||
@@ -23,6 +26,11 @@ export function ShellTab(props: { sessionID: string }) {
|
||||
|
||||
const selectedEntry = createMemo(() => entries()[store.selected])
|
||||
|
||||
const open = () => {
|
||||
const entry = selectedEntry()
|
||||
if (entry) dialog.replace(() => <DialogShellOutput shell={entry} location={entry.location} />)
|
||||
}
|
||||
|
||||
createEffect(() => {
|
||||
if (store.selected >= entries().length) setStore("selected", Math.max(0, entries().length - 1))
|
||||
})
|
||||
@@ -42,7 +50,13 @@ export function ShellTab(props: { sessionID: string }) {
|
||||
const cleanup = composer.register({
|
||||
id: "shell",
|
||||
label: "Shell",
|
||||
hints: () => (selectedEntry() ? [{ label: "kill", shortcut: shortcuts.get("composer.shell.kill") ?? "" }] : []),
|
||||
hints: () =>
|
||||
selectedEntry()
|
||||
? [
|
||||
{ label: "output", shortcut: shortcuts.get("composer.shell.select") ?? "" },
|
||||
{ label: "kill", shortcut: shortcuts.get("composer.shell.kill") ?? "" },
|
||||
]
|
||||
: [],
|
||||
})
|
||||
onCleanup(cleanup)
|
||||
})
|
||||
@@ -74,6 +88,12 @@ export function ShellTab(props: { sessionID: string }) {
|
||||
setStore("selected", (prev) => (prev + 1) % list.length)
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "composer.shell.select",
|
||||
title: "View shell output",
|
||||
group: "Composer",
|
||||
run: open,
|
||||
},
|
||||
{
|
||||
id: "composer.shell.kill",
|
||||
title: "Kill shell command",
|
||||
@@ -105,7 +125,11 @@ export function ShellTab(props: { sessionID: string }) {
|
||||
backgroundColor={
|
||||
active() ? theme.background.action.primary.focused : theme.background.action.primary.default
|
||||
}
|
||||
onMouseOver={() => setStore("selected", index())}
|
||||
onMouseMove={() => setStore("selected", index())}
|
||||
onMouseUp={() => {
|
||||
setStore("selected", index())
|
||||
open()
|
||||
}}
|
||||
>
|
||||
<text
|
||||
fg={active() ? theme.text.action.primary.focused : theme.text.action.primary.default}
|
||||
|
||||
@@ -215,7 +215,7 @@ export function SubagentsTab(props: { sessionID: string }) {
|
||||
? theme.background.action.primary.selected
|
||||
: theme.background.action.primary.default
|
||||
}
|
||||
onMouseOver={() => setStore("selected", index())}
|
||||
onMouseMove={() => setStore("selected", index())}
|
||||
onMouseUp={() => {
|
||||
setStore("selected", index())
|
||||
navigate({ type: "session", sessionID: entry.sessionID })
|
||||
|
||||
@@ -84,7 +84,7 @@ export function TerminalsTab(props: { sessionID: string; visibleTerminalID?: str
|
||||
? theme.background.action.primary.selected
|
||||
: theme.background.action.primary.default
|
||||
}
|
||||
onMouseOver={() => setSelected(index())}
|
||||
onMouseMove={() => setSelected(index())}
|
||||
onMouseUp={() => {
|
||||
setSelected(index())
|
||||
select()
|
||||
|
||||
@@ -907,7 +907,7 @@ export function FormPrompt(props: { form: FormWithLocation }) {
|
||||
}
|
||||
return (
|
||||
<box
|
||||
onMouseOver={() => setStore("selected", i())}
|
||||
onMouseMove={() => setStore("selected", i())}
|
||||
onMouseDown={() => setStore("selected", i())}
|
||||
onMouseUp={() => {
|
||||
if (renderer.getSelection()?.getSelectedText()) return
|
||||
@@ -961,7 +961,7 @@ export function FormPrompt(props: { form: FormWithLocation }) {
|
||||
</For>
|
||||
<Show when={custom()}>
|
||||
<box
|
||||
onMouseOver={() => setStore("selected", rows().length)}
|
||||
onMouseMove={() => setStore("selected", rows().length)}
|
||||
onMouseDown={() => setStore("selected", rows().length)}
|
||||
onMouseUp={() => {
|
||||
if (renderer.getSelection()?.getSelectedText()) return
|
||||
|
||||
@@ -591,7 +591,7 @@ export function SessionQuestion<const T extends Record<string, string>>(props: {
|
||||
? theme.background.action.primary.focused
|
||||
: theme.background.action.primary.default
|
||||
}
|
||||
onMouseOver={() => setStore("selected", option)}
|
||||
onMouseMove={() => setStore("selected", option)}
|
||||
onMouseUp={() => {
|
||||
setStore("selected", option)
|
||||
props.onSelect(option)
|
||||
|
||||
@@ -112,7 +112,6 @@ export function DialogSelect<T>(props: DialogSelectProps<T>) {
|
||||
const [store, setStore] = createStore({
|
||||
selected: 0,
|
||||
filter: "",
|
||||
input: "keyboard" as "keyboard" | "mouse",
|
||||
})
|
||||
const [focusedAction, setFocusedAction] = createSignal<number>()
|
||||
const actionFocused = createMemo(() => focusedAction() !== undefined)
|
||||
@@ -201,12 +200,8 @@ export function DialogSelect<T>(props: DialogSelectProps<T>) {
|
||||
return result
|
||||
})
|
||||
|
||||
// When the filter changes due to how TUI works, the mousemove might still be triggered
|
||||
// via a synthetic event as the layout moves underneath the cursor. This is a workaround to make sure the input mode remains keyboard
|
||||
// that the mouseover event doesn't trigger when filtering.
|
||||
createEffect(() => {
|
||||
filtered()
|
||||
setStore("input", "keyboard")
|
||||
setFocusedAction(undefined)
|
||||
})
|
||||
|
||||
@@ -384,7 +379,6 @@ export function DialogSelect<T>(props: DialogSelectProps<T>) {
|
||||
|
||||
function submit() {
|
||||
if (props.locked) return
|
||||
setStore("input", "keyboard")
|
||||
const index = focusedAction()
|
||||
if (index !== undefined) {
|
||||
trigger(actionItems()[index])
|
||||
@@ -418,7 +412,6 @@ export function DialogSelect<T>(props: DialogSelectProps<T>) {
|
||||
title: "Previous item",
|
||||
group: "Dialog",
|
||||
run() {
|
||||
setStore("input", "keyboard")
|
||||
move(-1)
|
||||
},
|
||||
},
|
||||
@@ -427,7 +420,6 @@ export function DialogSelect<T>(props: DialogSelectProps<T>) {
|
||||
title: "Next item",
|
||||
group: "Dialog",
|
||||
run() {
|
||||
setStore("input", "keyboard")
|
||||
move(1)
|
||||
},
|
||||
},
|
||||
@@ -436,7 +428,6 @@ export function DialogSelect<T>(props: DialogSelectProps<T>) {
|
||||
title: "Page up",
|
||||
group: "Dialog",
|
||||
run() {
|
||||
setStore("input", "keyboard")
|
||||
move(-10)
|
||||
},
|
||||
},
|
||||
@@ -445,7 +436,6 @@ export function DialogSelect<T>(props: DialogSelectProps<T>) {
|
||||
title: "Page down",
|
||||
group: "Dialog",
|
||||
run() {
|
||||
setStore("input", "keyboard")
|
||||
move(10)
|
||||
},
|
||||
},
|
||||
@@ -455,7 +445,6 @@ export function DialogSelect<T>(props: DialogSelectProps<T>) {
|
||||
group: "Dialog",
|
||||
run() {
|
||||
if (props.locked) return
|
||||
setStore("input", "keyboard")
|
||||
moveTo(0)
|
||||
},
|
||||
},
|
||||
@@ -465,7 +454,6 @@ export function DialogSelect<T>(props: DialogSelectProps<T>) {
|
||||
group: "Dialog",
|
||||
run() {
|
||||
if (props.locked) return
|
||||
setStore("input", "keyboard")
|
||||
moveTo(flat().length - 1)
|
||||
},
|
||||
},
|
||||
@@ -538,7 +526,6 @@ export function DialogSelect<T>(props: DialogSelectProps<T>) {
|
||||
|
||||
function trigger(item: Action | undefined) {
|
||||
if (props.locked || !item || isActionDisabled(item)) return
|
||||
setStore("input", "keyboard")
|
||||
if (item.selection === "none") {
|
||||
item.onTrigger()
|
||||
return
|
||||
@@ -709,21 +696,16 @@ export function DialogSelect<T>(props: DialogSelectProps<T>) {
|
||||
position="relative"
|
||||
onMouseMove={() => {
|
||||
if (props.locked) return
|
||||
setStore("input", "mouse")
|
||||
setFocusedAction(undefined)
|
||||
const index = flat().findIndex((x) => isDeepEqual(x.value, option.value))
|
||||
if (index === -1 || index === store.selected) return
|
||||
moveTo(index)
|
||||
}}
|
||||
onMouseUp={() => {
|
||||
if (props.locked) return
|
||||
option.onSelect?.(dialog)
|
||||
props.onSelect?.(option)
|
||||
}}
|
||||
onMouseOver={() => {
|
||||
if (props.locked) return
|
||||
if (store.input !== "mouse") return
|
||||
const index = flat().findIndex((x) => isDeepEqual(x.value, option.value))
|
||||
if (index === -1) return
|
||||
moveTo(index)
|
||||
}}
|
||||
onMouseDown={() => {
|
||||
if (props.locked) return
|
||||
const index = flat().findIndex((x) => isDeepEqual(x.value, option.value))
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { prioritizeFavorites, sortModelOptions } from "../../../../src/component/dialog-model"
|
||||
import { go } from "fuzzysort"
|
||||
|
||||
describe("prioritizeFavorites", () => {
|
||||
test("uses the favorite order captured when the dialog opened", () => {
|
||||
@@ -24,32 +23,6 @@ describe("prioritizeFavorites", () => {
|
||||
})
|
||||
|
||||
describe("sortModelOptions", () => {
|
||||
test.each(["", "haik"])("orders matches free-first then newest for query %j", (query) => {
|
||||
const options = [
|
||||
{ providerID: "demo", title: "Claude Haiku 3", releaseDate: 1 },
|
||||
{ providerID: "demo", title: "Claude Haiku 4.5", releaseDate: 2 },
|
||||
{ providerID: "demo", title: "Claude Haiku Free", releaseDate: 0, footer: "Free" },
|
||||
]
|
||||
const matches = query ? go(query, options, { key: "title" }).map((item) => item.obj) : options
|
||||
expect(sortModelOptions(matches, !query).map((item) => item.title)).toEqual([
|
||||
"Claude Haiku Free",
|
||||
"Claude Haiku 4.5",
|
||||
"Claude Haiku 3",
|
||||
])
|
||||
})
|
||||
|
||||
test("flat search sorts across providers rather than by provider priority", () => {
|
||||
expect(
|
||||
sortModelOptions(
|
||||
[
|
||||
{ providerID: "opencode", providerName: "OpenCode", title: "Claude Haiku 3", releaseDate: 1 },
|
||||
{ providerID: "anthropic", providerName: "Anthropic", title: "Claude Haiku 4.5", releaseDate: 2 },
|
||||
],
|
||||
false,
|
||||
).map((item) => item.title),
|
||||
).toEqual(["Claude Haiku 4.5", "Claude Haiku 3"])
|
||||
})
|
||||
|
||||
test("orders opencode models before other providers", () => {
|
||||
const sorted = sortModelOptions([
|
||||
{ providerID: "openai", providerName: "OpenAI", releaseDate: 3, title: "GPT 5" },
|
||||
|
||||
@@ -11,6 +11,8 @@ import { LocationProvider } from "../../../src/context/location"
|
||||
import { RouteProvider, useRoute } from "../../../src/context/route"
|
||||
import { ThemeProvider } from "../../../src/context/theme"
|
||||
import { Composer } from "../../../src/routes/session/composer"
|
||||
import { DialogProvider } from "../../../src/ui/dialog"
|
||||
import { ToastProvider } from "../../../src/ui/toast"
|
||||
import { createApi, createEventStream, createFetch, directory, json } from "../../fixture/tui-client"
|
||||
import { TestTuiContexts } from "../../fixture/tui-environment"
|
||||
import { createTuiResolvedConfig } from "../../fixture/tui-runtime"
|
||||
@@ -31,6 +33,7 @@ async function renderComposer(
|
||||
const events = createEventStream()
|
||||
const interrupted: string[] = []
|
||||
const removed: string[] = []
|
||||
const viewed: string[] = []
|
||||
const ready = Promise.withResolvers<void>()
|
||||
let closed = 0
|
||||
let dispatch!: ReturnType<typeof Keymap.use>["dispatch"]
|
||||
@@ -53,6 +56,13 @@ async function renderComposer(
|
||||
})
|
||||
}
|
||||
const shellID = url.pathname.match(/^\/api\/shell\/([^/]+)$/)?.[1]
|
||||
if (shellID && request.method === "GET") {
|
||||
viewed.push(shellID)
|
||||
return json({ location: { directory }, data: shells.find((shell) => shell.id === shellID) })
|
||||
}
|
||||
if (url.pathname.endsWith("/output")) {
|
||||
return json({ location: { directory }, data: { output: "", cursor: 0, size: 0, truncated: false } })
|
||||
}
|
||||
if (shellID && request.method === "DELETE") {
|
||||
removed.push(shellID)
|
||||
return new Response(null, { status: 204 })
|
||||
@@ -100,7 +110,11 @@ async function renderComposer(
|
||||
<LocationProvider>
|
||||
<RouteProvider initialRoute={{ type: "session", sessionID: "parent" }}>
|
||||
<ThemeProvider mode="dark" source={{ discover: async () => ({}) }}>
|
||||
<Content />
|
||||
<ToastProvider>
|
||||
<DialogProvider>
|
||||
<Content />
|
||||
</DialogProvider>
|
||||
</ToastProvider>
|
||||
</ThemeProvider>
|
||||
</RouteProvider>
|
||||
</LocationProvider>
|
||||
@@ -119,6 +133,7 @@ async function renderComposer(
|
||||
app,
|
||||
interrupted,
|
||||
removed,
|
||||
viewed,
|
||||
route: () => route.data,
|
||||
dispatch: (command: string) => dispatch(command),
|
||||
closed: () => closed,
|
||||
@@ -154,15 +169,18 @@ test("disabled shell bindings have no component fallbacks", async () => {
|
||||
const composer = await renderComposer("shell", {
|
||||
"composer.shell.up": "none",
|
||||
"composer.shell.down": "none",
|
||||
"composer.shell.select": "none",
|
||||
"composer.shell.kill": "none",
|
||||
})
|
||||
try {
|
||||
expect(composer.app.captureCharFrame()).toContain("bun test")
|
||||
composer.app.mockInput.pressArrow("up")
|
||||
composer.app.mockInput.pressEnter()
|
||||
composer.app.mockInput.pressKey("d", { ctrl: true })
|
||||
await composer.app.renderOnce()
|
||||
expect(composer.closed()).toBe(0)
|
||||
expect(composer.removed).toEqual([])
|
||||
expect(composer.viewed).toEqual([])
|
||||
|
||||
composer.app.mockInput.pressArrow("down")
|
||||
composer.dispatch("composer.shell.kill")
|
||||
@@ -198,6 +216,22 @@ test("ctrl+c closes the active composer", async () => {
|
||||
}
|
||||
})
|
||||
|
||||
test("shell output respects a configured binding with a focused textarea", async () => {
|
||||
const composer = await renderComposer("shell", { "composer.shell.select": "ctrl+o" }, true)
|
||||
try {
|
||||
composer.app.mockInput.pressEnter()
|
||||
await composer.app.renderOnce()
|
||||
expect(composer.viewed).toEqual([])
|
||||
composer.app.mockInput.pressKey("o", { ctrl: true })
|
||||
await wait(() => composer.viewed.length > 0)
|
||||
await composer.app.renderOnce()
|
||||
expect(composer.app.captureCharFrame()).toContain("Shell output")
|
||||
expect(composer.viewed).toEqual(["sh-a"])
|
||||
} finally {
|
||||
composer.app.renderer.destroy()
|
||||
}
|
||||
})
|
||||
|
||||
function session(id: string, title: string, parentID?: string) {
|
||||
return {
|
||||
id,
|
||||
|
||||
@@ -15,6 +15,8 @@ import { LocationProvider, useLocation } from "../../../src/context/location"
|
||||
import { RouteProvider } from "../../../src/context/route"
|
||||
import { ThemeProvider } from "../../../src/context/theme"
|
||||
import { Composer } from "../../../src/routes/session/composer"
|
||||
import { DialogProvider } from "../../../src/ui/dialog"
|
||||
import { ToastProvider } from "../../../src/ui/toast"
|
||||
import { createSessionRows, type SessionRow } from "../../../src/routes/session/rows"
|
||||
import { createApi, createEventStream, createFetch, directory, json, worktree } from "../../fixture/tui-client"
|
||||
import { emptyThemeSource } from "../../fixture/fixture"
|
||||
@@ -2020,7 +2022,11 @@ test("keeps shell state scoped to location", async () => {
|
||||
<RouteProvider initialRoute={{ type: "session", sessionID: "ses_shared" }}>
|
||||
<Keymap.Provider>
|
||||
<ThemeProvider mode="dark" source={emptyThemeSource}>
|
||||
<Composer sessionID="ses_shared" open={true} defaultTab="shell" />
|
||||
<ToastProvider>
|
||||
<DialogProvider>
|
||||
<Composer sessionID="ses_shared" open={true} defaultTab="shell" />
|
||||
</DialogProvider>
|
||||
</ToastProvider>
|
||||
</ThemeProvider>
|
||||
</Keymap.Provider>
|
||||
</RouteProvider>
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
/** @jsxImportSource @opentui/solid */
|
||||
import { ScrollBoxRenderable } from "@opentui/core"
|
||||
import { testRender } from "@opentui/solid"
|
||||
import type { ShellInfo } from "@opencode-ai/client"
|
||||
import { expect, test } from "bun:test"
|
||||
import { createSignal, onMount } from "solid-js"
|
||||
import { ConfigProvider } from "../../src/config"
|
||||
import { ClientProvider } from "../../src/context/client"
|
||||
import { DataProvider, useData } from "../../src/context/data"
|
||||
import { Keymap } from "../../src/context/keymap"
|
||||
import { RouteProvider } from "../../src/context/route"
|
||||
import { ThemeProvider } from "../../src/context/theme"
|
||||
import { Composer } from "../../src/routes/session/composer"
|
||||
import { DialogProvider } from "../../src/ui/dialog"
|
||||
import { ToastProvider } from "../../src/ui/toast"
|
||||
import { emptyThemeSource, tmpdir } from "../fixture/fixture"
|
||||
import { createApi, createEventStream, createFetch, json } from "../fixture/tui-client"
|
||||
import { TestTuiContexts } from "../fixture/tui-environment"
|
||||
import { createTuiResolvedConfig } from "../fixture/tui-runtime"
|
||||
|
||||
async function setup(width: number, output = "") {
|
||||
const temporary = await tmpdir()
|
||||
const location = { directory: `${temporary.path}/original`, workspaceID: "workspace_fixture" }
|
||||
const shell: ShellInfo = {
|
||||
id: "sh_fixture",
|
||||
command: "render-scene --quality high",
|
||||
cwd: location.directory,
|
||||
shell: "/bin/sh",
|
||||
file: `${temporary.path}/capture.out`,
|
||||
status: "running",
|
||||
metadata: { sessionID: "ses_fixture" },
|
||||
time: { started: 0 },
|
||||
}
|
||||
const state = { output, missing: false, failure: false }
|
||||
const requests: { url: URL; method: string }[] = []
|
||||
const events = createEventStream()
|
||||
const envelope = (data: unknown) => json({ location, data })
|
||||
const api = createApi(
|
||||
createFetch((url, request) => {
|
||||
if (!url.pathname.startsWith("/api/shell")) return undefined
|
||||
requests.push({ url, method: request.method })
|
||||
if (url.pathname === "/api/shell") return envelope([shell])
|
||||
if (state.missing)
|
||||
return json({ _tag: "ShellNotFoundError", id: shell.id, message: "Shell not found" }, { status: 404 })
|
||||
if (state.failure) return new Response("Unavailable", { status: 503 })
|
||||
if (url.pathname === `/api/shell/${shell.id}`) return envelope(shell)
|
||||
const bytes = Buffer.from(state.output)
|
||||
const cursor = Math.min(Number(url.searchParams.get("cursor") ?? 0), bytes.length)
|
||||
const end = Math.min(cursor + Number(url.searchParams.get("limit") ?? 65536), bytes.length)
|
||||
return envelope({
|
||||
output: bytes.subarray(cursor, end).toString(),
|
||||
cursor: end,
|
||||
size: bytes.length,
|
||||
truncated: false,
|
||||
})
|
||||
}, events).fetch,
|
||||
)
|
||||
|
||||
function Shells() {
|
||||
const data = useData()
|
||||
const [open, setOpen] = createSignal(true)
|
||||
onMount(() => void data.shell.sync(location))
|
||||
return <Composer sessionID="ses_fixture" open={open()} defaultTab="shell" onClose={() => setOpen(false)} />
|
||||
}
|
||||
|
||||
const app = await testRender(
|
||||
() => (
|
||||
<TestTuiContexts directory={temporary.path} paths={{ state: temporary.path }}>
|
||||
<ConfigProvider config={createTuiResolvedConfig({ session: { terminal: false } })}>
|
||||
<RouteProvider initialRoute={{ type: "session", sessionID: "ses_fixture" }}>
|
||||
<ClientProvider api={api}>
|
||||
<DataProvider directory={temporary.path}>
|
||||
<ThemeProvider mode={width === 40 ? "light" : "dark"} source={emptyThemeSource}>
|
||||
<Keymap.Provider>
|
||||
<ToastProvider>
|
||||
<DialogProvider>
|
||||
<Shells />
|
||||
</DialogProvider>
|
||||
</ToastProvider>
|
||||
</Keymap.Provider>
|
||||
</ThemeProvider>
|
||||
</DataProvider>
|
||||
</ClientProvider>
|
||||
</RouteProvider>
|
||||
</ConfigProvider>
|
||||
</TestTuiContexts>
|
||||
),
|
||||
{ width, height: 30, kittyKeyboard: true },
|
||||
)
|
||||
app.renderer.start()
|
||||
await app.waitForFrame((frame) => frame.includes(shell.command))
|
||||
return {
|
||||
...app,
|
||||
state,
|
||||
shell,
|
||||
location,
|
||||
requests,
|
||||
events,
|
||||
async [Symbol.asyncDispose]() {
|
||||
app.renderer.destroy()
|
||||
await temporary[Symbol.asyncDispose]()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
test.each([40, 100])("shell output opens, follows, scrolls, and survives exit at %s columns", async (width) => {
|
||||
await using app = await setup(width, Array.from({ length: 50 }, (_, i) => `Frame ${i + 1}\n`).join(""))
|
||||
expect(app.captureCharFrame()).toContain("output")
|
||||
app.mockInput.pressEnter()
|
||||
await app.waitForFrame((frame) => frame.includes("Shell output") && frame.includes("Frame 50"))
|
||||
const scroll = app.renderer.root.findDescendantById("shell-output-scroll")
|
||||
if (!(scroll instanceof ScrollBoxRenderable)) throw new Error("Output scrollbox missing")
|
||||
expect(scroll.scrollTop).toBeGreaterThan(0)
|
||||
|
||||
app.mockInput.pressKey("HOME")
|
||||
await app.waitForFrame((frame) => frame.includes("Frame 1\n") || /Frame 1\s/.test(frame))
|
||||
expect(scroll.scrollTop).toBe(0)
|
||||
app.state.output += "Frame 51\n"
|
||||
await app.waitFor(
|
||||
() =>
|
||||
app.requests.some(
|
||||
(request) => request.url.searchParams.get("cursor") === String(Buffer.byteLength(app.state.output)),
|
||||
),
|
||||
{ maxPasses: 150 },
|
||||
)
|
||||
expect(scroll.scrollTop).toBe(0)
|
||||
app.mockInput.pressKey("END")
|
||||
await app.waitForFrame((frame) => frame.includes("Frame 51"))
|
||||
app.shell.status = "exited"
|
||||
app.shell.exit = 0
|
||||
app.events.emit({
|
||||
id: "evt_exit",
|
||||
created: 0,
|
||||
type: "shell.exited",
|
||||
location: app.location,
|
||||
data: { id: app.shell.id, exit: 0, status: "exited" },
|
||||
})
|
||||
await app.waitForFrame((frame) => frame.includes("code 0"), { maxPasses: 100 })
|
||||
const metadataReads = app.requests.filter((request) => request.url.pathname === `/api/shell/${app.shell.id}`).length
|
||||
// Terminal metadata can arrive before the capture's final flush.
|
||||
app.state.output += "\u001b[32mRender complete\u001b[0m\r\n"
|
||||
await app.waitForFrame((frame) => frame.includes("Render complete") && frame.includes("code 0"), { maxPasses: 100 })
|
||||
expect(app.requests.filter((request) => request.url.pathname === `/api/shell/${app.shell.id}`)).toHaveLength(
|
||||
metadataReads,
|
||||
)
|
||||
expect(app.captureCharFrame()).not.toContain("[32m")
|
||||
expect(app.requests.every((request) => request.method === "GET")).toBe(true)
|
||||
const reads = app.requests.filter((request) => request.url.pathname !== "/api/shell")
|
||||
expect(reads.every((request) => request.url.searchParams.get("location[directory]") === app.location.directory)).toBe(
|
||||
true,
|
||||
)
|
||||
expect(
|
||||
reads.every((request) => request.url.searchParams.get("location[workspace]") === app.location.workspaceID),
|
||||
).toBe(true)
|
||||
|
||||
app.mockInput.pressEscape()
|
||||
await app.waitForFrame((frame) => !frame.includes("Shell output") && frame.includes("No shell commands"))
|
||||
const count = app.requests.length
|
||||
await Bun.sleep(1100)
|
||||
expect(app.requests).toHaveLength(count)
|
||||
})
|
||||
|
||||
test("empty output explains redirection, retries errors, and preserves output after removal", async () => {
|
||||
await using app = await setup(100)
|
||||
app.mockInput.pressEnter()
|
||||
await app.waitForFrame((frame) => frame.includes("No captured output") && frame.includes("redirected"))
|
||||
app.state.failure = true
|
||||
await app.waitForFrame((frame) => frame.includes("Retrying"), { maxPasses: 100 })
|
||||
app.state.failure = false
|
||||
app.state.output = "Recovered output\n"
|
||||
await app.waitForFrame((frame) => frame.includes("Recovered output") && !frame.includes("Retrying"), {
|
||||
maxPasses: 100,
|
||||
})
|
||||
app.state.missing = true
|
||||
await app.waitForFrame((frame) => frame.includes("no longer available"), { maxPasses: 100 })
|
||||
expect(app.captureCharFrame()).toContain("Recovered output")
|
||||
const count = app.requests.length
|
||||
await Bun.sleep(1100)
|
||||
expect(app.requests).toHaveLength(count)
|
||||
})
|
||||
|
||||
test.each([40, 100])("mouse-wheel scrolling pauses and resumes output following at %s columns", async (width) => {
|
||||
await using app = await setup(width, Array.from({ length: 50 }, (_, i) => `Frame ${i + 1}\n`).join(""))
|
||||
app.mockInput.pressEnter()
|
||||
await app.waitForFrame((frame) => frame.includes("Shell output") && frame.includes("Frame 50"))
|
||||
const scroll = app.renderer.root.findDescendantById("shell-output-scroll")
|
||||
if (!(scroll instanceof ScrollBoxRenderable)) throw new Error("Output scrollbox missing")
|
||||
const bottom = scroll.scrollTop
|
||||
await app.mockMouse.scroll(scroll.viewport.x + 2, scroll.viewport.y + 2, "up")
|
||||
await app.waitFor(() => scroll.scrollTop < bottom)
|
||||
const paused = scroll.scrollTop
|
||||
const height = scroll.scrollHeight
|
||||
|
||||
app.state.output += "Frame 51\n"
|
||||
await app.waitFor(() => scroll.scrollHeight > height, { maxPasses: 100 })
|
||||
expect(scroll.scrollTop).toBe(paused)
|
||||
expect(app.captureCharFrame()).toContain("Shell output")
|
||||
|
||||
await app.mockMouse.scroll(scroll.viewport.x + 2, scroll.viewport.y + 2, "down")
|
||||
await app.mockMouse.scroll(scroll.viewport.x + 2, scroll.viewport.y + 2, "down")
|
||||
await app.waitFor(() => scroll.scrollTop === scroll.scrollHeight - scroll.viewport.height)
|
||||
const followed = scroll.scrollTop
|
||||
app.state.output += "Frame 52\n"
|
||||
await app.waitForFrame((frame) => frame.includes("Frame 52"), { maxPasses: 100 })
|
||||
expect(scroll.scrollTop).toBeGreaterThan(followed)
|
||||
expect(scroll.scrollTop).toBe(scroll.scrollHeight - scroll.viewport.height)
|
||||
})
|
||||
|
||||
test("large captures open at a bounded tail and clicking a shell opens the viewer", async () => {
|
||||
await using app = await setup(100, "old output\n".repeat(20000) + "Latest frame\n")
|
||||
const row = app
|
||||
.captureCharFrame()
|
||||
.split("\n")
|
||||
.findIndex((line) => line.includes(app.shell.command))
|
||||
await app.mockMouse.click(6, row)
|
||||
await app.waitForFrame((frame) => frame.includes("Latest frame") && frame.includes("Earlier output omitted"))
|
||||
const reads = app.requests.filter((request) => request.url.pathname.endsWith("/output"))
|
||||
expect(reads[0]?.url.searchParams.get("cursor")).toBe(String(Number.MAX_SAFE_INTEGER))
|
||||
expect(reads[1]?.url.searchParams.get("cursor")).toBe(String(Buffer.byteLength(app.state.output) - 65536))
|
||||
expect(reads[1]?.url.searchParams.get("limit")).toBe("65536")
|
||||
})
|
||||
@@ -58,7 +58,6 @@ describe("run catalog shared", () => {
|
||||
models: {
|
||||
"gpt-5": {
|
||||
name: "Little Frank",
|
||||
time: { released: 1 },
|
||||
cost: {
|
||||
input: 0,
|
||||
},
|
||||
|
||||
@@ -82,13 +82,11 @@ function model(input: {
|
||||
id: string
|
||||
name: string
|
||||
status?: "active" | "deprecated"
|
||||
released?: number
|
||||
cost?: number
|
||||
variants?: Record<string, Record<string, never>>
|
||||
}) {
|
||||
return {
|
||||
name: input.name,
|
||||
time: input.released === undefined ? undefined : { released: input.released },
|
||||
cost: {
|
||||
input: input.cost ?? 1,
|
||||
},
|
||||
@@ -1035,7 +1033,6 @@ test("direct skill panel renders searchable skill list", async () => {
|
||||
command({ name: "review", description: "Review code" }),
|
||||
command({ name: "internal", description: "Skill command", source: "skill" }),
|
||||
command({ name: "formatter", description: "Apply formatter fixes", source: "skill" }),
|
||||
command({ name: "auto-formatter", description: "Format code", source: "skill" }),
|
||||
])
|
||||
const selected: string[] = []
|
||||
|
||||
@@ -1069,13 +1066,11 @@ test("direct skill panel renders searchable skill list", async () => {
|
||||
expect(frame).toContain("formatter")
|
||||
expect(frame).toContain("Apply formatter fixes")
|
||||
expect(frame).not.toContain("review")
|
||||
app.mockInput.pressEnter()
|
||||
expect(selected).toEqual(["auto-formatter"])
|
||||
await app.mockInput.typeText("format")
|
||||
await app.renderOnce()
|
||||
expect(app.captureCharFrame()).not.toContain("internal")
|
||||
app.mockInput.pressEnter()
|
||||
expect(selected).toEqual(["auto-formatter", "formatter"])
|
||||
expect(selected).toEqual(["formatter"])
|
||||
} finally {
|
||||
app.renderer.destroy()
|
||||
}
|
||||
@@ -2468,112 +2463,6 @@ test("direct permission rejection submits through keymap return binding", async
|
||||
}
|
||||
})
|
||||
|
||||
test.each(["", "model"])(
|
||||
"direct model panel orders free, release, and name with provider grouping only for blank query '%s'",
|
||||
async (query) => {
|
||||
const providers: RunProvider[] = [
|
||||
{
|
||||
id: "other",
|
||||
name: "Another provider",
|
||||
models: {
|
||||
model: model({ id: "model", name: "Model", cost: 0, released: 1 }),
|
||||
"model-e": model({ id: "model-e", name: "Model E", released: 1000 }),
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "opencode",
|
||||
name: "OpenCode",
|
||||
models: {
|
||||
"model-d": model({ id: "model-d", name: "Model D" }),
|
||||
"model-c": model({ id: "model-c", name: "Model C", released: 500 }),
|
||||
"b-model": model({ id: "b-model", name: "B Model", cost: 0, released: 200 }),
|
||||
"a-model": model({ id: "a-model", name: "A Model", cost: 0, released: 200 }),
|
||||
"z-model": model({ id: "z-model", name: "Z Model", cost: 0, released: 300 }),
|
||||
old: model({ id: "old", name: "Old Model", cost: 0, released: 2000, status: "deprecated" }),
|
||||
},
|
||||
},
|
||||
]
|
||||
const selected: NonNullable<RunInput["model"]>[] = []
|
||||
const current = { providerID: "opencode", modelID: "a-model" }
|
||||
const app = await testRender(
|
||||
() => (
|
||||
<box width={100} height={RUN_COMMAND_PANEL_ROWS}>
|
||||
<RunModelSelectBody
|
||||
theme={() => RUN_THEME_FALLBACK.footer}
|
||||
providers={() => providers}
|
||||
current={() => current}
|
||||
onClose={() => {}}
|
||||
onSelect={(value) => selected.push(value)}
|
||||
/>
|
||||
</box>
|
||||
),
|
||||
{ width: 100, height: RUN_COMMAND_PANEL_ROWS + 1 },
|
||||
)
|
||||
|
||||
try {
|
||||
await app.renderOnce()
|
||||
if (query) await app.mockInput.typeText(query)
|
||||
await app.renderOnce()
|
||||
const names = query
|
||||
? ["Z Model", "A Model", "B Model", "Model E", "Model C", "Model", "Model D"]
|
||||
: ["Z Model", "A Model", "B Model", "Model C", "Model D", "Model E", "Model"]
|
||||
const rows = app
|
||||
.captureCharFrame()
|
||||
.split("\n")
|
||||
.map((row) => row.trim().split(/\s{2,}/)[0])
|
||||
expect(rows.filter((row) => names.includes(row))).toEqual(names)
|
||||
expect(app.captureCharFrame()).not.toContain("Old Model")
|
||||
expect(rows.filter((row) => ["OpenCode", "Another provider"].includes(row))).toEqual(
|
||||
query ? [] : ["OpenCode", "Another provider"],
|
||||
)
|
||||
if (!query) {
|
||||
expect(app.captureCharFrame()).toContain("current")
|
||||
expect(app.captureCharFrame().match(/\bFree\b/g)).toHaveLength(2)
|
||||
}
|
||||
|
||||
app.mockInput.pressEnter()
|
||||
expect(selected.at(-1)).toEqual(query ? { providerID: "opencode", modelID: "z-model" } : current)
|
||||
app.mockInput.pressKey("HOME")
|
||||
for (const [providerID, modelID] of [
|
||||
["opencode", "z-model"],
|
||||
["opencode", "a-model"],
|
||||
["opencode", "b-model"],
|
||||
...(query
|
||||
? [
|
||||
["other", "model-e"],
|
||||
["opencode", "model-c"],
|
||||
["other", "model"],
|
||||
["opencode", "model-d"],
|
||||
]
|
||||
: [
|
||||
["opencode", "model-c"],
|
||||
["opencode", "model-d"],
|
||||
["other", "model-e"],
|
||||
["other", "model"],
|
||||
]),
|
||||
]) {
|
||||
app.mockInput.pressEnter()
|
||||
expect(selected.at(-1)).toEqual({ providerID, modelID })
|
||||
app.mockInput.pressKey("ARROW_DOWN")
|
||||
await app.renderOnce()
|
||||
}
|
||||
app.mockInput.pressKey("ARROW_UP")
|
||||
app.mockInput.pressEnter()
|
||||
expect(selected.at(-1)).toEqual({ providerID: "other", modelID: query ? "model" : "model-e" })
|
||||
|
||||
if (query) {
|
||||
app.mockInput.pressKey("u", { ctrl: true })
|
||||
await app.renderOnce()
|
||||
app.mockInput.pressKey("HOME")
|
||||
app.mockInput.pressEnter()
|
||||
expect(selected.at(-1)).toEqual({ providerID: "opencode", modelID: "z-model" })
|
||||
}
|
||||
} finally {
|
||||
app.renderer.destroy()
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
test("direct model panel keeps native V2 light search and options readable on a transparent background", async () => {
|
||||
const theme = await nativeLightTheme()
|
||||
const background = RGBA.fromHex("#ffffff")
|
||||
|
||||
@@ -89,7 +89,6 @@ describe("run runtime boot", () => {
|
||||
models: {
|
||||
"gpt-5": {
|
||||
name: "gpt-5",
|
||||
time: { released: 1 },
|
||||
cost: {
|
||||
input: 0,
|
||||
},
|
||||
|
||||
@@ -1,133 +0,0 @@
|
||||
import { expect, test } from "bun:test"
|
||||
import { createTestRenderer } from "@opentui/core/testing"
|
||||
import { InputRenderable } from "@opentui/core"
|
||||
import { Effect, FileSystem } from "effect"
|
||||
import { Global } from "@opencode-ai/util/global"
|
||||
import { createEventStream, createFetch, directory, json } from "./fixture/tui-client"
|
||||
import { tmpdir } from "./fixture/fixture"
|
||||
|
||||
test.each(["all", "connected", "connect"])(
|
||||
"%s model picker keeps release order before and after searching",
|
||||
async (entry) => {
|
||||
await using state = await tmpdir()
|
||||
const setup = await createTestRenderer({ width: 110, height: 40, useThread: false, kittyKeyboard: true })
|
||||
setup.renderer.start()
|
||||
const ready = Promise.withResolvers<void>()
|
||||
const location = { directory, project: { id: "proj_test", directory, canonical: directory } }
|
||||
let connected = entry === "connected"
|
||||
const calls = createFetch((url) => {
|
||||
if (url.pathname === "/api/agent")
|
||||
return json({ location, data: [{ id: "build", mode: "primary", hidden: false, permissions: [] }] })
|
||||
if (url.pathname === "/api/provider")
|
||||
return json({
|
||||
location,
|
||||
data: [
|
||||
{ id: "demo", name: "Demo" },
|
||||
{ id: "other", name: "Other" },
|
||||
],
|
||||
})
|
||||
if (url.pathname === "/api/integration")
|
||||
return json({
|
||||
location,
|
||||
data: [
|
||||
{
|
||||
id: "demo",
|
||||
name: "Demo",
|
||||
methods: [{ type: "key" }],
|
||||
connections: connected ? [{ type: "credential", id: "cred_demo", label: "Demo" }] : [],
|
||||
},
|
||||
],
|
||||
})
|
||||
if (url.pathname === "/api/integration/demo/connect/key") {
|
||||
connected = true
|
||||
return new Response(null, { status: 204 })
|
||||
}
|
||||
if (url.pathname === "/api/model")
|
||||
return json({
|
||||
location,
|
||||
data: [
|
||||
{
|
||||
id: "haiku-other",
|
||||
providerID: "other",
|
||||
name: "Other Haiku",
|
||||
enabled: true,
|
||||
variants: [],
|
||||
cost: [],
|
||||
time: { released: 0 },
|
||||
},
|
||||
...[
|
||||
{ id: "haiku-3", name: "Claude Haiku 3", released: 1 },
|
||||
{ id: "haiku-4-5", name: "Claude Haiku 4.5", released: 2 },
|
||||
].map((model) => ({
|
||||
id: model.id,
|
||||
providerID: "demo",
|
||||
name: model.name,
|
||||
enabled: true,
|
||||
variants: [],
|
||||
cost: [],
|
||||
time: { released: model.released },
|
||||
})),
|
||||
],
|
||||
})
|
||||
return undefined
|
||||
}, createEventStream())
|
||||
const server = Bun.serve({ port: 0, fetch: (request) => calls.fetch(request) })
|
||||
const { run } = await import("../src/app")
|
||||
const task = Effect.runPromise(
|
||||
run({
|
||||
app: { name: "test", version: "test", channel: "test" },
|
||||
server: { endpoint: { url: server.url.toString() } },
|
||||
config: { get: async () => ({ animations: false }), update: async () => ({}) },
|
||||
packages: { prepare: async () => ({ directory: "" }) },
|
||||
terminalHandoff: async () => ({ renderer: setup.renderer, mode: "dark", complete: ready.resolve }),
|
||||
args: {},
|
||||
log: () => {},
|
||||
}).pipe(Effect.provide(Global.layerWith({ state: state.path })), Effect.provide(FileSystem.layerNoop({}))),
|
||||
)
|
||||
try {
|
||||
await ready.promise
|
||||
await setup.waitForFrame((frame) => frame.includes("Build ·"))
|
||||
await setup.mockInput.typeText("/models")
|
||||
setup.mockInput.pressEnter()
|
||||
await setup.waitForFrame(
|
||||
(frame) => frame.includes("Select model") && setup.renderer.currentFocusedRenderable instanceof InputRenderable,
|
||||
)
|
||||
if (entry === "connect") {
|
||||
setup.mockInput.pressKey("a", { ctrl: true })
|
||||
await setup.waitForFrame((frame) => frame.includes("Connect an integration") && frame.includes("Services"))
|
||||
setup.mockInput.pressEnter()
|
||||
await setup.waitForFrame((frame) => frame.includes("API key"))
|
||||
await setup.mockInput.typeText("fixture-key")
|
||||
setup.mockInput.pressEnter()
|
||||
await setup.waitForFrame((frame) => frame.includes("Connected Demo") && frame.includes("Claude Haiku 4.5"))
|
||||
expect(setup.captureCharFrame().split("Connect an integration")[0]).not.toContain("Other Haiku")
|
||||
}
|
||||
const initial = setup.captureCharFrame()
|
||||
expect(initial.indexOf("Claude Haiku 4.5")).toBeLessThan(initial.indexOf("Claude Haiku 3"))
|
||||
await setup.mockInput.typeText("haik")
|
||||
const frame = await setup.waitForFrame((frame) => frame.includes("haik") && frame.includes("Claude Haiku 3"))
|
||||
expect(frame.indexOf("Claude Haiku 4.5")).toBeLessThan(frame.indexOf("Claude Haiku 3"))
|
||||
setup.mockInput.pressKey("u", { ctrl: true })
|
||||
await setup.waitForFrame((frame) => !frame.includes("haik"))
|
||||
expect(setup.captureCharFrame().indexOf("Claude Haiku 4.5")).toBeLessThan(
|
||||
setup.captureCharFrame().indexOf("Claude Haiku 3"),
|
||||
)
|
||||
await setup.mockInput.typeText("no-such-model")
|
||||
await setup.waitForFrame((frame) => frame.includes("No results found"))
|
||||
setup.mockInput.pressKey("u", { ctrl: true })
|
||||
await setup.mockInput.typeText("haik")
|
||||
await setup.waitForFrame((frame) => frame.includes("haik") && frame.includes("Claude Haiku 4.5"))
|
||||
setup.mockInput.pressEnter()
|
||||
await setup.waitForFrame(
|
||||
(frame) =>
|
||||
!frame.includes("Select model") &&
|
||||
!frame.includes("Connect an integration") &&
|
||||
frame.includes("Build · Claude Haiku 4.5"),
|
||||
)
|
||||
} finally {
|
||||
setup.renderer.destroy()
|
||||
await task
|
||||
await server.stop()
|
||||
}
|
||||
},
|
||||
)
|
||||
@@ -9,6 +9,7 @@
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
[data-component="split-button-v2"].session-review-v2-open-in-app,
|
||||
[data-component="split-button-v2"]:is(:hover, :has([data-component="split-button-v2-menu-trigger"][data-expanded])) {
|
||||
box-shadow: inset 0 0 0 1px var(--v2-border-border-muted);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Icon } from "@opencode-ai/ui/icon"
|
||||
import { AppIcon } from "@opencode-ai/ui/app-icon"
|
||||
import { SplitButton, SplitButtonAction, SplitButtonMenuTrigger } from "./split-button"
|
||||
|
||||
export default {
|
||||
@@ -29,3 +30,16 @@ export const Disabled = {
|
||||
</SplitButton>
|
||||
),
|
||||
}
|
||||
|
||||
export const OpenIn = {
|
||||
render: () => (
|
||||
<SplitButton class="session-review-v2-open-in-app">
|
||||
<SplitButtonAction aria-label="Open in Finder">
|
||||
<AppIcon id="finder" />
|
||||
</SplitButtonAction>
|
||||
<SplitButtonMenuTrigger aria-label="Open options">
|
||||
<Icon name="chevron-down" size="small" />
|
||||
</SplitButtonMenuTrigger>
|
||||
</SplitButton>
|
||||
),
|
||||
}
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
export type ModelOrder = {
|
||||
free: boolean
|
||||
released: number
|
||||
name: string
|
||||
}
|
||||
|
||||
/** Apply after filtering so fuzzy relevance cannot put older models first. */
|
||||
export function compareModelOrder(a: ModelOrder, b: ModelOrder) {
|
||||
return Number(b.free) - Number(a.free) || b.released - a.released || a.name.localeCompare(b.name)
|
||||
}
|
||||
@@ -210,8 +210,12 @@ const layer = Layer.effect(
|
||||
Effect.gen(function* () {
|
||||
const { Arborist } = yield* Effect.promise(() => import("@npmcli/arborist"))
|
||||
const add = input.add ?? []
|
||||
const npmOptions = yield* NpmConfig.load(input.config ?? input.dir)
|
||||
const options = input.update ? { ...npmOptions, preferOnline: true, noGitRevCache: true } : npmOptions
|
||||
const options = {
|
||||
...(yield* NpmConfig.load(input.config ?? input.dir)),
|
||||
...(input.update ? { preferOnline: true, noGitRevCache: true } : {}),
|
||||
// Audit reports are unused here, but Arborist waits for them before completing an install.
|
||||
audit: false,
|
||||
}
|
||||
const arborist = new Arborist({
|
||||
...options,
|
||||
path: input.dir,
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
import { expect, test } from "bun:test"
|
||||
import { compareModelOrder } from "../src/model-order.js"
|
||||
|
||||
test("model order is free first, newest release, then name", () => {
|
||||
const models = [
|
||||
{ name: "Paid newest", released: 30, free: false },
|
||||
{ name: "Free older", released: 10, free: true },
|
||||
{ name: "Paid unknown", released: 0, free: false },
|
||||
{ name: "Free Z", released: 20, free: true },
|
||||
{ name: "Free A", released: 20, free: true },
|
||||
{ name: "Paid older", released: 10, free: false },
|
||||
]
|
||||
expect(models.toSorted(compareModelOrder).map((model) => model.name)).toEqual([
|
||||
"Free A",
|
||||
"Free Z",
|
||||
"Free older",
|
||||
"Paid newest",
|
||||
"Paid older",
|
||||
"Paid unknown",
|
||||
])
|
||||
expect(models[0].name).toBe("Paid newest")
|
||||
})
|
||||
|
||||
test("equal model keys retain the caller's existing order", () => {
|
||||
const models = ["provider-b", "provider-a"].map((provider) => ({
|
||||
provider,
|
||||
name: "Claude Haiku 4.5",
|
||||
released: 20,
|
||||
free: false,
|
||||
}))
|
||||
expect(compareModelOrder(models[0], models[1])).toBe(0)
|
||||
expect(models.toSorted(compareModelOrder)).toEqual(models)
|
||||
})
|
||||
@@ -317,8 +317,13 @@ The retired `diff.toggle`, `diff.expand`, `diff.expand_all`, `diff.collapse`, an
|
||||
| `composer.subagent.interrupt` | `ctrl+d` | Interrupt subagent |
|
||||
| `composer.shell.up` | `up` | Previous shell |
|
||||
| `composer.shell.down` | `down` | Next shell |
|
||||
| `composer.shell.select` | `return` | View shell output |
|
||||
| `composer.shell.kill` | `ctrl+d` | Kill shell command |
|
||||
|
||||
Select a running command in the **Shell** tab and press **Enter**, or click it, to view captured stdout and stderr.
|
||||
Use **↑/↓**, **Page Up/Down**, or **Home** to scroll, **End** to follow new output, and **Esc** to return without stopping the command.
|
||||
The viewer shows recent output and stays open after exit; output redirected to a file is not included.
|
||||
|
||||
## Dialogs And Autocomplete
|
||||
|
||||
| ID | Default | Description |
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import { Effect, Stream } from "effect"
|
||||
import { Llm, OpenCodeDriver } from "opencode-drive"
|
||||
|
||||
const label = process.env.DEMO_LABEL ?? "AFTER"
|
||||
|
||||
// Run from the repository root with `opencode-drive run script/drive/shell-output.ts`.
|
||||
// Set OPENCODE_DEV to an immutable base worktree and DEMO_LABEL=BEFORE for comparison.
|
||||
// Only the conversation is simulated; shell execution and output reads are real.
|
||||
export default OpenCodeDriver.use(
|
||||
{
|
||||
opencode: { dev: process.env.OPENCODE_DEV ?? process.cwd() },
|
||||
keepArtifacts: true,
|
||||
tui: { recording: true, keypressOverlay: true, viewport: { cols: 90, rows: 30 } },
|
||||
config: { autoupdate: false, username: "Demo" },
|
||||
tuiConfig: { theme: { name: "opencode", mode: "dark" }, animations: false, tabs: { enabled: false } },
|
||||
project: {
|
||||
git: true,
|
||||
files: {
|
||||
"README.md": "# Shell output demo\nDeterministic real shell output.\n",
|
||||
"render-scene.sh": [
|
||||
"#!/bin/sh",
|
||||
"i=1",
|
||||
'while [ "$i" -le 40 ]; do printf "Frame %02d: rendered successfully\\n" "$i"; i=$((i+1)); done',
|
||||
"while [ ! -f continue ]; do sleep 0.1; done",
|
||||
'while [ "$i" -le 48 ]; do printf "Frame %02d: rendered successfully\\n" "$i"; i=$((i+1)); sleep 0.25; done',
|
||||
"while [ ! -f finish ]; do sleep 0.1; done",
|
||||
"printf 'Diagnostics: no errors\\n' >&2",
|
||||
"printf 'Render complete: 48 frames saved.\\n'",
|
||||
].join("\n"),
|
||||
},
|
||||
},
|
||||
},
|
||||
({ ui, llm, tui, opencode, artifacts }) =>
|
||||
Effect.gen(function* () {
|
||||
const recording = tui.recording
|
||||
if (!recording) return yield* Effect.fail(new Error("Recording required"))
|
||||
yield* llm.serve(() => Stream.make(Llm.text("Ready to inspect the render job.")))
|
||||
yield* ui.submit("Inspect the render job.")
|
||||
yield* ui.waitFor("Ready to inspect the render job.")
|
||||
const sessions = yield* opencode.session.list({ limit: 1, order: "desc" })
|
||||
const session = sessions.data[0]
|
||||
if (!session) return yield* Effect.fail(new Error("Session missing"))
|
||||
yield* opencode.session.rename({ sessionID: session.id, title: "Shell output demo" })
|
||||
yield* opencode.shell.create({ command: "sh render-scene.sh", timeout: 0, metadata: { sessionID: session.id } })
|
||||
yield* ui.arrow("down")
|
||||
yield* ui.arrow("right")
|
||||
yield* ui.waitFor("sh render-scene.sh")
|
||||
yield* recording.mark(`${label}: select a running shell`)
|
||||
yield* Effect.sleep(1000)
|
||||
yield* ui.enter()
|
||||
yield* ui.waitFor(label === "AFTER" ? "Frame 40: rendered successfully" : "sh render-scene.sh")
|
||||
yield* Effect.sleep(1000)
|
||||
yield* recording.mark(`${label}: Enter ${label === "AFTER" ? "opens live output" : "does nothing"}`)
|
||||
console.log("opened:", yield* ui.screenshot(`${label.toLowerCase()}-opened`))
|
||||
yield* Effect.promise(() => Bun.write(`${artifacts}/files/continue`, "go"))
|
||||
if (label === "AFTER") yield* ui.waitFor("Frame 48: rendered successfully")
|
||||
yield* Effect.sleep(2800)
|
||||
yield* ui.press("home")
|
||||
yield* ui.waitFor(label === "AFTER" ? "Frame 01: rendered successfully" : "sh render-scene.sh")
|
||||
yield* recording.mark(`${label}: ${label === "AFTER" ? "Home scrolls to earlier output" : "no output to scroll"}`)
|
||||
yield* Effect.sleep(1500)
|
||||
console.log("scrolled:", yield* ui.screenshot(`${label.toLowerCase()}-scrolled`))
|
||||
yield* ui.press("end")
|
||||
yield* ui.waitFor(label === "AFTER" ? "Frame 48: rendered successfully" : "sh render-scene.sh")
|
||||
yield* recording.mark(`${label}: ${label === "AFTER" ? "End follows the latest output" : "no output to follow"}`)
|
||||
yield* Effect.sleep(1000)
|
||||
yield* Effect.promise(() => Bun.write(`${artifacts}/files/finish`, "go"))
|
||||
yield* ui.waitFor(label === "AFTER" ? "Render complete: 48 frames saved." : "No shell commands")
|
||||
if (label === "AFTER") yield* ui.waitFor("Exited · code 0")
|
||||
yield* Effect.sleep(1600)
|
||||
yield* recording.mark(
|
||||
`${label}: ${label === "AFTER" ? "result stays open after exit" : "finished shell disappears"}`,
|
||||
)
|
||||
console.log("exited:", yield* ui.screenshot(`${label.toLowerCase()}-exited`))
|
||||
yield* Effect.sleep(2000)
|
||||
yield* ui.resize({ cols: 40, rows: 24 })
|
||||
yield* Effect.sleep(500)
|
||||
console.log("narrow:", yield* ui.screenshot(`${label.toLowerCase()}-narrow`))
|
||||
yield* ui.resize({ cols: 90, rows: 30 })
|
||||
yield* Effect.sleep(500)
|
||||
yield* ui.press("escape")
|
||||
if (label === "AFTER") yield* ui.waitFor("No shell commands")
|
||||
yield* recording.mark(`${label}: Esc back`)
|
||||
yield* Effect.sleep(1000)
|
||||
console.log("back:", yield* ui.screenshot(`${label.toLowerCase()}-back`))
|
||||
return console.log("video:", yield* recording.finish())
|
||||
}),
|
||||
)
|
||||
Reference in New Issue
Block a user