mirror of
https://github.com/anomalyco/opencode.git
synced 2026-07-30 22:56:11 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3989bedd21 |
@@ -0,0 +1,133 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { createRoot } from "solid-js"
|
||||
import { createStore } from "solid-js/store"
|
||||
import { SESSION_OPEN_FILE_TAB } from "./helpers"
|
||||
import { createSessionSidePanelController, sessionSidePanelHandoffFiles } from "./session-side-panel-controller"
|
||||
|
||||
function createController(options?: { active?: string; all?: string[]; mode?: "changes" | "all" }) {
|
||||
const calls: string[] = []
|
||||
const [state, setState] = createStore({
|
||||
active: options?.active,
|
||||
all: options?.all ?? ["file://src/a.ts"],
|
||||
preview: undefined as string | undefined,
|
||||
mode: options?.mode ?? ("changes" as "changes" | "all"),
|
||||
})
|
||||
return createRoot((dispose) => ({
|
||||
dispose,
|
||||
calls,
|
||||
state,
|
||||
controller: createSessionSidePanelController({
|
||||
currentTab: () => state.active,
|
||||
allTabs: () => state.all,
|
||||
openTab: (tab) => calls.push(`open:${tab}`),
|
||||
preview: (tab) => calls.push(`preview:${tab}`),
|
||||
setActive: (tab) => calls.push(`active:${tab}`),
|
||||
normalizeFileTab: (tab) => `file://${tab.slice("file://".length).toLowerCase()}`,
|
||||
pathFromTab: (tab) => (tab.startsWith("file://") ? tab.slice("file://".length) : undefined),
|
||||
loadFile: (path) => calls.push(`load:${path}`),
|
||||
reviewEnabled: () => true,
|
||||
canReview: () => true,
|
||||
fileBrowserEnabled: () => true,
|
||||
reviewPanelOpened: () => false,
|
||||
openReviewPanel: () => calls.push("panel"),
|
||||
treeMode: () => state.mode,
|
||||
setTreeMode: (mode) => setState("mode", mode),
|
||||
fileReady: () => false,
|
||||
sessionKey: () => "session",
|
||||
selectedLines: () => null,
|
||||
persistHandoff: () => undefined,
|
||||
showDialog: () => undefined,
|
||||
}),
|
||||
}))
|
||||
}
|
||||
|
||||
describe("session side panel controller", () => {
|
||||
test("normalizes and centralizes file tab selection mutations", async () => {
|
||||
const owned = createController()
|
||||
|
||||
owned.controller.tabs.activate("file://SRC/A.ts")
|
||||
expect(owned.calls).toEqual(["load:src/a.ts", "panel", "active:file://src/a.ts"])
|
||||
|
||||
owned.calls.length = 0
|
||||
owned.controller.tabs.preview("file://SRC/B.ts")
|
||||
expect(owned.calls).toEqual(["preview:file://src/b.ts", "load:src/b.ts", "panel"])
|
||||
await Promise.resolve()
|
||||
expect(owned.calls).toEqual(["preview:file://src/b.ts", "load:src/b.ts", "panel", "active:file://src/b.ts"])
|
||||
|
||||
owned.calls.length = 0
|
||||
owned.controller.tabs.open("file://SRC/C.ts")
|
||||
expect(owned.calls).toEqual(["open:file://src/c.ts", "load:src/c.ts", "panel", "active:file://src/c.ts"])
|
||||
owned.dispose()
|
||||
})
|
||||
|
||||
test("derives browser selection and controls the tree mode", () => {
|
||||
const owned = createController({ active: "file://src/a.ts", all: ["file://src/a.ts"] })
|
||||
|
||||
expect(owned.controller.browser.tab()).toBe("file://src/a.ts")
|
||||
expect(owned.controller.browser.mounted()).toBe(true)
|
||||
expect(owned.controller.browser.visible()).toBe(true)
|
||||
|
||||
owned.controller.tree.setMode("invalid")
|
||||
expect(owned.state.mode).toBe("changes")
|
||||
owned.controller.tree.showAll()
|
||||
expect(owned.state.mode).toBe("all")
|
||||
owned.controller.tree.showAll()
|
||||
expect(owned.state.mode).toBe("all")
|
||||
|
||||
owned.calls.length = 0
|
||||
owned.controller.browser.open()
|
||||
expect(owned.calls[0]).toBe(`preview:${SESSION_OPEN_FILE_TAB}`)
|
||||
owned.dispose()
|
||||
})
|
||||
|
||||
test("opens the file dialog with the tree handoff callback", async () => {
|
||||
let render: (() => unknown) | undefined
|
||||
let dialogProps: { mode?: "files"; onOpenFile?: (path: string) => void } | undefined
|
||||
const owned = createController()
|
||||
const controller = createSessionSidePanelController({
|
||||
currentTab: () => undefined,
|
||||
allTabs: () => [],
|
||||
openTab: () => undefined,
|
||||
preview: () => undefined,
|
||||
setActive: () => undefined,
|
||||
normalizeFileTab: (tab) => tab,
|
||||
pathFromTab: () => undefined,
|
||||
loadFile: () => undefined,
|
||||
reviewEnabled: () => true,
|
||||
canReview: () => true,
|
||||
fileBrowserEnabled: () => true,
|
||||
reviewPanelOpened: () => true,
|
||||
openReviewPanel: () => undefined,
|
||||
treeMode: owned.controller.tree.mode,
|
||||
setTreeMode: owned.controller.tree.setMode,
|
||||
fileReady: () => false,
|
||||
sessionKey: () => "session",
|
||||
selectedLines: () => null,
|
||||
persistHandoff: () => undefined,
|
||||
showDialog: (value) => (render = value),
|
||||
loadSelectFileDialog: async () => ({
|
||||
DialogSelectFile: (props) => {
|
||||
dialogProps = props
|
||||
return null
|
||||
},
|
||||
}),
|
||||
})
|
||||
|
||||
await controller.dialog.openFile()
|
||||
render?.()
|
||||
expect(dialogProps?.mode).toBe("files")
|
||||
dialogProps?.onOpenFile?.("src/a.ts")
|
||||
expect(owned.state.mode).toBe("all")
|
||||
owned.dispose()
|
||||
})
|
||||
})
|
||||
|
||||
test("projects only file tabs into handoff persistence", () => {
|
||||
expect(
|
||||
sessionSidePanelHandoffFiles(
|
||||
["review", "file://src/a.ts", "file://src/b.ts"],
|
||||
(tab) => (tab.startsWith("file://") ? tab.slice("file://".length) : undefined),
|
||||
(path) => (path.endsWith("a.ts") ? { start: 2, end: 4 } : { startLine: 2, endLine: 4 }),
|
||||
),
|
||||
).toEqual({ "src/a.ts": { start: 2, end: 4 }, "src/b.ts": null })
|
||||
})
|
||||
@@ -0,0 +1,150 @@
|
||||
import { createComponent, createEffect, createMemo, type Accessor, type Component, type JSX } from "solid-js"
|
||||
import type { SelectedLineRange } from "@/context/file"
|
||||
import { SESSION_OPEN_FILE_TAB, createOpenSessionFileTab, createSessionTabs } from "@/pages/session/helpers"
|
||||
|
||||
type TreeMode = "changes" | "all"
|
||||
|
||||
type Input = {
|
||||
currentTab: Accessor<string | undefined>
|
||||
allTabs: Accessor<string[]>
|
||||
openTab: (tab: string) => void
|
||||
preview: (tab: string) => void
|
||||
setActive: (tab: string) => void
|
||||
normalizeFileTab: (tab: string) => string
|
||||
pathFromTab: (tab: string) => string | undefined
|
||||
loadFile: (path: string) => void
|
||||
reviewEnabled: Accessor<boolean>
|
||||
canReview: Accessor<boolean>
|
||||
fileBrowserEnabled: Accessor<boolean>
|
||||
reviewPanelOpened: Accessor<boolean>
|
||||
openReviewPanel: () => void
|
||||
treeMode: Accessor<TreeMode>
|
||||
setTreeMode: (mode: TreeMode) => void
|
||||
fileReady: Accessor<boolean>
|
||||
sessionKey: Accessor<string>
|
||||
selectedLines: (path: string) => unknown
|
||||
persistHandoff: (key: string, files: Record<string, SelectedLineRange | null>) => void
|
||||
showDialog: (render: () => JSX.Element) => void
|
||||
loadSelectFileDialog?: () => Promise<{
|
||||
DialogSelectFile: Component<{ mode?: "files"; onOpenFile?: (path: string) => void }>
|
||||
}>
|
||||
}
|
||||
|
||||
export function createSessionSidePanelController(input: Input) {
|
||||
const normalizeTab = (tab: string) => (tab.startsWith("file://") ? input.normalizeFileTab(tab) : tab)
|
||||
const openReviewPanel = () => {
|
||||
if (!input.reviewPanelOpened()) input.openReviewPanel()
|
||||
}
|
||||
const tabs = createSessionTabs({
|
||||
tabs: () => ({ active: input.currentTab, all: input.allTabs }),
|
||||
pathFromTab: input.pathFromTab,
|
||||
normalizeTab,
|
||||
review: input.reviewEnabled,
|
||||
hasReview: input.canReview,
|
||||
fileBrowser: input.fileBrowserEnabled,
|
||||
})
|
||||
const prepareTab = (tab: string) => {
|
||||
const path = input.pathFromTab(tab)
|
||||
if (path) input.loadFile(path)
|
||||
openReviewPanel()
|
||||
return tab
|
||||
}
|
||||
const open = createOpenSessionFileTab({
|
||||
normalizeTab,
|
||||
openTab: input.openTab,
|
||||
pathFromTab: input.pathFromTab,
|
||||
loadFile: input.loadFile,
|
||||
openReviewPanel,
|
||||
setActive: input.setActive,
|
||||
})
|
||||
const preview = (value: string) => {
|
||||
const next = normalizeTab(value)
|
||||
input.preview(next)
|
||||
const selected = prepareTab(next)
|
||||
queueMicrotask(() => input.setActive(selected))
|
||||
}
|
||||
const activate = (value: string) => input.setActive(prepareTab(normalizeTab(value)))
|
||||
const openFileBrowser = () => preview(SESSION_OPEN_FILE_TAB)
|
||||
const browserTab = createMemo(() => {
|
||||
if (!input.fileBrowserEnabled()) return undefined
|
||||
const active = tabs.activeTab()
|
||||
if (active === SESSION_OPEN_FILE_TAB) return SESSION_OPEN_FILE_TAB
|
||||
if (active && input.pathFromTab(active)) return active
|
||||
return tabs.activeFileTab()
|
||||
})
|
||||
// Keep the shell mounted while any file tab exists. Kobalte briefly selects
|
||||
// Review while replacing a preview trigger, which must not reset sidebar scroll.
|
||||
const fileBrowserMounted = createMemo(
|
||||
() =>
|
||||
input.fileBrowserEnabled() && (tabs.openedTabs().length > 0 || tabs.openFileOpen() || browserTab() !== undefined),
|
||||
)
|
||||
const fileBrowserVisible = createMemo(() => {
|
||||
const active = tabs.activeTab()
|
||||
return active !== "review" && active !== "context" && active !== "empty"
|
||||
})
|
||||
const setTreeMode = (value: string) => {
|
||||
if (value !== "changes" && value !== "all") return
|
||||
input.setTreeMode(value)
|
||||
}
|
||||
const showAllFiles = () => {
|
||||
if (input.treeMode() !== "changes") return
|
||||
input.setTreeMode("all")
|
||||
}
|
||||
const openFileDialog = async () => {
|
||||
const load = input.loadSelectFileDialog ?? (() => import("@/components/dialog-select-file"))
|
||||
const { DialogSelectFile } = await load()
|
||||
input.showDialog(() => createComponent(DialogSelectFile, { mode: "files", onOpenFile: showAllFiles }))
|
||||
}
|
||||
|
||||
createEffect(() => {
|
||||
if (!input.fileReady()) return
|
||||
input.persistHandoff(
|
||||
input.sessionKey(),
|
||||
sessionSidePanelHandoffFiles(input.allTabs(), input.pathFromTab, input.selectedLines),
|
||||
)
|
||||
})
|
||||
|
||||
return {
|
||||
tabs: {
|
||||
...tabs,
|
||||
normalize: normalizeTab,
|
||||
open,
|
||||
preview,
|
||||
activate,
|
||||
},
|
||||
browser: {
|
||||
tab: browserTab,
|
||||
mounted: fileBrowserMounted,
|
||||
visible: fileBrowserVisible,
|
||||
open: openFileBrowser,
|
||||
},
|
||||
tree: {
|
||||
mode: input.treeMode,
|
||||
setMode: setTreeMode,
|
||||
showAll: showAllFiles,
|
||||
},
|
||||
dialog: {
|
||||
openFile: openFileDialog,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export function sessionSidePanelHandoffFiles(
|
||||
tabs: readonly string[],
|
||||
pathFromTab: (tab: string) => string | undefined,
|
||||
selectedLines: (path: string) => unknown,
|
||||
) {
|
||||
return tabs.reduce<Record<string, SelectedLineRange | null>>((files, tab) => {
|
||||
const path = pathFromTab(tab)
|
||||
if (!path) return files
|
||||
const selected = selectedLines(path)
|
||||
files[path] = isSelectedLineRange(selected) ? selected : null
|
||||
return files
|
||||
}, {})
|
||||
}
|
||||
|
||||
function isSelectedLineRange(value: unknown): value is SelectedLineRange {
|
||||
return !!value && typeof value === "object" && "start" in value && "end" in value
|
||||
}
|
||||
|
||||
export type SessionSidePanelController = ReturnType<typeof createSessionSidePanelController>
|
||||
@@ -1,4 +1,4 @@
|
||||
import { For, Match, Show, Switch, createEffect, createMemo, onCleanup, type JSX } from "solid-js"
|
||||
import { For, Match, Show, Switch, createMemo, onCleanup, type JSX } from "solid-js"
|
||||
import { createStore } from "solid-js/store"
|
||||
import { createMediaQuery } from "@solid-primitives/media"
|
||||
import { DragDropProvider as DndKitProvider, PointerSensor } from "@dnd-kit/solid"
|
||||
@@ -38,23 +38,17 @@ const fileBrowserTabPanelID = "session-side-panel-file-browser-tabpanel"
|
||||
import { SessionContextTab, SortableTab, SortableTabV2, FileVisual } from "@/components/session"
|
||||
import { OpenInAppV2 } from "@/components/session/open-in-app-v2"
|
||||
import { useCommand } from "@/context/command"
|
||||
import { useFile, type SelectedLineRange } from "@/context/file"
|
||||
import { useFile } from "@/context/file"
|
||||
import { useLanguage } from "@/context/language"
|
||||
import { useLayout } from "@/context/layout"
|
||||
import { useSDK } from "@/context/sdk"
|
||||
import { useSettings } from "@/context/settings"
|
||||
import { createFileTabListSync } from "@/pages/session/file-tab-scroll"
|
||||
import { FileTabContent } from "@/pages/session/file-tabs"
|
||||
import {
|
||||
SESSION_OPEN_FILE_TAB,
|
||||
createOpenSessionFileTab,
|
||||
createSessionTabs,
|
||||
getTabReorderIndex,
|
||||
shouldShowFileTree,
|
||||
type Sizing,
|
||||
} from "@/pages/session/helpers"
|
||||
import { SESSION_OPEN_FILE_TAB, getTabReorderIndex, shouldShowFileTree, type Sizing } from "@/pages/session/helpers"
|
||||
import { setSessionHandoff } from "@/pages/session/handoff"
|
||||
import { useSessionLayout } from "@/pages/session/session-layout"
|
||||
import { createSessionSidePanelController } from "@/pages/session/session-side-panel-controller"
|
||||
import { SessionFileBrowserTab, type SessionFileBrowserState } from "@/pages/session/v2/session-file-browser-tab"
|
||||
|
||||
type ReviewDiff = FileDiffInfo | SnapshotFileDiff | VcsFileDiff
|
||||
@@ -153,91 +147,49 @@ export function SessionSidePanel(props: {
|
||||
return file.tree.children("").length === 0
|
||||
})
|
||||
|
||||
const normalizeTab = (tab: string) => {
|
||||
if (!tab.startsWith("file://")) return tab
|
||||
return file.tab(tab)
|
||||
}
|
||||
|
||||
const openReviewPanel = () => {
|
||||
if (!view().reviewPanel.opened()) view().reviewPanel.open()
|
||||
}
|
||||
|
||||
const openTab = createOpenSessionFileTab({
|
||||
normalizeTab,
|
||||
openTab: tabs().open,
|
||||
const controller = createSessionSidePanelController({
|
||||
currentTab: () => tabs().active(),
|
||||
allTabs: () => tabs().all(),
|
||||
openTab: (tab) => tabs().open(tab),
|
||||
preview: (tab) => tabs().previewTab(tab),
|
||||
setActive: (tab) => tabs().setActive(tab),
|
||||
normalizeFileTab: file.tab,
|
||||
pathFromTab: file.pathFromTab,
|
||||
loadFile: file.load,
|
||||
openReviewPanel,
|
||||
setActive: tabs().setActive,
|
||||
reviewEnabled: reviewTab,
|
||||
canReview: props.canReview,
|
||||
fileBrowserEnabled: () => !!props.fileBrowserState,
|
||||
reviewPanelOpened: () => view().reviewPanel.opened(),
|
||||
openReviewPanel: () => view().reviewPanel.open(),
|
||||
treeMode: () => layout.fileTree.tab(),
|
||||
setTreeMode: (mode) => layout.fileTree.setTab(mode),
|
||||
fileReady: file.ready,
|
||||
sessionKey,
|
||||
selectedLines: file.selectedLines,
|
||||
persistHandoff: (key, files) => setSessionHandoff(key, { files }),
|
||||
showDialog: (render) => void dialog.show(render),
|
||||
})
|
||||
|
||||
const tabState = createSessionTabs({
|
||||
tabs,
|
||||
pathFromTab: file.pathFromTab,
|
||||
normalizeTab,
|
||||
review: reviewTab,
|
||||
hasReview: props.canReview,
|
||||
fileBrowser: () => !!props.fileBrowserState,
|
||||
})
|
||||
const contextOpen = tabState.contextOpen
|
||||
const openFileOpen = tabState.openFileOpen
|
||||
const panelTabs = tabState.panelTabs
|
||||
const openedTabs = tabState.openedTabs
|
||||
const activeTab = tabState.activeTab
|
||||
const activeFileTab = tabState.activeFileTab
|
||||
|
||||
const fileTreeTab = () => layout.fileTree.tab()
|
||||
|
||||
const setFileTreeTabValue = (value: string) => {
|
||||
if (value !== "changes" && value !== "all") return
|
||||
layout.fileTree.setTab(value)
|
||||
}
|
||||
|
||||
const showAllFiles = () => {
|
||||
if (fileTreeTab() !== "changes") return
|
||||
layout.fileTree.setTab("all")
|
||||
}
|
||||
const contextOpen = controller.tabs.contextOpen
|
||||
const panelTabs = controller.tabs.panelTabs
|
||||
const openedTabs = controller.tabs.openedTabs
|
||||
const activeTab = controller.tabs.activeTab
|
||||
const activeFileTab = controller.tabs.activeFileTab
|
||||
const openTab = controller.tabs.open
|
||||
const previewTab = controller.tabs.preview
|
||||
const activateTab = controller.tabs.activate
|
||||
const browserTab = controller.browser.tab
|
||||
const fileBrowserMounted = controller.browser.mounted
|
||||
const fileBrowserVisible = controller.browser.visible
|
||||
const fileTreeTab = controller.tree.mode
|
||||
const setFileTreeTabValue = controller.tree.setMode
|
||||
|
||||
let fileFilter: HTMLInputElement | undefined
|
||||
let tabList: HTMLDivElement | undefined
|
||||
const temporaryTab = tabs().preview
|
||||
const previewTab = (value: string) => {
|
||||
const next = normalizeTab(value)
|
||||
tabs().previewTab(next)
|
||||
const path = file.pathFromTab(next)
|
||||
if (path) void file.load(path)
|
||||
openReviewPanel()
|
||||
queueMicrotask(() => tabs().setActive(next))
|
||||
}
|
||||
const openFileBrowser = () => {
|
||||
previewTab(SESSION_OPEN_FILE_TAB)
|
||||
controller.browser.open()
|
||||
queueMicrotask(() => fileFilter?.focus())
|
||||
}
|
||||
const activateTab = (value: string) => {
|
||||
const next = normalizeTab(value)
|
||||
const path = file.pathFromTab(next)
|
||||
if (path) void file.load(path)
|
||||
openReviewPanel()
|
||||
tabs().setActive(next)
|
||||
}
|
||||
const browserTab = createMemo(() => {
|
||||
if (!props.fileBrowserState) return undefined
|
||||
const active = activeTab()
|
||||
if (active === SESSION_OPEN_FILE_TAB) return SESSION_OPEN_FILE_TAB
|
||||
if (active && file.pathFromTab(active)) return active
|
||||
return activeFileTab()
|
||||
})
|
||||
// Keep the file-browser shell mounted while any file tab exists. Kobalte briefly
|
||||
// selects Review while the tab For replaces a preview trigger, which would
|
||||
// otherwise dispose the sidebar and reset scroll.
|
||||
const fileBrowserMounted = createMemo(() => {
|
||||
if (!props.fileBrowserState) return false
|
||||
return openedTabs().length > 0 || openFileOpen() || !!browserTab()
|
||||
})
|
||||
const fileBrowserVisible = createMemo(() => {
|
||||
const active = activeTab()
|
||||
return active !== "review" && active !== "context" && active !== "empty"
|
||||
})
|
||||
const openFileKeybind = createMemo(() => command.keybindParts("file.open"))
|
||||
const closeTabKeybind = createMemo(() => command.keybindParts("tab.close"))
|
||||
const [store, setStore] = createStore({
|
||||
@@ -264,27 +216,6 @@ export function SessionSidePanel(props: {
|
||||
setStore("activeDraggable", undefined)
|
||||
}
|
||||
|
||||
createEffect(() => {
|
||||
if (!file.ready()) return
|
||||
|
||||
setSessionHandoff(sessionKey(), {
|
||||
files: tabs()
|
||||
.all()
|
||||
.reduce<Record<string, SelectedLineRange | null>>((acc, tab) => {
|
||||
const path = file.pathFromTab(tab)
|
||||
if (!path) return acc
|
||||
|
||||
const selected = file.selectedLines(path)
|
||||
acc[path] =
|
||||
selected && typeof selected === "object" && "start" in selected && "end" in selected
|
||||
? (selected as SelectedLineRange)
|
||||
: null
|
||||
|
||||
return acc
|
||||
}, {}),
|
||||
})
|
||||
})
|
||||
|
||||
return (
|
||||
<Show when={isDesktop() && !(settings.general.newLayoutDesigns() && !params.id)}>
|
||||
<aside
|
||||
@@ -451,9 +382,7 @@ export function SessionSidePanel(props: {
|
||||
iconSize="large"
|
||||
class="!rounded-md"
|
||||
onClick={() => {
|
||||
void import("@/components/dialog-select-file").then((x) => {
|
||||
dialog.show(() => <x.DialogSelectFile mode="files" onOpenFile={showAllFiles} />)
|
||||
})
|
||||
void controller.dialog.openFile()
|
||||
}}
|
||||
aria-label={language.t("command.file.open")}
|
||||
/>
|
||||
|
||||
@@ -1,79 +0,0 @@
|
||||
export * as BrowserControlProtocol from "./browser-control.js"
|
||||
|
||||
import { BrowserControl } from "@opencode-ai/schema/browser-control"
|
||||
import { Effect, Schema } from "effect"
|
||||
|
||||
export const Path = "/api/browser/control"
|
||||
export const Subprotocol = "opencode.browser.control.v1"
|
||||
export const MaxMessageBytes = 8 * 1_024 * 1_024
|
||||
|
||||
class MessageError extends Schema.TaggedErrorClass<MessageError>()("BrowserControlProtocol.MessageError", {
|
||||
kind: Schema.Literals(["invalid", "too_large"]),
|
||||
message: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
}) {}
|
||||
|
||||
const decoder = new TextDecoder("utf-8", { fatal: true })
|
||||
const encoder = new TextEncoder()
|
||||
const encodeClient = Schema.encodeSync(Schema.fromJsonString(BrowserControl.FromClient))
|
||||
const encodeServer = Schema.encodeSync(Schema.fromJsonString(BrowserControl.FromServer))
|
||||
const decodeClient = Schema.decodeUnknownEffect(Schema.fromJsonString(BrowserControl.FromClient), {
|
||||
errors: "all",
|
||||
onExcessProperty: "error",
|
||||
})
|
||||
const decodeServer = Schema.decodeUnknownEffect(Schema.fromJsonString(BrowserControl.FromServer), {
|
||||
errors: "all",
|
||||
onExcessProperty: "error",
|
||||
})
|
||||
|
||||
export function encodeFromClient(input: BrowserControl.FromClient) {
|
||||
return encode(input, encodeClient)
|
||||
}
|
||||
|
||||
export function encodeFromServer(input: BrowserControl.FromServer) {
|
||||
return encode(input, encodeServer)
|
||||
}
|
||||
|
||||
function encode<Message>(input: Message, encodeMessage: (input: Message) => string) {
|
||||
const output = encodeMessage(input)
|
||||
if (encoder.encode(output).byteLength > MaxMessageBytes) {
|
||||
throw new RangeError(`Browser control message must not exceed ${MaxMessageBytes} bytes.`)
|
||||
}
|
||||
return output
|
||||
}
|
||||
|
||||
export function decodeFromClient(input: string | Uint8Array) {
|
||||
return decode(input, decodeClient)
|
||||
}
|
||||
|
||||
export function decodeFromServer(input: string | Uint8Array) {
|
||||
return decode(input, decodeServer)
|
||||
}
|
||||
|
||||
function decode<Message>(
|
||||
input: string | Uint8Array,
|
||||
decodeMessage: (input: unknown) => Effect.Effect<Message, unknown>,
|
||||
): Effect.Effect<Message, MessageError> {
|
||||
if (typeof input === "string" && encoder.encode(input).byteLength > MaxMessageBytes) {
|
||||
return Effect.fail(new MessageError({ kind: "too_large", message: "Browser control message is too large." }))
|
||||
}
|
||||
if (typeof input !== "string" && input.byteLength > MaxMessageBytes) {
|
||||
return Effect.fail(new MessageError({ kind: "too_large", message: "Browser control message is too large." }))
|
||||
}
|
||||
const text =
|
||||
typeof input === "string"
|
||||
? Effect.succeed(input)
|
||||
: Effect.try({
|
||||
try: () => decoder.decode(input),
|
||||
catch: (cause) =>
|
||||
new MessageError({ kind: "invalid", message: "Browser control message is not valid UTF-8.", cause }),
|
||||
})
|
||||
return text.pipe(
|
||||
Effect.flatMap(decodeMessage),
|
||||
Effect.mapError((cause) =>
|
||||
cause instanceof MessageError
|
||||
? cause
|
||||
: new MessageError({ kind: "invalid", message: "Browser control message is invalid.", cause }),
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
export * as BrowserTunnelProtocol from "./browser-tunnel.js"
|
||||
|
||||
import { BrowserTunnel } from "@opencode-ai/schema/browser-tunnel"
|
||||
import { Effect, Schema } from "effect"
|
||||
|
||||
export const Path = "/api/browser/tunnel"
|
||||
export const Subprotocol = "opencode.browser.tunnel.v1"
|
||||
export const MaxFrameBytes = 64 * 1_024
|
||||
export const MaxHandshakeBytes = 16 * 1_024
|
||||
|
||||
class MessageError extends Schema.TaggedErrorClass<MessageError>()("BrowserTunnelProtocol.MessageError", {
|
||||
kind: Schema.Literals(["invalid", "too_large"]),
|
||||
message: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
}) {}
|
||||
|
||||
const encoder = new TextEncoder()
|
||||
const decoder = new TextDecoder("utf-8", { fatal: true })
|
||||
const encodeClient = Schema.encodeSync(Schema.fromJsonString(BrowserTunnel.FromClient))
|
||||
const encodeServer = Schema.encodeSync(Schema.fromJsonString(BrowserTunnel.FromServer))
|
||||
const decodeClient = Schema.decodeUnknownEffect(Schema.fromJsonString(BrowserTunnel.FromClient), {
|
||||
errors: "all",
|
||||
onExcessProperty: "error",
|
||||
})
|
||||
const decodeServer = Schema.decodeUnknownEffect(Schema.fromJsonString(BrowserTunnel.FromServer), {
|
||||
errors: "all",
|
||||
onExcessProperty: "error",
|
||||
})
|
||||
|
||||
export function encodeFromClient(input: BrowserTunnel.FromClient) {
|
||||
return encode(encodeClient(input))
|
||||
}
|
||||
|
||||
export function encodeFromServer(input: BrowserTunnel.FromServer) {
|
||||
return encode(encodeServer(input))
|
||||
}
|
||||
|
||||
function encode(input: string) {
|
||||
if (encoder.encode(input).byteLength > MaxHandshakeBytes) {
|
||||
throw new RangeError(`Browser tunnel handshake must not exceed ${MaxHandshakeBytes} bytes.`)
|
||||
}
|
||||
return input
|
||||
}
|
||||
|
||||
export function decodeFromClient(input: string | Uint8Array) {
|
||||
return decode(input, decodeClient)
|
||||
}
|
||||
|
||||
export function decodeFromServer(input: string | Uint8Array) {
|
||||
return decode(input, decodeServer)
|
||||
}
|
||||
|
||||
function decode<Message>(
|
||||
input: string | Uint8Array,
|
||||
decodeMessage: (input: unknown) => Effect.Effect<Message, unknown>,
|
||||
): Effect.Effect<Message, MessageError> {
|
||||
if ((typeof input === "string" ? encoder.encode(input).byteLength : input.byteLength) > MaxHandshakeBytes) {
|
||||
return Effect.fail(new MessageError({ kind: "too_large", message: "Browser tunnel handshake is too large." }))
|
||||
}
|
||||
const text =
|
||||
typeof input === "string"
|
||||
? Effect.succeed(input)
|
||||
: Effect.try({
|
||||
try: () => decoder.decode(input),
|
||||
catch: (cause) => new MessageError({ kind: "invalid", message: "Invalid tunnel handshake UTF-8.", cause }),
|
||||
})
|
||||
return text.pipe(
|
||||
Effect.flatMap(decodeMessage),
|
||||
Effect.mapError((cause) =>
|
||||
cause instanceof MessageError
|
||||
? cause
|
||||
: new MessageError({ kind: "invalid", message: "Browser tunnel handshake is invalid.", cause }),
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
import { Schema } from "effect"
|
||||
import { HttpApiEndpoint, HttpApiGroup, OpenApi } from "effect/unstable/httpapi"
|
||||
import { ConflictError, ServiceUnavailableError } from "../errors.js"
|
||||
import { BrowserControlProtocol } from "../browser-control.js"
|
||||
import { BrowserTunnelProtocol } from "../browser-tunnel.js"
|
||||
import { HeaderOnlyAuthorization } from "../middleware/authorization.js"
|
||||
|
||||
const websocket = (identifier: string, summary: string, description: string, subprotocol: string) =>
|
||||
OpenApi.annotations({
|
||||
identifier,
|
||||
summary,
|
||||
description,
|
||||
transform: (operation) => ({
|
||||
...operation,
|
||||
"x-websocket": true,
|
||||
"x-websocket-subprotocol": subprotocol,
|
||||
responses: {
|
||||
...operation.responses,
|
||||
403: { description: "WebSocket Origin is not allowed." },
|
||||
426: { description: `WebSocket subprotocol ${subprotocol} is required.` },
|
||||
},
|
||||
}),
|
||||
})
|
||||
|
||||
export const BrowserGroup = HttpApiGroup.make("server.browser")
|
||||
.add(
|
||||
HttpApiEndpoint.get("browser.control.connect", BrowserControlProtocol.Path, {
|
||||
success: Schema.Boolean,
|
||||
error: ConflictError,
|
||||
})
|
||||
.annotate(HeaderOnlyAuthorization, true)
|
||||
.annotate(OpenApi.Exclude, true)
|
||||
.annotateMerge(
|
||||
websocket(
|
||||
"v2.browser.control.connect",
|
||||
"Connect Session browser host",
|
||||
"Establish an authenticated WebSocket controlling the browser attachment for one Session.",
|
||||
BrowserControlProtocol.Subprotocol,
|
||||
),
|
||||
),
|
||||
)
|
||||
.add(
|
||||
HttpApiEndpoint.get("browser.tunnel.connect", BrowserTunnelProtocol.Path, {
|
||||
success: Schema.Boolean,
|
||||
error: ServiceUnavailableError,
|
||||
})
|
||||
.annotate(HeaderOnlyAuthorization, true)
|
||||
.annotate(OpenApi.Exclude, true)
|
||||
.annotateMerge(
|
||||
websocket(
|
||||
"v2.browser.tunnel.connect",
|
||||
"Open browser network tunnel",
|
||||
"Establish an authenticated WebSocket carrying one TCP stream dialed from the OpenCode server.",
|
||||
BrowserTunnelProtocol.Subprotocol,
|
||||
),
|
||||
),
|
||||
)
|
||||
.annotateMerge(
|
||||
OpenApi.annotations({
|
||||
title: "browser",
|
||||
description: "Desktop browser host control and server-network tunnel routes.",
|
||||
}),
|
||||
)
|
||||
@@ -1,11 +1,6 @@
|
||||
import { Context } from "effect"
|
||||
import { HttpApiMiddleware } from "effect/unstable/httpapi"
|
||||
import { UnauthorizedError } from "../errors.js"
|
||||
|
||||
export const HeaderOnlyAuthorization = Context.Reference<boolean>("@opencode/HttpApiAuthorization/HeaderOnly", {
|
||||
defaultValue: () => false,
|
||||
})
|
||||
|
||||
export class Authorization extends HttpApiMiddleware.Service<Authorization>()("@opencode/HttpApiAuthorization", {
|
||||
error: UnauthorizedError,
|
||||
}) {}
|
||||
|
||||
@@ -1,78 +0,0 @@
|
||||
export * as BrowserControl from "./browser-control.js"
|
||||
|
||||
import { Schema } from "effect"
|
||||
import { Browser } from "./browser.js"
|
||||
import { ascending } from "./identifier.js"
|
||||
import { SessionID } from "./session-id.js"
|
||||
import { statics } from "./schema.js"
|
||||
|
||||
const RequestIDSchema = Schema.String.check(Schema.isPattern(/^brr_[0-9A-Za-z]+$/))
|
||||
.pipe(Schema.brand("BrowserControl.RequestID"))
|
||||
.annotate({ identifier: "BrowserControl.RequestID" })
|
||||
|
||||
export const RequestID = RequestIDSchema.pipe(
|
||||
statics((schema: typeof RequestIDSchema) => ({
|
||||
create: () => schema.make("brr_" + ascending()),
|
||||
})),
|
||||
)
|
||||
export type RequestID = typeof RequestID.Type
|
||||
|
||||
const Register = Schema.Struct({
|
||||
type: Schema.Literal("browser.control.register"),
|
||||
sessionID: SessionID,
|
||||
})
|
||||
|
||||
const Attach = Schema.Struct({
|
||||
type: Schema.Literal("browser.control.attach"),
|
||||
leaseID: Browser.LeaseID,
|
||||
state: Browser.State,
|
||||
})
|
||||
|
||||
const State = Schema.Struct({
|
||||
type: Schema.Literal("browser.control.state"),
|
||||
leaseID: Browser.LeaseID,
|
||||
state: Browser.State,
|
||||
})
|
||||
|
||||
const Detach = Schema.Struct({
|
||||
type: Schema.Literal("browser.control.detach"),
|
||||
leaseID: Browser.LeaseID,
|
||||
})
|
||||
|
||||
const Response = Schema.Struct({
|
||||
type: Schema.Literal("browser.control.response"),
|
||||
requestID: RequestID,
|
||||
leaseID: Browser.LeaseID,
|
||||
outcome: Browser.Outcome,
|
||||
})
|
||||
|
||||
const Registered = Schema.Struct({ type: Schema.Literal("browser.control.registered") })
|
||||
const Open = Schema.Struct({ type: Schema.Literal("browser.control.open") })
|
||||
|
||||
const Attached = Schema.Struct({
|
||||
type: Schema.Literal("browser.control.attached"),
|
||||
leaseID: Browser.LeaseID,
|
||||
})
|
||||
|
||||
const Request = Schema.Struct({
|
||||
type: Schema.Literal("browser.control.request"),
|
||||
requestID: RequestID,
|
||||
leaseID: Browser.LeaseID,
|
||||
command: Browser.Command,
|
||||
})
|
||||
|
||||
const Cancel = Schema.Struct({
|
||||
type: Schema.Literal("browser.control.cancel"),
|
||||
requestID: RequestID,
|
||||
leaseID: Browser.LeaseID,
|
||||
})
|
||||
|
||||
export const FromClient = Schema.Union([Register, Attach, State, Detach, Response])
|
||||
.pipe(Schema.toTaggedUnion("type"))
|
||||
.annotate({ identifier: "BrowserControl.FromClient" })
|
||||
export type FromClient = typeof FromClient.Type
|
||||
|
||||
export const FromServer = Schema.Union([Registered, Open, Attached, Request, Cancel])
|
||||
.pipe(Schema.toTaggedUnion("type"))
|
||||
.annotate({ identifier: "BrowserControl.FromServer" })
|
||||
export type FromServer = typeof FromServer.Type
|
||||
@@ -1,55 +0,0 @@
|
||||
export * as BrowserTunnel from "./browser-tunnel.js"
|
||||
|
||||
import { Schema } from "effect"
|
||||
import { Browser } from "./browser.js"
|
||||
import { SessionID } from "./session-id.js"
|
||||
|
||||
export const Host = Schema.NonEmptyString.check(Schema.isMaxLength(253), Schema.isPattern(/^[^\s/?#]+$/))
|
||||
.pipe(Schema.brand("BrowserTunnel.Host"))
|
||||
.annotate({ identifier: "BrowserTunnel.Host" })
|
||||
export type Host = typeof Host.Type
|
||||
|
||||
export const Port = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65_535 }))
|
||||
.pipe(Schema.brand("BrowserTunnel.Port"))
|
||||
.annotate({ identifier: "BrowserTunnel.Port" })
|
||||
export type Port = typeof Port.Type
|
||||
|
||||
export interface Target extends Schema.Schema.Type<typeof Target> {}
|
||||
export const Target = Schema.Struct({
|
||||
host: Host,
|
||||
port: Port,
|
||||
}).annotate({ identifier: "BrowserTunnel.Target" })
|
||||
|
||||
const Open = Schema.Struct({
|
||||
type: Schema.Literal("browser.tunnel.open"),
|
||||
sessionID: SessionID,
|
||||
leaseID: Browser.LeaseID,
|
||||
target: Target,
|
||||
}).annotate({ identifier: "BrowserTunnel.Open" })
|
||||
|
||||
const Opened = Schema.Struct({
|
||||
type: Schema.Literal("browser.tunnel.opened"),
|
||||
}).annotate({ identifier: "BrowserTunnel.Opened" })
|
||||
|
||||
export const OpenErrorCode = Schema.Literals([
|
||||
"invalid_open",
|
||||
"not_attached",
|
||||
"stale_lease",
|
||||
"connect_failed",
|
||||
"connect_timeout",
|
||||
]).annotate({ identifier: "BrowserTunnel.OpenErrorCode" })
|
||||
export type OpenErrorCode = typeof OpenErrorCode.Type
|
||||
|
||||
const Rejected = Schema.Struct({
|
||||
type: Schema.Literal("browser.tunnel.rejected"),
|
||||
code: OpenErrorCode,
|
||||
message: Schema.String.check(Schema.isMaxLength(1_024)),
|
||||
}).annotate({ identifier: "BrowserTunnel.Rejected" })
|
||||
|
||||
export const FromClient = Open.annotate({ identifier: "BrowserTunnel.FromClient" })
|
||||
export type FromClient = typeof FromClient.Type
|
||||
|
||||
export const FromServer = Schema.Union([Opened, Rejected])
|
||||
.pipe(Schema.toTaggedUnion("type"))
|
||||
.annotate({ identifier: "BrowserTunnel.FromServer" })
|
||||
export type FromServer = typeof FromServer.Type
|
||||
@@ -1,163 +0,0 @@
|
||||
export * as Browser from "./browser.js"
|
||||
|
||||
import { Schema } from "effect"
|
||||
import { ascending } from "./identifier.js"
|
||||
import { NonNegativeInt, PositiveInt, statics } from "./schema.js"
|
||||
|
||||
const LeaseIDSchema = Schema.String.check(Schema.isPattern(/^brl_[0-9A-Za-z]+$/))
|
||||
.pipe(Schema.brand("Browser.LeaseID"))
|
||||
.annotate({ identifier: "Browser.LeaseID" })
|
||||
|
||||
export const LeaseID = LeaseIDSchema.pipe(
|
||||
statics((schema: typeof LeaseIDSchema) => ({
|
||||
create: () => schema.make("brl_" + ascending()),
|
||||
})),
|
||||
)
|
||||
export type LeaseID = typeof LeaseID.Type
|
||||
|
||||
export const Ref = Schema.String.check(Schema.isPattern(/^e[1-9][0-9]*$/))
|
||||
.pipe(Schema.brand("Browser.Ref"))
|
||||
.annotate({ identifier: "Browser.Ref" })
|
||||
export type Ref = typeof Ref.Type
|
||||
|
||||
export interface State extends Schema.Schema.Type<typeof State> {}
|
||||
export const State = Schema.Struct({
|
||||
url: Schema.String.check(Schema.isMaxLength(16_384)),
|
||||
title: Schema.String.check(Schema.isMaxLength(1_024)),
|
||||
loading: Schema.Boolean,
|
||||
canGoBack: Schema.Boolean,
|
||||
canGoForward: Schema.Boolean,
|
||||
generation: NonNegativeInt,
|
||||
}).annotate({ identifier: "Browser.State" })
|
||||
|
||||
export const Key = Schema.Literals([
|
||||
"Enter",
|
||||
"Tab",
|
||||
"Escape",
|
||||
"Backspace",
|
||||
"Delete",
|
||||
"ArrowUp",
|
||||
"ArrowDown",
|
||||
"ArrowLeft",
|
||||
"ArrowRight",
|
||||
"PageUp",
|
||||
"PageDown",
|
||||
"Home",
|
||||
"End",
|
||||
"Space",
|
||||
]).annotate({ identifier: "Browser.Key" })
|
||||
export type Key = typeof Key.Type
|
||||
|
||||
export const Direction = Schema.Literals(["up", "down", "left", "right"]).annotate({
|
||||
identifier: "Browser.Direction",
|
||||
})
|
||||
export type Direction = typeof Direction.Type
|
||||
|
||||
const generation = { generation: NonNegativeInt }
|
||||
|
||||
export const Command = Schema.Union([
|
||||
Schema.Struct({
|
||||
type: Schema.Literal("navigate"),
|
||||
url: Schema.String.check(Schema.isMaxLength(16_384)),
|
||||
...generation,
|
||||
}),
|
||||
Schema.Struct({ type: Schema.Literal("snapshot"), ...generation }),
|
||||
Schema.Struct({ type: Schema.Literal("click"), ref: Ref, ...generation }),
|
||||
Schema.Struct({
|
||||
type: Schema.Literal("fill"),
|
||||
ref: Ref,
|
||||
text: Schema.String.check(Schema.isMaxLength(10_000)),
|
||||
...generation,
|
||||
}),
|
||||
Schema.Struct({ type: Schema.Literal("press"), key: Key, ...generation }),
|
||||
Schema.Struct({ type: Schema.Literal("scroll"), direction: Direction, pixels: PositiveInt, ...generation }),
|
||||
Schema.Struct({ type: Schema.Literal("screenshot"), ...generation }),
|
||||
])
|
||||
.pipe(Schema.toTaggedUnion("type"))
|
||||
.annotate({ identifier: "Browser.Command" })
|
||||
export type Command = typeof Command.Type
|
||||
|
||||
const NavigateResult = Schema.Struct({
|
||||
type: Schema.Literal("navigate"),
|
||||
state: State,
|
||||
}).annotate({ identifier: "Browser.NavigateResult" })
|
||||
|
||||
const SnapshotResult = Schema.Struct({
|
||||
type: Schema.Literal("snapshot"),
|
||||
state: State,
|
||||
format: Schema.Literal("opencode.semantic.v1"),
|
||||
content: Schema.String.check(Schema.isMaxLength(100_000)),
|
||||
}).annotate({ identifier: "Browser.SnapshotResult" })
|
||||
|
||||
const ClickResult = Schema.Struct({
|
||||
type: Schema.Literal("click"),
|
||||
state: State,
|
||||
}).annotate({ identifier: "Browser.ClickResult" })
|
||||
|
||||
const FillResult = Schema.Struct({
|
||||
type: Schema.Literal("fill"),
|
||||
state: State,
|
||||
}).annotate({ identifier: "Browser.FillResult" })
|
||||
|
||||
const PressResult = Schema.Struct({
|
||||
type: Schema.Literal("press"),
|
||||
state: State,
|
||||
}).annotate({ identifier: "Browser.PressResult" })
|
||||
|
||||
const ScrollResult = Schema.Struct({
|
||||
type: Schema.Literal("scroll"),
|
||||
state: State,
|
||||
}).annotate({ identifier: "Browser.ScrollResult" })
|
||||
|
||||
const ScreenshotResult = Schema.Struct({
|
||||
type: Schema.Literal("screenshot"),
|
||||
state: State,
|
||||
mediaType: Schema.Literal("image/png"),
|
||||
data: Schema.Uint8ArrayFromBase64.check(Schema.isMaxLength(5 * 1_024 * 1_024)),
|
||||
width: PositiveInt,
|
||||
height: PositiveInt,
|
||||
}).annotate({ identifier: "Browser.ScreenshotResult" })
|
||||
|
||||
export const Result = Schema.Union([
|
||||
NavigateResult,
|
||||
SnapshotResult,
|
||||
ClickResult,
|
||||
FillResult,
|
||||
PressResult,
|
||||
ScrollResult,
|
||||
ScreenshotResult,
|
||||
])
|
||||
.pipe(Schema.toTaggedUnion("type"))
|
||||
.annotate({ identifier: "Browser.Result" })
|
||||
export type Result = typeof Result.Type
|
||||
|
||||
export const ErrorCode = Schema.Literals([
|
||||
"not_attached",
|
||||
"stale_ref",
|
||||
"invalid_url",
|
||||
"navigation_failed",
|
||||
"timeout",
|
||||
"aborted",
|
||||
"page_crashed",
|
||||
"result_too_large",
|
||||
"overloaded",
|
||||
"protocol",
|
||||
"internal",
|
||||
]).annotate({ identifier: "Browser.ErrorCode" })
|
||||
export type ErrorCode = typeof ErrorCode.Type
|
||||
|
||||
const Failure = Schema.Struct({
|
||||
type: Schema.Literal("failure"),
|
||||
code: ErrorCode,
|
||||
message: Schema.String.check(Schema.isMaxLength(1_024)),
|
||||
}).annotate({ identifier: "Browser.Failure" })
|
||||
|
||||
const Success = Schema.Struct({
|
||||
type: Schema.Literal("success"),
|
||||
result: Result,
|
||||
}).annotate({ identifier: "Browser.Success" })
|
||||
|
||||
export const Outcome = Schema.Union([Success, Failure])
|
||||
.pipe(Schema.toTaggedUnion("type"))
|
||||
.annotate({ identifier: "Browser.Outcome" })
|
||||
export type Outcome = typeof Outcome.Type
|
||||
@@ -1,5 +1,4 @@
|
||||
export { Agent } from "./agent.js"
|
||||
export { Browser } from "./browser.js"
|
||||
export { Command } from "./command.js"
|
||||
export { Config } from "./config.js"
|
||||
export { Connection } from "./connection.js"
|
||||
|
||||
Reference in New Issue
Block a user