Merge remote-tracking branch 'origin/dev' into persisted-browser

command.tsx: dev dispatches command keys through @opentui/keymap (#64394) instead of the window keydown handler. The page prompt's keyboard ownership moves into the keymap's block check, which now gets the key's event: a key inside a surface registered with ownKeyboard runs no command, and keymap.test.ts pins it.
This commit is contained in:
Luke Parker 2026-11-18 15:18:49 +10:00
commit ea13b16ef7
34 changed files with 1056 additions and 474 deletions

View file

@ -66,6 +66,7 @@
"@opencode/session-ui": "workspace:*",
"@opencode/ui": "workspace:*",
"@opencode/util": "workspace:*",
"@opentui/keymap": "catalog:",
"@pierre/highlights": "catalog:",
"@pierre/trees": "1.0.0-beta.6",
"@sentry/solid": "catalog:",

View file

@ -216,7 +216,8 @@ story(
await input.fill("")
await input.press("ArrowUp")
await expect(input).toHaveText("Explain the latest changes")
await input.press("ControlOrMeta+u")
await component.getByRole("button", { name: "Add images and files", exact: true }).click()
await page.getByRole("menuitem", { name: /^Images and files/ }).click()
await input.press("ArrowDown")
await expect(input).toBeEmpty()
},

View file

@ -68,6 +68,7 @@
"@opencode/session-ui": "workspace:*",
"@opencode/ui": "workspace:*",
"@opencode/util": "workspace:*",
"@opentui/keymap": "catalog:",
"@pierre/highlights": "catalog:",
"@pierre/trees": "1.0.0-beta.6",
"@sentry/solid": "catalog:",

View file

@ -474,19 +474,6 @@ export function createComposerEditor(input: {
flushFocus()
if (
mode() === "normal" &&
(event.metaKey || event.ctrlKey) &&
!event.altKey &&
!event.shiftKey &&
event.key.toLowerCase() === "u"
) {
event.preventDefault()
attach()
return true
}
const ctrl = event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey
const open = isComposerPopoverOpen(readState())
@ -537,18 +524,6 @@ export function createComposerEditor(input: {
return true
}
const stop =
(input.view.submit.working?.() || input.view.submit.held?.()) &&
((event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey && event.key.toLowerCase() === "g") ||
event.key === "Escape")
if (stop) {
event.preventDefault()
input.view.submit.onStop()
return true
}
if (
!event.altKey &&
!event.ctrlKey &&

View file

@ -2,7 +2,7 @@ import { ImagePreview } from "@opencode/ui/image-preview"
import { useDialog } from "@opencode/ui/context/dialog"
import type { ReferenceInfo } from "@opencode/client/promise"
import type { Links, MountedSession } from "@opencode/plugin/gui"
import { createComponent, createEffect, createMemo, on, onCleanup } from "solid-js"
import { createComponent, createEffect, createMemo, createSignal, on, onCleanup } from "solid-js"
import { Predicate } from "effect"
import type { ComposerSuggestion } from "./types"
import { createComposerEditor, type ComposerEditorModel } from "./editor/interaction"
@ -33,6 +33,7 @@ import type { PromptHistoryComment } from "./history/entry"
import { createComposerHistory } from "./history/store"
import { createComposerSubmit } from "./submit"
import { composerSubmitView } from "./machine"
import { isComposerPopoverOpen } from "./suggestions/machine"
import { useAttachmentDestination } from "./attachments/destination"
import { parseClientSlashCommand } from "./client-slash-command"
@ -73,6 +74,8 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue?
),
)
let editor: HTMLDivElement | undefined
// The element `prompt.stop` binds its keys to.
const [editorElement, setEditorElement] = createSignal<HTMLDivElement>()
// A path attachment's image is read through the server, which can see both local and uploaded paths.
const pathImages = new Map<string, Promise<string | undefined>>()
const pathImageReads = new AbortController()
@ -458,6 +461,7 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue?
onEditor(element) {
// SAFETY: the editor's only `setEditor` call passes its editable root, a `<div>` (`editor/editor.tsx`).
editor = element as HTMLDivElement
setEditorElement(editor)
if (adapter.kind === "active-session") adapter.setEditor(editor)
},
@ -608,6 +612,20 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue?
disabled: mode() === "normal",
onSelect: () => void controller.dispatch({ type: "mode.normal" }),
},
{
id: "prompt.stop",
title: language.t("command.prompt.stop"),
category: language.t("command.category.session"),
keybind: "escape,ctrl+g",
editable: true,
target: editorElement,
disabled: !adapter.working() && !submitView().held,
// An open list, a queued prompt being edited and shell mode each take the key first in the editor.
skip: (event) =>
isComposerPopoverOpen(controller.state) ||
(event.key === "Escape" && (!!options?.queue?.editing() || mode() === "shell")),
onSelect: () => void submission.stop(),
},
])
// SAFETY: the `model` getter defined on the controller above completes `ComposerModel`.

View file

@ -105,6 +105,7 @@ export const dict = {
"command.prompt.mode.shell": "Shell",
"command.prompt.mode.normal": "Prompt",
"command.prompt.mode.toggle": "Toggle shell mode",
"command.prompt.stop": "Stop session",
"command.permissions.autoaccept.enable": "Auto-accept permissions",
"command.permissions.autoaccept.disable": "Stop auto-accepting permissions",
"command.permissions.autoaccept.project": "Auto-accept permissions for this project",

View file

@ -5,11 +5,9 @@ import {
addCommandRegistration,
commandPaletteOptions,
CommandCatalog,
commandKeymap,
formatKeybind,
matchKeybind,
parseKeybind,
resolveKeybindOption,
type CommandOption,
} from "./command"
@ -62,35 +60,6 @@ test("command registrations shadow keyed owners, restore the previous owner, and
expect(unkeyed.map((entry) => entry.options)).toEqual([two, one])
})
test.each([true, false])("resolveKeybindOption prefers a contextual command only in its context: %p", (inside) => {
const fallback = { id: "tab.close", title: "Close tab" }
const contextual = { id: "terminal.close", title: "Close terminal", when: () => inside }
expect(resolveKeybindOption([fallback, contextual], new KeyboardEvent("keydown"))).toBe(
inside ? contextual : fallback,
)
})
test("commandKeymap puts a user's binding before a default on the same keys", () => {
const rename = { id: "session.rename", title: "Rename session", keybind: "ctrl+r" }
const focus = { id: "input.focus", title: "Focus input", keybind: "ctrl+r" }
const event = new KeyboardEvent("keydown", { key: "r", ctrlKey: true })
const keymap = (custom: string[]) => commandKeymap([rename, focus], (id) => custom.includes(id)).get("r:1")
expect(resolveKeybindOption(keymap([]), event)).toBe(rename)
expect(resolveKeybindOption(keymap(["input.focus"]), event)).toBe(focus)
expect(commandKeymap([{ ...rename, disabled: true }], () => false).size).toBe(0)
})
test.each([true, false])("resolveKeybindOption leaves the key to a skipping command's target: %p", (inside) => {
const rename = { id: "session.rename", title: "Rename session", skip: () => inside }
const focus = { id: "input.focus", title: "Focus input" }
const event = new KeyboardEvent("keydown")
expect(resolveKeybindOption([rename], event)).toBe(inside ? undefined : rename)
expect(resolveKeybindOption([rename, focus], event)).toBe(inside ? focus : rename)
})
describe("command keybinds", () => {
test("parseKeybind handles aliases, multiple combos, and disabled bindings", () => {
const keybinds = parseKeybind("control+option+k, mod+shift+comma")

View file

@ -5,15 +5,15 @@ import { type Accessor, batch, createEffect, createMemo, createSignal, onCleanup
import { createStore, produce, reconcile } from "solid-js/store"
import { Predicate, Schema } from "effect"
import { Persistence } from "@/runtime/persistence/schema"
import { makeEventListener } from "@solid-primitives/event-listener"
import { useLanguage } from "@/runtime/i18n/language"
import { useSettings } from "@/settings/model"
import { keybindRenames } from "@/settings/keybinds/migration"
import en from "@/runtime/i18n/en"
import { Persist, persisted } from "@/runtime/persistence/storage"
import { INITIAL_KEYBIND_SUSPEND_STATE, selectKeybindsSuspended, transitionKeybindSuspend } from "./suspend-machine"
import { createAppKeymap, IS_MAC, keyFromKeyboardEvent, registerCommandLayers } from "./keymap"
const IS_MAC = typeof navigator !== "undefined" && /(Mac|iPod|iPhone|iPad)/.test(navigator.platform)
export { keyFromKeyboardEvent }
const PALETTE_ID = "command.palette"
@ -51,51 +51,6 @@ function actionId(id: string) {
return id.slice(SUGGESTED_PREFIX.length)
}
function normalizeKey(key: string) {
if (key === ",") return "comma"
if (key === "+") return "plus"
if (key === " ") return "space"
return key.toLowerCase()
}
export function keyFromKeyboardEvent(event: KeyboardEvent) {
const key = normalizeKey(physicalKey(event))
if (!event.altKey || /^[a-z0-9]$/.test(key)) return key
if (!event.code.startsWith("Key") || event.code.length !== 4) return key
return event.code.slice(3).toLowerCase()
}
// ⇧[ types { and ⌥. types ≥ on US layouts. Keep ASCII layout mappings; non-ASCII falls back to the physical key.
function physicalKey(event: Pick<KeyboardEvent, "key" | "code">) {
if (event.key === "{" || event.key === "}") return event.key === "{" ? "[" : "]"
if (!/^[^\x00-\x7f]$/u.test(event.key)) return event.key
if (event.code === "BracketLeft") return "["
if (event.code === "BracketRight") return "]"
if (event.code === "Period") return "."
return event.key
}
function signature(key: string, ctrl: boolean, meta: boolean, shift: boolean, alt: boolean) {
const mask = (ctrl ? 1 : 0) | (meta ? 2 : 0) | (shift ? 4 : 0) | (alt ? 8 : 0)
return `${key}:${mask}`
}
function signatureFromEvent(event: KeyboardEvent) {
return signature(keyFromKeyboardEvent(event), event.ctrlKey, event.metaKey, event.shiftKey, event.altKey)
}
type KeybindConfig = string
export interface Keybind {
@ -135,6 +90,8 @@ export interface CommandOption {
hidden?: boolean
/** The keybind also fires while a text field has focus. */
editable?: boolean
/** The keybind fires only while focus is inside this element, ahead of keybinds without one. */
target?: () => HTMLElement | undefined
when?: (event: KeyboardEvent) => boolean
/** The keybind leaves this event to its target, as if the command had no keybind. */
skip?: (event: KeyboardEvent) => boolean
@ -150,37 +107,6 @@ export function commandPaletteOptions(options: CommandOption[]) {
)
}
/** Maps each keybind signature to its commands. A user's own binding comes before a default on the same keys. */
export function commandKeymap(options: CommandOption[], custom: (id: string) => boolean) {
const map = new Map<string, CommandOption[]>()
for (const option of options) {
if (option.id.startsWith(SUGGESTED_PREFIX)) continue
if (option.disabled) continue
if (!option.keybind) continue
const keybinds = parseKeybind(option.keybind)
for (const kb of keybinds) {
if (!kb.key) continue
const sig = signature(kb.key, kb.ctrl, kb.meta, kb.shift, kb.alt)
const existing = map.get(sig) ?? []
map.set(sig, custom(actionId(option.id)) ? [option, ...existing] : [...existing, option])
}
}
return map
}
export function resolveKeybindOption(candidates: CommandOption[] | undefined, event: KeyboardEvent) {
const live = candidates?.filter((option) => !option.skip?.(event))
return live?.find((option) => option.when?.(event)) ?? live?.find((option) => !option.when)
}
export type CommandSource = "palette" | "keybind" | "slash"
const CommandCatalogItem = Persistence.struct({
@ -399,8 +325,9 @@ export const { use: useCommand, provider: CommandProvider } = createSimpleContex
const [catalog, setCatalog, _, catalogReady] = persisted(Persist.global("command.catalog.v1"), CommandCatalog, {})
const bind = (id: string, def: KeybindConfig | undefined, follows?: string) => {
const custom = settings.keybinds.get(actionId(id)) ?? (follows ? settings.keybinds.get(follows) : undefined)
const config = custom ?? def
const base = actionId(id)
const custom = settings.keybinds.get(base) ?? (follows ? settings.keybinds.get(follows) : undefined)
const config = custom ?? (base === PALETTE_ID ? DEFAULT_PALETTE_KEYBIND : def)
if (!config || config === "none") return
@ -468,6 +395,7 @@ export const { use: useCommand, provider: CommandProvider } = createSimpleContex
const resolved = registered().map((opt) => ({
...opt,
keybind: bind(opt.id, opt.keybind, opt.follows),
editable: opt.editable || opt.id === PALETTE_ID,
}))
const suggested = resolved.filter((x) => x.suggested && !x.disabled)
@ -484,14 +412,29 @@ export const { use: useCommand, provider: CommandProvider } = createSimpleContex
const suspended = () => selectKeybindsSuspended(suspendState())
const palette = createMemo(() => {
const config = settings.keybinds.get(PALETTE_ID) ?? DEFAULT_PALETTE_KEYBIND
const keybinds = parseKeybind(config)
return new Set(keybinds.map((kb) => signature(kb.key, kb.ctrl, kb.meta, kb.shift, kb.alt)))
// A surface that owns the keyboard, such as a page's prompt in the browser pane, is modal for less than the window.
const app = createAppKeymap({
blocked: (event) => suspended() || !!dialog.active || keyboardOwned(event?.target ?? null),
editable: isEditableTarget,
})
const keymap = createMemo(() => commandKeymap(options(), (id) => settings.keybinds.get(id) !== undefined))
onCleanup(app.destroy)
createEffect(() => {
const bound = options().filter((option) => !option.id.startsWith(SUGGESTED_PREFIX) && !option.disabled)
// The palette's keys come first, so they win over any other command on the same keys.
onCleanup(
registerCommandLayers(
app.keymap,
[
...bound.filter((option) => option.id === PALETTE_ID),
...bound.filter((option) => option.id !== PALETTE_ID),
],
(id) => settings.keybinds.get(id) !== undefined,
),
)
})
const optionMap = createMemo(() => {
const map = new Map<string, CommandOption>()
@ -514,41 +457,6 @@ export const { use: useCommand, provider: CommandProvider } = createSimpleContex
run(PALETTE_ID, "palette")
}
const handleKeyDown = (event: KeyboardEvent) => {
// A surface that owns the keyboard, such as a page's prompt in the browser pane, is modal for less than the window.
if (suspended() || dialog.active || keyboardOwned(event.target)) return
const sig = signatureFromEvent(event)
const isPalette = palette().has(sig)
const option = resolveKeybindOption(keymap().get(sig), event)
const modified = event.ctrlKey || event.metaKey || event.altKey
const isTab = event.key === "Tab"
if (isEditableTarget(event.target) && !isPalette && !option?.editable && !modified && !isTab) return
if (isPalette) {
event.preventDefault()
event.stopPropagation()
showPalette()
return
}
if (!option) return
// A command that returns false declines the key, which goes on to its target.
const result = option.onSelect?.("keybind")
if (result === false) return
event.preventDefault()
event.stopPropagation()
void result
}
onMount(() => {
makeEventListener(document, "keydown", handleKeyDown, { capture: true })
})
function register(cb: () => CommandOption[]): void
function register(key: string, cb: () => CommandOption[]): void
function register(key: string | (() => CommandOption[]), cb?: () => CommandOption[]) {
@ -572,7 +480,6 @@ export const { use: useCommand, provider: CommandProvider } = createSimpleContex
}
const keybindConfig = (id: string) => {
if (id === PALETTE_ID) return settings.keybinds.get(PALETTE_ID) ?? DEFAULT_PALETTE_KEYBIND
const base = actionId(id)
return (

View file

@ -0,0 +1,175 @@
import { afterEach, expect, test } from "bun:test"
import type { CommandOption } from "./command"
import { keyboardOwned, ownKeyboard } from "@opencode/ui/hooks"
import { createAppKeymap, registerCommandLayers } from "./keymap"
const cleanup: (() => void)[] = []
afterEach(() => {
cleanup.splice(0).forEach((dispose) => dispose())
document.body.replaceChildren()
})
function setup(options: CommandOption[], input?: { custom?: string[]; blocked?: (event?: KeyboardEvent) => boolean }) {
const app = createAppKeymap({
blocked: input?.blocked ?? (() => false),
editable: (target) => target instanceof HTMLElement && target.isContentEditable,
})
const layers = registerCommandLayers(app.keymap, options, (id) => input?.custom?.includes(id) ?? false)
cleanup.push(() => {
layers()
app.destroy()
})
return app
}
function press(target: HTMLElement, init: KeyboardEventInit) {
const event = new KeyboardEvent("keydown", { bubbles: true, cancelable: true, ...init })
target.dispatchEvent(event)
return event
}
function editor() {
const element = document.createElement("div")
element.contentEditable = "true"
document.body.append(element)
element.focus()
return element
}
function command(id: string, keybind: string, ran: string[], extra?: Partial<CommandOption>): CommandOption {
return { id, title: id, keybind, onSelect: () => void ran.push(id), ...extra }
}
// happy-dom never reports a Mac platform, so mod is Ctrl here.
test("a command with a when wins only in its context, then a user's binding, then the first registered", () => {
const ran: string[] = []
const inside = { value: true }
setup(
[
command("tab.close", "mod+w", ran),
command("file.close", "mod+w", ran),
command("terminal.close", "mod+w", ran, { when: () => inside.value }),
],
{ custom: ["file.close"] },
)
press(document.body, { key: "w", ctrlKey: true })
inside.value = false
press(document.body, { key: "w", ctrlKey: true })
expect(ran).toEqual(["terminal.close", "file.close"])
})
test("a declining command passes the key to the next command, and finally to the focused element", () => {
const ran: string[] = []
const skip = { value: true }
setup([
command("session.rename", "ctrl+r", ran, { skip: () => skip.value }),
command("plugin.run", "ctrl+r", ran, { onSelect: () => (ran.push("plugin.run"), false) }),
])
const declined = press(document.body, { key: "r", ctrlKey: true })
skip.value = false
const handled = press(document.body, { key: "r", ctrlKey: true })
expect(ran).toEqual(["plugin.run", "session.rename"])
expect(declined.defaultPrevented).toBe(false)
expect(handled.defaultPrevented).toBe(true)
})
test("a key that types a character fires in a text field only for an editable command", () => {
const ran: string[] = []
setup([
command("review.next", "j", ran),
command("prompt.stop", "escape", ran, { editable: true }),
command("model.choose", "mod+'", ran),
])
const field = editor()
const typed = press(field, { key: "j" })
press(field, { key: "Escape" })
press(field, { key: "'", ctrlKey: true })
field.blur()
press(document.body, { key: "j" })
expect(typed.defaultPrevented).toBe(false)
expect(ran).toEqual(["prompt.stop", "model.choose", "review.next"])
})
test("a focus target's command wins inside the target and is absent outside it", () => {
const ran: string[] = []
const field = editor()
const outside = document.createElement("button")
document.body.append(outside)
setup([
command("dialog.close", "escape", ran, { editable: true }),
command("prompt.stop", "escape", ran, { editable: true, target: () => field }),
])
press(field, { key: "Escape" })
outside.focus()
press(outside, { key: "Escape" })
expect(ran).toEqual(["prompt.stop", "dialog.close"])
})
test.each([
{ name: "composing", init: { key: "Escape", isComposing: true } },
{ name: "Safari's composition Enter", init: { key: "Escape", keyCode: 229 } },
])("keys are left to the IME while it composes: $name", (row) => {
const ran: string[] = []
setup([command("prompt.stop", "escape", ran, { editable: true })])
const event = press(editor(), row.init)
expect(event.defaultPrevented).toBe(false)
expect(ran).toEqual([])
})
test("keys are left alone while keybinds are blocked", () => {
const ran: string[] = []
const blocked = { value: true }
setup([command("palette", "mod+k", ran)], { blocked: () => blocked.value })
press(document.body, { key: "k", ctrlKey: true })
blocked.value = false
press(document.body, { key: "k", ctrlKey: true })
expect(ran).toEqual(["palette"])
})
// A page prompt in the browser pane registers itself; the app's keys stay off inside it and work everywhere else.
test("a surface that owns the keyboard keeps command keys from running inside it", () => {
const ran: string[] = []
setup([command("palette", "mod+k", ran)], { blocked: (event) => keyboardOwned(event?.target ?? null) })
const prompt = document.createElement("div")
const field = document.createElement("input")
prompt.append(field)
document.body.append(prompt)
cleanup.push(ownKeyboard(prompt))
press(field, { key: "k", ctrlKey: true })
press(document.body, { key: "k", ctrlKey: true })
expect(ran).toEqual(["palette"])
})
test.each([
{ keybind: "mod+alt+.", init: { key: "≥", code: "Period", ctrlKey: true, altKey: true } },
{ keybind: "mod+shift+[", init: { key: "{", code: "BracketLeft", ctrlKey: true, shiftKey: true } },
{ keybind: "alt+arrowup", init: { key: "ArrowUp", altKey: true } },
{ keybind: "mod+comma", init: { key: ",", ctrlKey: true } },
{ keybind: "shift+enter", init: { key: "Enter", shiftKey: true } },
])("$keybind matches the key the layout types", (row) => {
const ran: string[] = []
setup([command("run", row.keybind, ran)])
press(document.body, row.init)
expect(ran).toEqual(["run"])
})

View file

@ -0,0 +1,261 @@
import { Keymap, type KeymapHost } from "@opentui/keymap"
import { registerDefaultBindingParser } from "@opentui/keymap/addons"
import { createHtmlKeymapHost, type HtmlKeymapEvent } from "@opentui/keymap/html"
import type { CommandOption } from "./command"
export const IS_MAC = typeof navigator !== "undefined" && /(Mac|iPod|iPhone|iPad)/.test(navigator.platform)
export type AppKeymap = Keymap<HTMLElement, HtmlKeymapEvent>
/**
* The keymap behind every command keybind. It reads keys in the capture phase on the document root, before the
* focused element sees them.
*/
export function createAppKeymap(input: {
/** Whether keybinds are off for this key press, such as while a dialog or a surface owning the keyboard has it. */
blocked: (event?: KeyboardEvent) => boolean
editable: (target: EventTarget | null) => boolean
}) {
const host = createAppKeymapHost(document.documentElement, input.blocked)
const keymap: AppKeymap = new Keymap(host.host)
// Every binding is written by `keymapKey`: one `+`-joined combo.
keymap.prependBindingParser((ctx) => {
if (ctx.index !== 0) return
return {
parts: [ctx.parseObjectKey(strokeInput(ctx.input.trim()), { display: ctx.input })],
nextIndex: ctx.input.length,
}
})
registerDefaultBindingParser(keymap)
keymap.prependEventMatchResolver((event, ctx) => {
const original = event.originalEvent
if (!original) return
const name = keymapKeyName(keyFromKeyboardEvent(original))
const alias = KEY_ALIASES.get(name)
const stroke = {
name,
ctrl: original.ctrlKey,
shift: original.shiftKey,
meta: original.altKey,
super: original.metaKey,
}
return (alias ? [name, alias] : [name]).flatMap((name) => [
ctx.resolveKey({ ...stroke, name }),
// `shift+/` types `?`, so `?` binds the symbol whichever modifier the layout needs.
...(stroke.shift && name.length === 1 && !/^[a-z0-9]$/.test(name)
? [ctx.resolveKey({ ...stroke, name, shift: false })]
: []),
])
})
// A binding whose key types a character stays out of text fields, so typing in them is never taken.
keymap.registerBindingFields({
outsideText(value, ctx) {
if (value === true) ctx.activeWhen(() => !input.editable(document.activeElement))
},
})
return { keymap, destroy: host.destroy }
}
/**
* Registers the keybinds of `options`: one global layer, plus one layer per focus target, which wins over the global
* one while focus is inside it. On the same keys a command with a `when` comes first, then a user's own binding, then
* the order given. A command declines a key by returning false from `onSelect`, or through `when` and `skip`; the key
* then goes to the next command, and finally to the focused element.
*/
export function registerCommandLayers(keymap: AppKeymap, options: CommandOption[], custom: (id: string) => boolean) {
const layers = new Map<HTMLElement | undefined, CommandOption[]>()
options
.map((option, index) => ({ option, index, rank: (option.when ? 2 : 0) + (custom(option.id) ? 1 : 0) }))
.sort((a, b) => b.rank - a.rank || a.index - b.index)
.forEach(({ option }) => {
if (!option.keybind) return
const target = option.target?.()
if (option.target && !target) return
layers.set(target, [...(layers.get(target) ?? []), option])
})
const disposers = Array.from(layers, ([target, options]) =>
keymap.registerLayer({
target,
priority: target ? 1 : 0,
commands: options.map((option) => ({
name: option.id,
run(ctx) {
const event = ctx.event.originalEvent
if (event && option.skip?.(event)) return false
if (event && option.when && !option.when(event)) return false
return option.onSelect?.("keybind") !== false
},
})),
bindings: options.flatMap((option) =>
option
.keybind!.split(",")
.map((combo) => combo.trim())
.filter((combo) => combo && combo !== "none")
.map((combo) => {
const key = keymapKey(combo)
return { key, cmd: option.id, outsideText: !option.editable && typesCharacter(keymap, key) }
}),
),
}),
)
return () => disposers.forEach((dispose) => dispose())
}
/** Translates one combo of the app's keybind syntax (`mod+shift+arrowup`) into the keymap's. */
export function keymapKey(combo: string) {
return combo
.trim()
.split("+")
.map((part) => {
const lower = part.toLowerCase()
if (lower === "mod") return IS_MAC ? "super" : "ctrl"
if (lower === "meta" || lower === "cmd" || lower === "command") return "super"
return MODIFIER_PARTS.has(lower) ? lower : keymapKeyName(lower)
})
.join("+")
}
// One stroke as `keymapKey` writes it, such as `super+shift+[`.
function strokeInput(stroke: string) {
const parts = stroke.split("+")
const has = (...names: string[]) => parts.some((part) => names.includes(part))
return {
name: parts.findLast((part) => !MODIFIER_PARTS.has(part)) ?? parts.at(-1)!,
ctrl: has("ctrl", "control"),
shift: has("shift"),
meta: has("alt", "option"),
super: has("super"),
hyper: has("hyper") || undefined,
}
}
/** Whether a keymap key types a character, so it should stay out of text fields. */
export function typesCharacter(keymap: AppKeymap, key: string) {
const first = keymap.parseKeySequence(key)[0]?.stroke
if (!first) return false
return !first.ctrl && !first.meta && !first.super && first.name !== "tab"
}
export function keyFromKeyboardEvent(event: KeyboardEvent) {
const key = normalizeKey(physicalKey(event))
if (!event.altKey || /^[a-z0-9]$/.test(key)) return key
if (!event.code.startsWith("Key") || event.code.length !== 4) return key
return event.code.slice(3).toLowerCase()
}
const MODIFIER_PARTS = new Set(["ctrl", "control", "shift", "alt", "option", "super", "hyper"])
const KEY_NAMES = new Map([
["arrowup", "up"],
["arrowdown", "down"],
["arrowleft", "left"],
["arrowright", "right"],
["esc", "escape"],
["enter", "return"],
])
// The app writes these keys by name and the keymap parser reads both forms, so events resolve to each.
const KEY_ALIASES = new Map([
["comma", ","],
["plus", "+"],
])
function keymapKeyName(key: string) {
return KEY_NAMES.get(key) ?? key
}
function normalizeKey(key: string) {
if (key === ",") return "comma"
if (key === "+") return "plus"
if (key === " ") return "space"
return key.toLowerCase()
}
// ⇧[ types { and ⌥. types ≥ on US layouts. Keep ASCII layout mappings; non-ASCII falls back to the physical key.
function physicalKey(event: Pick<KeyboardEvent, "key" | "code">) {
if (event.key === "{" || event.key === "}") return event.key === "{" ? "[" : "]"
if (!/^[^\x00-\x7f]$/u.test(event.key)) return event.key
if (event.code === "BracketLeft") return "["
if (event.code === "BracketRight") return "]"
if (event.code === "Period") return "."
return event.key
}
// The HTML host, except that it drops keys while an IME composes or while command keybinds are blocked, and that
// its owner can destroy it, which disposes the keymap.
function createAppKeymapHost(root: HTMLElement, blocked: (event?: KeyboardEvent) => boolean) {
const host = createHtmlKeymapHost(root)
const destroyed = new Set<() => void>()
const state = { destroyed: false }
const keymapHost: KeymapHost<HTMLElement, HtmlKeymapEvent> = {
metadata: host.metadata,
rootTarget: host.rootTarget,
get isDestroyed() {
return state.destroyed
},
onDestroy(listener) {
destroyed.add(listener)
return () => destroyed.delete(listener)
},
getFocusedTarget: () => host.getFocusedTarget(),
getParentTarget: (target) => host.getParentTarget(target),
isTargetDestroyed: (target) => host.isTargetDestroyed(target),
onKeyPress: (listener) =>
host.onKeyPress((event) => {
const original = event.originalEvent
// Escape, Enter and Tab confirm or cancel IME candidates; Safari can report them as keyCode 229.
if (original && (original.isComposing || original.keyCode === 229)) return
if (blocked(original)) return
listener(event)
}),
onKeyRelease: (listener) => host.onKeyRelease(listener),
onFocusChange: (listener) => host.onFocusChange(listener),
onTargetDestroy: (target, listener) => host.onTargetDestroy(target, listener),
createCommandEvent: () => host.createCommandEvent(),
}
return {
host: keymapHost,
destroy() {
if (state.destroyed) return
state.destroyed = true
destroyed.forEach((listener) => listener())
},
}
}

View file

@ -1,3 +1,4 @@
import { createMediaQuery } from "@solid-primitives/media"
import { showToast, toaster } from "@opencode/ui/toast"
import { Schema } from "effect"
import { createEffect, createMemo, createSignal, onCleanup } from "solid-js"
@ -24,6 +25,7 @@ export function createTipToasts() {
const servers = useServers()
const language = useLanguage()
const platform = usePlatform()
const touch = createMediaQuery("(hover: none)")
const server = createMemo(() => {
const conn = servers.visible.find(servers.current) ?? servers.visible[0]
@ -74,7 +76,7 @@ export function createTipToasts() {
id: "hex",
title: "tips.hex.title",
description: "tips.hex.description",
when: () => hexInstalled() === false,
when: () => !touch() && hexInstalled() === false,
action: {
label: "tips.hex.install",
// anoma.ly/hex 404s with a query string; the trailing slash is required.

View file

@ -5,18 +5,15 @@ import { createComposerEditor } from "../src/composer/editor/interaction"
import type { ComposerPersistedState } from "../src/composer/types"
test.each([
{ key: "Escape", isComposing: true, keyCode: 27, list: false, stops: 0, selections: 0, prevented: false },
{ key: "Escape", isComposing: false, keyCode: 229, list: false, stops: 0, selections: 0, prevented: false },
{ key: "Escape", isComposing: false, keyCode: 27, list: false, stops: 1, selections: 0, prevented: true },
{ key: "Tab", isComposing: true, keyCode: 9, list: true, stops: 0, selections: 0, prevented: false },
{ key: "Tab", isComposing: false, keyCode: 229, list: true, stops: 0, selections: 0, prevented: false },
{ key: "Enter", isComposing: false, keyCode: 229, list: true, stops: 0, selections: 0, prevented: false },
{ key: "Tab", isComposing: false, keyCode: 9, list: true, stops: 0, selections: 1, prevented: true },
{ key: "Tab", isComposing: true, keyCode: 9, selections: 0, prevented: false },
{ key: "Tab", isComposing: false, keyCode: 229, selections: 0, prevented: false },
{ key: "Enter", isComposing: false, keyCode: 229, selections: 0, prevented: false },
{ key: "Tab", isComposing: false, keyCode: 9, selections: 1, prevented: true },
])("IME key ownership: $key, composing=$isComposing, keyCode=$keyCode", (row) => {
const value = createRoot((dispose) => {
const store = createStore<ComposerPersistedState>({ prompt: [], context: { items: [] } })
const [calls, setCalls] = createStore({ stops: 0, selections: 0 })
const [calls, setCalls] = createStore({ selections: 0 })
const editor = createComposerEditor({
store,
@ -26,10 +23,9 @@ test.each([
onSuggestionSelect: () => () => setCalls("selections", (count) => count + 1),
view: {
submit: {
working: () => true,
stopping: () => false,
onSubmit() {},
onStop: () => setCalls("stops", (count) => count + 1),
onStop() {},
},
},
})
@ -38,12 +34,10 @@ test.each([
})
try {
if (row.list) {
value.editor.openCommands()
value.editor.dispatch({ type: "popover.results", ids: ["review"] })
expect(value.editor.state.popover.type).toBe("command-inline")
expect(value.editor.suggestions().map((item) => item.id)).toEqual(["review"])
}
value.editor.openCommands()
value.editor.dispatch({ type: "popover.results", ids: ["review"] })
expect(value.editor.state.popover.type).toBe("command-inline")
expect(value.editor.suggestions().map((item) => item.id)).toEqual(["review"])
const event = new KeyboardEvent("keydown", {
key: row.key,
@ -54,11 +48,10 @@ test.each([
// happy-dom does not initialize the legacy keyCode field from KeyboardEventInit.
Object.defineProperty(event, "keyCode", { value: row.keyCode })
expect(value.editor.onKeyDown(event)).toBe(true)
expect(value.calls.stops).toBe(row.stops)
expect(value.calls.selections).toBe(row.selections)
expect(event.defaultPrevented).toBe(row.prevented)
if (row.list && !row.selections) expect(value.editor.state.popover.type).toBe("command-inline")
if (!row.selections) expect(value.editor.state.popover.type).toBe("command-inline")
} finally {
value.dispose()
}

View file

@ -738,7 +738,7 @@ export type ModelCost = {
export type GenerateVideoRunning = { id: GenerateVideoID; status: "running" }
export type BlobInfo = { id: BlobID; mime: string; bytes: number; expiresAt: number }
export type BlobInfo = { id: BlobID; mime: string; bytes: number }
export type GenerateVideoError = {
id: GenerateVideoID

View file

@ -4,7 +4,7 @@ import { globals } from "./globals.js"
import type { Builtins } from "./intrinsics.js"
import { IntrinsicNames } from "./intrinsic-names.js"
import { type AstNode, type Binding, PendingThrow } from "./model.js"
import { moduleName, resolveModule } from "./modules.js"
import { isRuntimeModule, moduleName, resolveModule } from "./modules.js"
import { define, entries, type HostNamespace, makingIntrinsics, nativeRule, Obj, type Value } from "./objects.js"
import type { HostResult } from "../host.js"
import { Prelude } from "../prelude/prelude.js"
@ -88,12 +88,7 @@ export class Interpreter<R> {
const cached = this.modules.get(name)
if (cached !== undefined) return cached
const module = resolveModule(name, (global) => this.globalScope.get(global)?.value, this.moduleGlobals)
if (module === undefined)
throw new PendingThrow(
"Error",
`Cannot import "${specifier}": it isn't available here, where packages and files can't be loaded. Use the provided globals.`,
site,
)
if (module === undefined) throw new PendingThrow("Error", cannotImport(specifier), site)
this.modules.set(name, module)
return module
}
@ -135,3 +130,11 @@ export class Interpreter<R> {
return this.sources.get(id.source)?.node(id)
}
}
/** Why `specifier` can't be loaded, split so the error names the kind of import that failed. */
function cannotImport(specifier: string): string {
if (specifier.startsWith(".") || specifier.startsWith("/") || specifier.startsWith("file:"))
return `Cannot import "${specifier}": local files can't be imported.`
if (isRuntimeModule(specifier)) return `Cannot import "${specifier}": this runtime doesn't provide it.`
return `Cannot import "${specifier}": packages can't be installed here.`
}

View file

@ -18,6 +18,20 @@ const aliases: Record<string, (global: (name: string) => Value) => Value> = {
/** `node:fs` names the same module as `fs`. */
export const moduleName = (specifier: string) => (specifier.startsWith("node:") ? specifier.slice(5) : specifier)
// Node's core modules, fixed here so every host gives the same answer (Bun's `isBuiltin` also claims `ws` and `undici`).
const core = new Set(
"assert async_hooks buffer child_process cluster console constants crypto dgram diagnostics_channel dns domain events fs http http2 https inspector module net os path perf_hooks process punycode querystring readline repl stream string_decoder sys timers tls trace_events tty url util v8 vm wasi worker_threads zlib".split(
" ",
),
)
/** Whether a specifier names a module a runtime provides, as Node's and Bun's own modules are, rather than a package. */
export const isRuntimeModule = (specifier: string) =>
specifier.startsWith("node:") ||
specifier === "bun" ||
specifier.startsWith("bun:") ||
core.has(specifier.split("/")[0]!)
/** `hosted` names the global a host's own module names load (`{ bun: "Bun" }`). */
export const resolveModule = (
specifier: string,

View file

@ -630,7 +630,13 @@ describe("imports", () => {
test("a module that isn't provided, or a missing export, fails at the import", async () => {
const target = CodeMode.make({ extensions: [files] })
expect((await failure(`import yaml from "yaml"`, target)).message).toStartWith(
`Error: Cannot import "yaml": it isn't available here, where packages and files can't be loaded.`,
`Error: Cannot import "yaml": packages can't be installed here.`,
)
expect((await failure(`import ws from "ws"`, target)).message).toStartWith(
`Error: Cannot import "ws": packages can't be installed here.`,
)
expect((await failure(`import x from "./local.js"`, target)).message).toStartWith(
`Error: Cannot import "./local.js": local files can't be imported.`,
)
expect(await value(`try { await import("child_process") } catch (e) { return e.message }`, target)).toStartWith(
`Cannot import "child_process"`,
@ -638,7 +644,9 @@ describe("imports", () => {
expect((await failure(`import { writeFile } from "fs"`, target)).message).toStartWith(
`SyntaxError: "fs" has no export named "writeFile".`,
)
expect((await failure(`require("fs")`)).message).toStartWith(`Error: Cannot import "fs"`)
expect((await failure(`require("fs")`)).message).toStartWith(
`Error: Cannot import "fs": this runtime doesn't provide it.`,
)
})
})

View file

@ -6,8 +6,7 @@ import { BlobStore } from "@opencode/schema/blob-store"
import { makeGlobalNode } from "@opencode/util/effect/app-node"
import { FSUtil } from "@opencode/util/fs-util"
import { Global } from "@opencode/util/global"
import { Context, Duration, Effect, Layer, Option, Schedule, Schema, Stream } from "effect"
import { FileRetention } from "./file-retention.js"
import { Context, Effect, Layer, Schema, Stream } from "effect"
export const ID = BlobStore.ID
export type ID = BlobStore.ID
@ -22,7 +21,6 @@ export class UnavailableError extends Schema.TaggedError<UnavailableError>()("Bl
message: Schema.String,
}) {}
export const RETENTION = Duration.days(7)
/** Blobs are files named by their ID, with no extension; their type is read from their first bytes. */
export const DIRECTORY = "blobs"
@ -32,18 +30,15 @@ export interface Content extends Info {
}
export interface Interface {
/** Stores the stream as the blob `id`, replacing any earlier one. The file appears only once it's whole. */
readonly write: <E>(id: ID, stream: Stream.Stream<Uint8Array, E>) => Effect.Effect<Info, E | UnavailableError>
/** Stores the stream as a new blob, flushed to disk before it returns. A failed write leaves no blob. */
readonly write: <E>(stream: Stream.Stream<Uint8Array, E>) => Effect.Effect<Info, E | UnavailableError>
readonly read: (id: ID) => Effect.Effect<Content, NotFoundError>
readonly remove: (id: ID) => Effect.Effect<void>
}
export class Service extends Context.Service<Service, Interface>()("@opencode/BlobStore") {}
/**
* Files under `<data>/blobs/`, deleted 7 days after they're written, at startup and hourly. Nothing tracks who uses a
* blob, so a caller that keeps one longer copies it.
*/
/** Files under `<data>/blobs/`, kept until something removes them. */
const layer = Layer.effect(
Service,
Effect.gen(function* () {
@ -55,7 +50,6 @@ const layer = Layer.effect(
const read = Effect.fn("BlobStore.read")(function* (id: ID) {
const missing = new NotFoundError({ id, message: `Blob not found: ${id}` })
const info = yield* fs.stat(file(id)).pipe(Effect.mapError(() => missing))
const written = Option.getOrUndefined(info.mtime)?.getTime() ?? 0
const head = yield* fs.stream(file(id), { bytesToRead: 64 }).pipe(
Stream.runCollect,
Effect.mapError(() => missing),
@ -65,46 +59,28 @@ const layer = Layer.effect(
path: file(id),
mime: Media.detectMediaType(Buffer.concat([...head])) ?? "application/octet-stream",
bytes: Number(info.size),
expiresAt: written + Duration.toMillis(RETENTION),
}
})
// Written to `<id>.part`, synced, then renamed, so a stored blob is always whole.
const write = <E>(id: ID, stream: Stream.Stream<Uint8Array, E>) =>
const remove = (id: ID) => fs.remove(file(id), { force: true }).pipe(Effect.ignore)
const write = <E>(stream: Stream.Stream<Uint8Array, E>) =>
Effect.gen(function* () {
const part = `${file(id)}.part`
const id = ID.create()
const unavailable = (cause: unknown) =>
new UnavailableError({ message: `Could not store blob ${id}: ${String(cause)}` })
yield* fs.makeDirectory(directory, { recursive: true }).pipe(Effect.mapError(unavailable))
yield* Effect.scoped(
Effect.gen(function* () {
const handle = yield* fs.open(part, { flag: "w", mode: 0o600 }).pipe(Effect.mapError(unavailable))
const handle = yield* fs.open(file(id), { flag: "w", mode: 0o600 }).pipe(Effect.mapError(unavailable))
yield* stream.pipe(Stream.runForEach((chunk) => handle.writeAll(chunk).pipe(Effect.mapError(unavailable))))
yield* handle.sync.pipe(Effect.mapError(unavailable))
}),
).pipe(Effect.onError(() => fs.remove(part, { force: true }).pipe(Effect.ignore)))
yield* fs.rename(part, file(id)).pipe(Effect.mapError(unavailable))
).pipe(Effect.onError(() => remove(id)))
const stored = yield* read(id).pipe(Effect.mapError(unavailable))
return { id, mime: stored.mime, bytes: stored.bytes, expiresAt: stored.expiresAt } satisfies Info
return { id, mime: stored.mime, bytes: stored.bytes } satisfies Info
}).pipe(Effect.withSpan("BlobStore.write"))
const remove = (id: ID) => fs.remove(file(id), { force: true }).pipe(Effect.ignore)
// Blobs and leftover `.part` files are deleted once older than the retention.
yield* fs.readDirectory(directory).pipe(
Effect.orElseSucceed((): string[] => []),
Effect.flatMap((entries) =>
FileRetention.cleanup(
fs,
entries.filter((entry) => entry.startsWith("video_")).map((entry) => path.join(directory, entry)),
RETENTION,
),
),
Effect.ignoreCause({ log: "Error", message: "Blob cleanup failed" }),
Effect.repeat(Schedule.spaced(Duration.hours(1))),
Effect.forkScoped,
)
return Service.of({ write, read, remove })
}),
)

View file

@ -93,16 +93,20 @@ export type Inventory = {
readonly namespaces?: ReadonlyMap<string, ToolNamespace>
}
// Invariant model-facing guidance; the changing tool catalog is delivered through Instructions.
const description = [
"Run JavaScript in a confined Code Mode runtime to script tool calls and HTTP requests and compose their results.",
"Write plain JavaScript and send it exactly as written: no code fence, and no JSON or other wrapper around it.",
"`fetch` is available for HTTP requests. Imports, direct filesystem access, and timers are unavailable: there is no `setTimeout` or sleep. All other external access goes through `tools`.",
"Inside `execute`, the only callable tools are those explicitly listed in the Code Mode catalog instructions or returned by the `search` function. Ignore tools shown outside the Code Mode catalog. They are not available in the Code Mode runtime.",
'Call tools through `tools` using only exact paths and signatures from the catalog. Do not infer or normalize tool names; preserve bracket notation such as `tools.<namespace>["tool-name"](input)`.',
"Prefer an explicit `return`; if omitted, the final top-level expression becomes the result.",
"Await every call whose completion matters; pending calls are interrupted when execution ends. Run independent calls concurrently with `Promise.allSettled`.",
].join("\n")
// Invariant model-facing guidance; the changing tool catalog is delivered through Instructions. With `full_codemode`,
// the runtime also has Bun's file APIs.
const description = (full: boolean) =>
[
"Run JavaScript in a confined Code Mode runtime to script tool calls and HTTP requests and compose their results.",
"Write plain JavaScript and send it exactly as written: no code fence, and no JSON or other wrapper around it.",
full
? "`fetch` is available for HTTP requests, and Bun's file APIs (`Bun.file`, `Bun.write`, `Bun.Glob`) for files, in place of Node's `fs`. Imports and timers are unavailable: there is no `setTimeout` or sleep. All other external access goes through `tools`."
: "`fetch` is available for HTTP requests. Imports, direct filesystem access, and timers are unavailable: there is no `setTimeout` or sleep. All other external access goes through `tools`.",
"Inside `execute`, the only callable tools are those explicitly listed in the Code Mode catalog instructions or returned by the `search` function. Ignore tools shown outside the Code Mode catalog. They are not available in the Code Mode runtime.",
'Call tools through `tools` using only exact paths and signatures from the catalog. Do not infer or normalize tool names; preserve bracket notation such as `tools.<namespace>["tool-name"](input)`.',
"Prefer an explicit `return`; if omitted, the final top-level expression becomes the result.",
"Await every call whose completion matters; pending calls are interrupted when execution ends. Run independent calls concurrently with `Promise.allSettled`.",
].join("\n")
export const create = (
inventory: Inventory,
@ -113,7 +117,7 @@ export const create = (
) => {
return {
name: "execute",
description,
description: description(services !== undefined),
input: CodeMode.Input,
freeform: { type: "text" },
output: ExecuteOutput,

View file

@ -15,6 +15,12 @@ type Connection = NonNullable<Effect.Success<ReturnType<Context["integration"]["
const Prepared = Schema.Struct({ missing: Schema.Array(Schema.String) })
const Published = Schema.Struct({ url: Schema.String })
const Files = Schema.Struct({
revision: Schema.Number,
files: Schema.Array(
Schema.Struct({ path: Schema.String, sha256: Schema.String, text: Schema.optional(Schema.String) }),
),
})
const Problem = Schema.Struct({ message: Schema.optional(Schema.String), owner: Schema.optional(Schema.String) })
/**
@ -97,8 +103,27 @@ export const make = Effect.fnUntraced(function* (ctx: Context, http: HttpClient.
Effect.flatMap((slug) => publish(slug, input, true)),
Effect.map((published) => ({ url: published.url })),
),
// Console has no API that returns an artifact's files.
read: () => Effect.fail(new Error("OpenCode Console can't return an artifact's files yet")),
// Console inlines UTF-8 text files up to a limit; the rest download as blobs of the same revision.
read: (id) =>
Effect.gen(function* () {
const slug = yield* slugOf(id)
const send = yield* sender(ctx, http, connection, slug)
const listing = yield* send("GET", `/api/artifacts/${slug}/files`).pipe(
Effect.flatMap(HttpClientResponse.schemaBodyJson(Files)),
)
const files = yield* Effect.forEach(
listing.files,
(file) =>
file.text !== undefined
? Effect.succeed([file.path, new TextEncoder().encode(file.text)] as const)
: send("GET", `/api/artifacts/${slug}/blobs/${file.sha256}?revision=${listing.revision}`).pipe(
Effect.flatMap((response) => response.arrayBuffer),
Effect.map((bytes) => [file.path, new Uint8Array(bytes)] as const),
),
{ concurrency: 4 },
)
return Object.fromEntries(files)
}).pipe(Effect.scoped),
delete: (id) =>
Effect.gen(function* () {
const slug = yield* slugOf(id)
@ -151,7 +176,7 @@ const sender = Effect.fnUntraced(function* (
const credential = yield* ctx.integration.connection.resolve(connection)
if (!credential || credential.type === "external")
return yield* Effect.fail(new Error("OpenCode Console is not connected"))
return (method: "POST" | "PUT" | "DELETE", path: string, body?: Uint8Array | object) => {
return (method: "GET" | "POST" | "PUT" | "DELETE", path: string, body?: Uint8Array | object) => {
const request = HttpClientRequest.make(method)(`${ConsoleAccess.server(credential)}${path}`).pipe(
HttpClientRequest.acceptJson,
HttpClientRequest.setHeaders(ConsoleAccess.headers(credential)),
@ -177,7 +202,9 @@ const sender = Effect.fnUntraced(function* (
problem?.owner !== undefined
? `${problem.owner} already shared an OpenCode Console artifact named ${slug}; give this one another title`
: response.status === 404
? "Artifacts are off for this OpenCode Console workspace"
? method === "GET"
? `OpenCode Console has no artifact named ${slug}`
: "Artifacts are off for this OpenCode Console workspace"
: (problem?.message ?? `OpenCode Console answered ${response.status}`),
),
),

View file

@ -1,13 +1,24 @@
export * as VideoGeneration from "./video-generation.js"
import { randomUUID } from "node:crypto"
import { and, eq, lte, sql } from "drizzle-orm"
import { Media } from "@opencode/ai/effect"
import { VideoID, type VideoJob, type VideoRequest, type VideoRunning } from "@opencode/schema/generate"
import type { Model } from "@opencode/schema/model"
import {
VideoErrorReason,
VideoID,
type VideoJob,
type VideoRequest,
type VideoRunning,
} from "@opencode/schema/generate"
import { Model } from "@opencode/schema/model"
import { makeGlobalNode } from "@opencode/util/effect/app-node"
import { Global } from "@opencode/util/global"
import { Context, Deferred, Duration, Effect, Exit, FiberMap, Layer, Option, Schedule, Schema } from "effect"
import { Clock, Context, Deferred, Duration, Effect, Exit, FiberMap, Layer, Option, Schedule, Schema } from "effect"
import { BlobStore } from "./blob-store.js"
import { Database } from "./database/database.js"
import { Generate } from "./generate.js"
import { KV } from "./kv.js"
import { KVTable } from "./kv/sql.js"
import { Location } from "./location.js"
import { LocationServiceMap } from "./location-service-map.js"
import { AbsolutePath } from "./schema.js"
@ -19,20 +30,62 @@ export class NotFoundError extends Schema.TaggedError<NotFoundError>()("VideoGen
const INTERVAL = Duration.seconds(5)
const DEADLINE = Duration.hours(2)
/** How long a finished job's record is kept. Its blobs keep their own retention. */
const RETENTION = Duration.hours(24)
const PREFIX = "video:"
/**
* A server polls a job only while it holds the job's lease, so servers sharing a database never poll the same job, and
* one takes over the jobs of a server that stopped within about a minute.
*/
const LEASE = "video-lease:"
const TTL = Duration.minutes(1)
export interface StartOptions {
/** Where the model and its credentials are resolved; defaults to the server's base configuration. */
readonly location?: Location.Ref
}
export interface Interface {
/** Returns once the provider accepted the job; the server then polls it and stores the video as a blob. */
readonly start: (input: VideoRequest) => Effect.Effect<VideoRunning, Generate.Error>
/** Returns once the provider accepted the job; the server then polls it and stores the videos as blobs. */
readonly start: (input: VideoRequest, options?: StartOptions) => Effect.Effect<VideoRunning, Generate.Error>
readonly get: (id: VideoID) => Effect.Effect<VideoJob, NotFoundError>
}
export class Service extends Context.Service<Service, Interface>()("@opencode/VideoGeneration") {}
// `remote` is the provider's ID for the job; it never leaves this service.
const fields = { model: Model.Ref, location: Location.Ref, created: Schema.Finite }
const Job = Schema.Union([
Schema.Struct({ status: Schema.Literal("submitting"), ...fields }),
Schema.Struct({ status: Schema.Literal("running"), remote: Schema.String, ...fields }),
Schema.Struct({
status: Schema.Literal("completed"),
blobs: Schema.Array(BlobStore.ID),
finished: Schema.Finite,
...fields,
}),
Schema.Struct({
status: Schema.Literal("error"),
reason: VideoErrorReason,
error: Schema.String,
finished: Schema.Finite,
...fields,
}),
])
type Job = typeof Job.Type
type Running = Extract<Job, { status: "running" }>
type Outcome =
| { readonly status: "completed"; readonly blobs: readonly BlobStore.ID[] }
| { readonly status: "error"; readonly reason: VideoErrorReason; readonly error: string }
const decode = Schema.decodeUnknownOption(Job)
const encode = Schema.encodeSync(Job)
const decodeID = Schema.decodeUnknownOption(VideoID)
/**
* Running and failed jobs live in memory only: a restart forgets them, and a running job's videos are never collected.
* A finished job is read from its blobs, so it outlives a restart until they expire.
*
* TODO: record jobs durably, so a restart resumes polling them.
* Each job is a record in kv under `video:<id>`, written before the provider is called, so a restart resumes polling
* running jobs and fails the ones whose submission it interrupted. Records are deleted 24 hours after the job finished.
* Only the server holding a job's lease works on it.
*/
const layer = Layer.effect(
Service,
@ -40,121 +93,159 @@ const layer = Layer.effect(
const global = yield* Global.Service
const locations = yield* LocationServiceMap.Service
const blobs = yield* BlobStore.Service
const kv = yield* KV.Service
const db = (yield* Database.Service).db
const owner = randomUUID()
// The same base-config Location the generate routes use.
const base = locations.get(Location.Ref.make({ directory: AbsolutePath.make(global.config) }))
const base = Location.Ref.make({ directory: AbsolutePath.make(global.config) })
const fibers = yield* FiberMap.make<VideoID>()
const jobs = new Map<VideoID, VideoJob>()
const generate = <A>(run: (generate: Generate.Interface) => Effect.Effect<A, Generate.Error>) =>
const save = (id: VideoID, job: Job) => kv.set(PREFIX + id, encode(job))
// Takes the lease if it's free, expired or already ours.
const claim = Effect.fnUntraced(function* (id: VideoID) {
const now = yield* Clock.currentTimeMillis
const value = { owner, until: now + Duration.toMillis(TTL) }
const claimed = yield* db
.insert(KVTable)
.values({ key: LEASE + id, value, time_created: now, time_updated: now })
.onConflictDoUpdate({
target: KVTable.key,
set: { value, time_updated: now },
where: sql`json_extract(${KVTable.value}, '$.owner') = ${owner} or json_extract(${KVTable.value}, '$.until') <= ${now}`,
})
.returning({ key: KVTable.key })
.get()
.pipe(Effect.orDie)
return claimed !== undefined
})
const release = (id: VideoID) =>
db
.delete(KVTable)
.where(and(eq(KVTable.key, LEASE + id), sql`json_extract(${KVTable.value}, '$.owner') = ${owner}`))
.run()
.pipe(Effect.ignore)
// Runs the work while renewing its lease, and stops it if another server took the lease over.
const hold = <A, E>(id: VideoID, work: Effect.Effect<A, E>) =>
Effect.raceFirst(
work,
claim(id).pipe(
Effect.repeat({ schedule: Schedule.spaced(Duration.seconds(30)), while: (held) => held }),
Effect.andThen(Effect.logWarning("video lease lost", { id })),
Effect.andThen(Effect.interrupt),
),
).pipe(Effect.ensuring(release(id)))
const finish = (id: VideoID, job: Job, outcome: Outcome) =>
Clock.currentTimeMillis.pipe(
Effect.flatMap((finished) =>
save(id, { model: job.model, location: job.location, created: job.created, ...outcome, finished }),
),
)
const generate = <A>(
location: Location.Ref,
run: (generate: Generate.Interface) => Effect.Effect<A, Generate.Error>,
) =>
Generate.Service.pipe(
Effect.flatMap(run),
Effect.provide(base),
Effect.provide(locations.get(location)),
Effect.catchTag("FileSystem.DirectoryNotFoundError", (error) =>
Effect.fail(new Generate.UnavailableError({ message: `Location not found: ${error.directory}` })),
),
)
// Each video becomes blob `<id>_<n>`, so a restarted server finds them from the job's ID alone.
const blobID = (id: VideoID, index: number) => BlobStore.ID.make(`${id}_${index}`)
const store = Effect.fnUntraced(function* (id: VideoID, model: Model.Ref, providerID: string) {
const videos = yield* generate((service) => service.video.result(model, providerID))
const stored = yield* Effect.forEach(videos, (video, index) =>
blobs.write(blobID(id, index), video.stream).pipe(
// All or nothing: a job never reports only some of its videos.
const download = Effect.fnUntraced(function* (job: Running) {
const videos = yield* generate(job.location, (service) => service.video.result(job.model, job.remote))
const written: BlobStore.ID[] = []
yield* Effect.forEach(videos, (video) =>
blobs.write(video.stream).pipe(
Effect.tap((blob) => Effect.sync(() => written.push(blob.id))),
Effect.flatMap((blob) =>
blob.bytes > 0
? Effect.succeed(blob)
? Effect.void
: Effect.fail(
new Generate.ProviderRequestError({
providerID: model.providerID,
providerID: job.model.providerID,
reason: "provider",
message: "The provider returned an empty video",
}),
),
),
),
).pipe(
// All or nothing: a job never reports only some of its videos.
Effect.onError(() => Effect.forEach(videos, (_, index) => blobs.remove(blobID(id, index)), { discard: true })),
)
return { id, status: "completed", blobs: stored } satisfies VideoJob
).pipe(Effect.onError(() => Effect.forEach(written, blobs.remove, { discard: true })))
return written
})
// A finished job outlives a restart through its blobs: `<id>_0`, `<id>_1`, … up to the first missing one.
const stored = (id: VideoID): Effect.Effect<readonly BlobStore.Info[]> =>
Effect.gen(function* () {
const found: BlobStore.Info[] = []
while (true) {
const blob = yield* blobs.read(blobID(id, found.length)).pipe(Effect.option)
if (Option.isNone(blob)) return found
found.push({
id: blob.value.id,
mime: blob.value.mime,
bytes: blob.value.bytes,
expiresAt: blob.value.expiresAt,
})
}
})
// A status read that fails is retried at the next interval: the provider may be briefly unavailable.
const poll = (id: VideoID, model: Model.Ref, providerID: string) =>
generate((service) => service.video.status(model, providerID)).pipe(
const poll = (id: VideoID, job: Running, left: Duration.Duration) =>
generate(job.location, (service) => service.video.status(job.model, job.remote)).pipe(
Effect.map((status) => (status.status === "running" ? undefined : status)),
Effect.catch((error) =>
Effect.logWarning("video status read failed", { id, error: error.message }).pipe(Effect.as(undefined)),
),
Effect.repeat({ schedule: Schedule.spaced(INTERVAL), until: (status) => status !== undefined }),
Effect.timeoutOption(DEADLINE),
Effect.timeoutOption(left),
Effect.map((status) => Option.getOrUndefined(status)),
)
const settle = Effect.fnUntraced(function* (id: VideoID, model: Model.Ref, providerID: string) {
const settled = yield* poll(id, model, providerID)
if (Option.isNone(settled) || settled.value === undefined)
return {
id,
const settle = Effect.fnUntraced(function* (id: VideoID, job: Running) {
const left = job.created + Duration.toMillis(DEADLINE) - (yield* Clock.currentTimeMillis)
const settled = left > 0 ? yield* poll(id, job, Duration.millis(left)) : undefined
if (settled === undefined)
return yield* finish(id, job, {
status: "error",
reason: "unknown",
error: `The provider had no result ${Duration.format(DEADLINE)} after submission`,
} satisfies VideoJob
if (settled.value.status === "error") {
const reason = settled.value.reason ?? "failed"
return { id, status: "error", reason, error: `The provider reported the job as ${reason}` } satisfies VideoJob
})
if (settled.status === "error") {
const reason = settled.reason ?? "failed"
return yield* finish(id, job, { status: "error", reason, error: `The provider reported the job as ${reason}` })
}
return yield* store(id, model, providerID).pipe(
const outcome = yield* download(job).pipe(
Effect.retry({ times: 2, schedule: Schedule.exponential("1 second") }),
Effect.catch((error) =>
Effect.succeed({ id, status: "error", reason: "failed", error: error.message } satisfies VideoJob),
),
Effect.map((written): Outcome => ({ status: "completed", blobs: written })),
Effect.catch((error) => Effect.succeed<Outcome>({ status: "error", reason: "failed", error: error.message })),
)
yield* finish(id, job, outcome)
})
const start = Effect.fn("VideoGeneration.start")(function* (input: VideoRequest) {
const start = Effect.fn("VideoGeneration.start")(function* (input: VideoRequest, options?: StartOptions) {
const id = VideoID.create()
const submitted = yield* Deferred.make<VideoRunning, Generate.Error>()
const job = {
status: "submitting",
model: input.model,
location: options?.location ?? base,
created: yield* Clock.currentTimeMillis,
} satisfies Job
// Runs in the server's fibers, so a client that disconnects can't interrupt a paid submission midway.
yield* claim(id)
yield* FiberMap.run(
fibers,
id,
Effect.gen(function* () {
const started = yield* generate((service) =>
service.video.start({
...input,
start: input.start && Media.image(Media.base64(input.start.data, input.start.mime)),
end: input.end && Media.image(Media.base64(input.end.data, input.end.mime)),
references: input.references?.map((file) => Media.base64(file.data, file.mime)),
}),
)
const running = { id, status: "running" } as const
jobs.set(id, running)
yield* Deferred.succeed(submitted, running)
const settled = yield* settle(id, input.model, started.id)
// A finished job's blobs are its record from here on.
if (settled.status === "completed") return jobs.delete(id)
// A failure is kept as long as a blob would be, so the map holds at most one retention's worth of jobs.
jobs.set(id, settled)
yield* Effect.sleep(BlobStore.RETENTION)
jobs.delete(id)
}).pipe(
hold(
id,
Effect.gen(function* () {
yield* save(id, job)
// A rejected submission's ID is never returned, so its record is dropped.
const started = yield* generate(job.location, (service) =>
service.video.start({
...input,
start: input.start && Media.image(Media.base64(input.start.data, input.start.mime)),
end: input.end && Media.image(Media.base64(input.end.data, input.end.mime)),
references: input.references?.map((file) => Media.base64(file.data, file.mime)),
}),
).pipe(Effect.tapError(() => kv.remove(PREFIX + id)))
const running = { ...job, status: "running", remote: started.id } satisfies Running
yield* save(id, running)
yield* Deferred.succeed(submitted, { id, status: "running" } as const)
yield* settle(id, running)
}),
).pipe(
// Once the submission succeeded, this does nothing.
Effect.onExit((exit) => (Exit.isFailure(exit) ? Deferred.failCause(submitted, exit.cause) : Effect.void)),
Effect.ignore,
@ -164,17 +255,108 @@ const layer = Layer.effect(
})
const get = Effect.fn("VideoGeneration.get")(function* (id: VideoID) {
const job = jobs.get(id)
if (job) return job
const found = yield* stored(id)
if (found.length === 0) return yield* new NotFoundError({ id, message: `Video not found: ${id}` })
return { id, status: "completed", blobs: found } satisfies VideoJob
const missing = new NotFoundError({ id, message: `Video not found: ${id}` })
const stored = yield* kv.get(PREFIX + id)
const job = stored === undefined ? undefined : Option.getOrUndefined(decode(stored))
if (!job || expired(job, yield* Clock.currentTimeMillis)) return yield* missing
if (job.status === "submitting" || job.status === "running") return { id, status: "running" } satisfies VideoJob
if (job.status === "error")
return { id, status: "error", reason: job.reason, error: job.error } satisfies VideoJob
// A blob that expired or was deleted is dropped.
const found = yield* Effect.forEach(job.blobs, (blob) => blobs.read(blob).pipe(Effect.option))
const infos = found.flatMap((blob) =>
Option.isSome(blob) ? [{ id: blob.value.id, mime: blob.value.mime, bytes: blob.value.bytes }] : [],
)
if (infos.length === 0) return yield* missing
return { id, status: "completed", blobs: infos } satisfies VideoJob
})
const rows = Effect.gen(function* () {
const found: KV.Entry[] = []
let after: string | undefined
while (true) {
const page = yield* kv.scan({ prefix: PREFIX, after, limit: 500 })
found.push(...page.entries)
if (!page.next) return found
after = page.next
}
})
// At startup and every minute, take over unfinished jobs nobody holds: a running job is polled again until its
// deadline. A submission the server stopped is never resent: it's paid and not idempotent, so whether the provider
// got it is unknown.
const adopt = Effect.gen(function* () {
yield* Effect.forEach(
yield* rows,
(row) =>
Effect.gen(function* () {
const id = Option.getOrUndefined(decodeID(row.key.slice(PREFIX.length)))
const seen = Option.getOrUndefined(decode(row.value))
if (!id || !seen || (seen.status !== "running" && seen.status !== "submitting")) return
if (yield* FiberMap.has(fibers, id)) return
if (!(yield* claim(id))) return
// Read again under the lease: the previous owner may have finished the job since the scan.
const stored = yield* kv.get(PREFIX + id)
const job = stored === undefined ? undefined : Option.getOrUndefined(decode(stored))
if (!job || (job.status !== "running" && job.status !== "submitting")) return yield* release(id)
if (job.status === "running")
return yield* FiberMap.run(fibers, id, hold(id, settle(id, job)).pipe(Effect.ignore))
yield* finish(id, job, {
status: "error",
reason: "unknown",
error: "The server stopped while submitting the job; its outcome is unknown",
}).pipe(Effect.ensuring(release(id)))
}),
{ discard: true },
)
})
yield* adopt
yield* adopt.pipe(
Effect.ignoreCause({ log: "Error", message: "Video job takeover failed" }),
Effect.repeat(Schedule.spaced(TTL)),
Effect.delay(TTL),
Effect.forkScoped,
)
// Records that can't be read are removed with the expired ones.
yield* Effect.gen(function* () {
const now = yield* Clock.currentTimeMillis
yield* Effect.forEach(
yield* rows,
(row) => {
const job = Option.getOrUndefined(decode(row.value))
return !job || expired(job, now) ? kv.remove(row.key) : Effect.void
},
{ discard: true },
)
// A lease outlives its job only when its server stopped after the job finished.
yield* db
.delete(KVTable)
.where(
and(
sql`${KVTable.key} like ${LEASE + "%"}`,
lte(sql`json_extract(${KVTable.value}, '$.until')`, now - Duration.toMillis(RETENTION)),
),
)
.run()
.pipe(Effect.ignore)
}).pipe(
Effect.ignoreCause({ log: "Error", message: "Video record cleanup failed" }),
Effect.repeat(Schedule.spaced(Duration.hours(1))),
Effect.forkScoped,
)
return Service.of({ start, get })
}),
)
// A job that never recorded finishing is treated as finished at its deadline.
function expired(job: Job, now: number) {
const finished =
job.status === "completed" || job.status === "error" ? job.finished : job.created + Duration.toMillis(DEADLINE)
return finished + Duration.toMillis(RETENTION) <= now
}
/** Videos are stored as blobs, which need a local disk that Durable Objects don't have. */
export const unsupportedLayer = Layer.succeed(
Service,
@ -188,5 +370,5 @@ export const unsupportedLayer = Layer.succeed(
export const node = makeGlobalNode({
service: Service,
layer,
deps: [BlobStore.node, Global.node, LocationServiceMap.node],
deps: [BlobStore.node, Database.node, Global.node, KV.node, LocationServiceMap.node],
})

View file

@ -21,11 +21,13 @@ function fakeConsole() {
const state = {
artifacts: true,
watches: true,
blobs: new Set<string>(),
blobs: new Map<string, Uint8Array>(),
blobReads: new Array<string>(),
uploads: new Array<string>(),
prepared: new Array<Record<string, unknown>>(),
published: new Array<{ slug: string; body: Record<string, unknown> }>(),
deleted: new Array<string>(),
gone: false,
}
const server = Bun.serve({
port: 0,
@ -48,9 +50,26 @@ function fakeConsole() {
return Response.json({ missing: body.files.map((file) => file.sha256).filter((sha) => !state.blobs.has(sha)) })
}
if (url.pathname.startsWith("/api/artifacts/blobs/")) {
const bytes = new Uint8Array(await request.arrayBuffer())
state.uploads.push(slug)
state.blobs.add(slug)
return Response.json({ sha256: slug, bytes: (await request.arrayBuffer()).byteLength })
state.blobs.set(slug, bytes)
return Response.json({ sha256: slug, bytes: bytes.byteLength })
}
// Lists the last published revision, inlining only index.html so other files download as blobs.
if (url.pathname.endsWith("/files")) {
if (state.gone) return new Response("Not found", { status: 404 })
const published = state.published.at(-1)?.body as { files: { path: string; sha256: string }[] }
return Response.json({
revision: state.published.length,
files: published.files.map((file) => ({
...file,
...(file.path === "index.html" ? { text: new TextDecoder().decode(state.blobs.get(file.sha256)) } : {}),
})),
})
}
if (url.pathname.includes("/blobs/")) {
state.blobReads.push(`${slug}?${url.searchParams}`)
return new Response(state.blobs.get(slug))
}
if (url.pathname.startsWith("/api/artifacts/") && request.method === "PUT") {
const body = (await request.json()) as Record<string, unknown>
@ -162,6 +181,32 @@ describe("OpencodePlugin artifacts", () => {
),
)
it.effect("reads the files back, downloading the ones Console doesn't inline from the listed revision", () =>
withConsole((console) =>
Effect.gen(function* () {
const artifacts = yield* Artifact.Service
yield* start(console)
const created = yield* artifacts.create({ title: "Report", files })
const content = yield* artifacts.get(created.id)
expect(content.files).toEqual(files)
expect(console.state.blobReads).toEqual([expect.stringMatching(/^[0-9a-f]{64}\?revision=1$/)])
}),
),
)
it.effect("says Console has no such artifact when it was deleted there", () =>
withConsole((console) =>
Effect.gen(function* () {
const artifacts = yield* Artifact.Service
yield* start(console)
const created = yield* artifacts.create({ title: "Report", files })
console.state.gone = true
const error = yield* Effect.flip(artifacts.get(created.id))
expect(String(error)).toContain(`OpenCode Console has no artifact named ${console.state.published[0]?.slug}`)
}),
),
)
it.effect("gives two artifacts with one title their own Console artifacts", () =>
withConsole((console) =>
Effect.gen(function* () {

View file

@ -72,6 +72,14 @@ test("execute describes invariant Code Mode behavior", () => {
)
})
test("with full_codemode, execute names Bun's file APIs instead of ruling out filesystem access", () => {
const description = createCodeMode(new Map(), allowAll, codeModeServices(process.cwd())).description
expect(description).toContain(
"`fetch` is available for HTTP requests, and Bun's file APIs (`Bun.file`, `Bun.write`, `Bun.Glob`) for files, in place of Node's `fs`. Imports and timers are unavailable: there is no `setTimeout` or sleep. All other external access goes through `tools`.",
)
expect(description).not.toContain("direct filesystem access")
})
test("canonical execution distinguishes declared, model-only, and raw schema outputs", async () => {
const declared: Info = {
name: "declared",

View file

@ -1,7 +1,6 @@
import fs from "node:fs/promises"
import path from "node:path"
import { expect } from "bun:test"
import { type Duration, Effect, Layer, Stream } from "effect"
import { Effect, Layer, Stream } from "effect"
import { TestClock } from "effect/testing"
import type { VideoStatus } from "@opencode/ai/effect"
import { Database } from "@opencode/core/database/database"
@ -9,6 +8,7 @@ import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
import { Watcher } from "@opencode/core/filesystem/watcher"
import { Generate } from "@opencode/core/generate"
import { BlobStore } from "@opencode/core/blob-store"
import { KV } from "@opencode/core/kv"
import { VideoGeneration } from "@opencode/core/video-generation"
import { LocationServiceMap } from "@opencode/core/location-service-map"
import type { VideoID, VideoJob } from "@opencode/schema/generate"
@ -23,26 +23,21 @@ import { it } from "./lib/effect"
import { eventually } from "./lib/eventually"
const model = Model.Ref.make({ providerID: Provider.ID.make("test"), id: Model.ID.make("video") })
const providerError = (message: string, status?: number) =>
new Generate.ProviderRequestError({ providerID: "test", reason: "provider", message, status })
// The start of an MP4: a `ftyp` box, so its type is read from its bytes.
const mp4 = Uint8Array.from([0, 0, 0, 0x14, ...new TextEncoder().encode("ftypmp42"), 0, 0, 0, 0, 1, 2, 3, 4])
/** A provider the test drives. */
/** A provider the test drives: each submission gets the next remote ID, whose status the test sets. */
const provider = () => ({
status: { status: "running" } as VideoStatus,
/** The videos a finished job returns. */
results: [Stream.make(mp4)] as Stream.Stream<Uint8Array, Generate.Error>[],
start: Effect.succeed({ id: "provider_1" }) as Effect.Effect<{ readonly id: string }, Generate.Error>,
/** Status reads that fail before one succeeds. */
failReads: 0,
submitted: 0,
hang: false,
status: new Map<string, VideoStatus>(),
})
type State = ReturnType<typeof provider>
const app = (dir: string, state: State) =>
AppNodeBuilder.build(
LayerNode.group([VideoGeneration.node, BlobStore.node, Database.node, LocationServiceMap.node]),
LayerNode.group([VideoGeneration.node, BlobStore.node, Database.node, KV.node, LocationServiceMap.node]),
[
Global.node.replace(Global.layerWith({ data: path.join(dir, "data"), config: path.join(dir, "config") })),
Database.node.replace(Database.configured({ path: "opencode.db" })),
@ -58,12 +53,13 @@ const app = (dir: string, state: State) =>
image: () => Effect.die("unused"),
decisions: () => Effect.die("unused"),
video: {
start: () => Effect.suspend(() => state.start),
status: () =>
Effect.suspend(() =>
state.failReads-- > 0 ? Effect.fail(providerError("reset")) : Effect.succeed(state.status),
),
result: () => Effect.sync(() => state.results.map((stream) => ({ mime: "video/mp4", stream }))),
start: () => (state.hang ? Effect.never : Effect.sync(() => ({ id: `remote_${++state.submitted}` }))),
status: (_, remote) => Effect.sync(() => state.status.get(remote) ?? { status: "running" }),
result: () =>
Effect.succeed([
{ mime: "video/mp4", stream: Stream.make(mp4) },
{ mime: "video/mp4", stream: Stream.make(mp4, mp4) },
]),
},
}),
),
@ -73,100 +69,57 @@ const app = (dir: string, state: State) =>
],
)
const settled = (id: VideoID, step: Duration.Input = "5 seconds") =>
const settled = (id: VideoID) =>
eventually(
VideoGeneration.Service.pipe(
Effect.tap(() => TestClock.adjust(step)),
Effect.tap(() => TestClock.adjust("5 seconds")),
Effect.flatMap((generations) => generations.get(id)),
),
(job: VideoJob) => job.status !== "running",
)
const blobs = (dir: string) => path.join(dir, "data", "blobs")
const listed = (dir: string) => Effect.promise(() => fs.readdir(blobs(dir)).catch(() => [] as string[]))
const records = KV.Service.pipe(Effect.flatMap((kv) => kv.scan({ prefix: "video:" })))
it.effect("stores each finished video as a blob, read back after a restart until it's 7 days old", () =>
it.effect("keeps video jobs across restarts and forgets them a day after they finish", () =>
Effect.gen(function* () {
const dir = (yield* tmpdirScoped("opencode-generation-")).path
const state = provider()
state.results = [Stream.make(mp4), Stream.make(mp4, mp4)]
const job = yield* Effect.gen(function* () {
const first = yield* Effect.gen(function* () {
const generations = yield* VideoGeneration.Service
const started = yield* generations.start({ model, prompt: "a cat" })
expect(yield* generations.get(started.id)).toEqual({ id: started.id, status: "running" })
state.status = { status: "completed" }
// A failed status read is retried at the next interval.
state.failReads = 1
const job = yield* settled(started.id)
const done = yield* generations.start({ model, prompt: "a cat" })
const slow = yield* generations.start({ model, prompt: "a snail" })
state.status.set("remote_1", { status: "completed" })
const job = yield* settled(done.id)
if (job.status !== "completed") throw new Error(`expected completed, got ${job.status}`)
expect(job.blobs).toMatchObject([
{ id: `${started.id}_0`, mime: "video/mp4", bytes: mp4.length },
{ id: `${started.id}_1`, mime: "video/mp4", bytes: mp4.length * 2 },
{ mime: "video/mp4", bytes: mp4.length },
{ mime: "video/mp4", bytes: mp4.length * 2 },
])
expect(job.blobs[0].expiresAt).toBeGreaterThan(Date.now() + 6 * 24 * 60 * 60 * 1000)
expect(
new Uint8Array(yield* Effect.promise(() => fs.readFile(path.join(blobs(dir), `${started.id}_0`)))),
).toEqual(mp4)
expect((yield* listed(dir)).toSorted()).toEqual([`${started.id}_0`, `${started.id}_1`])
return job
expect(job.blobs.every((blob) => blob.id.startsWith("blob_"))).toBe(true)
expect(yield* generations.get(slow.id)).toEqual({ id: slow.id, status: "running" })
// A submission the process stops in the middle of.
state.hang = true
yield* generations.start({ model, prompt: "a crab" }).pipe(Effect.forkChild({ startImmediately: true }))
yield* eventually(records, (page) => page.entries.length === 3)
return { job, slow: slow.id }
}).pipe(Effect.provide(app(dir, state)))
yield* Effect.gen(function* () {
const generations = yield* VideoGeneration.Service
// A new process knows nothing of the job, but finds its blobs from its ID.
expect(yield* generations.get(job.id)).toEqual(job)
const old = new Date(Date.now() - 8 * 24 * 60 * 60 * 1000)
yield* Effect.forEach(job.blobs, (blob) =>
Effect.promise(() => fs.utimes(path.join(blobs(dir), blob.id), old, old)),
)
yield* TestClock.adjust("1 hour")
yield* eventually(listed(dir), (files) => files.length === 0)
expect(yield* generations.get(job.id).pipe(Effect.flip)).toMatchObject({ _tag: "VideoGeneration.NotFoundError" })
}).pipe(Effect.provide(app(dir, state)))
}),
)
expect(yield* generations.get(first.job.id)).toEqual(first.job)
const crab = (yield* records).entries
.map((entry) => entry.key.slice("video:".length) as VideoID)
.find((id) => id !== first.job.id && id !== first.slow)!
expect(yield* generations.get(crab)).toMatchObject({ status: "error", reason: "unknown" })
it.effect("keeps none of a job's videos when one of their downloads keeps failing", () =>
Effect.gen(function* () {
const dir = (yield* tmpdirScoped("opencode-generation-fail-")).path
const state = provider()
state.results = [
Stream.make(mp4),
Stream.make(mp4).pipe(Stream.concat(Stream.fail(providerError("connection reset")))),
]
yield* Effect.gen(function* () {
const generations = yield* VideoGeneration.Service
const started = yield* generations.start({ model, prompt: "a bird" })
state.status = { status: "completed" }
expect(yield* settled(started.id, "1 second")).toEqual({
id: started.id,
status: "error",
reason: "failed",
error: "connection reset",
state.status.set("remote_2", { status: "completed" })
expect(yield* settled(first.slow)).toMatchObject({ status: "completed" })
yield* TestClock.adjust("25 hours")
yield* eventually(records, (page) => page.entries.length === 0)
expect(yield* generations.get(first.job.id).pipe(Effect.flip)).toMatchObject({
_tag: "VideoGeneration.NotFoundError",
})
expect(yield* listed(dir)).toEqual([])
}).pipe(Effect.provide(app(dir, state)))
}),
)
it.effect("reports the provider's failure reason, a job past its deadline and a rejected submission", () =>
Effect.gen(function* () {
const dir = (yield* tmpdirScoped("opencode-generation-errors-")).path
const state = provider()
yield* Effect.gen(function* () {
const generations = yield* VideoGeneration.Service
const expired = yield* generations.start({ model, prompt: "a fish" })
state.status = { status: "error", reason: "expired" }
expect(yield* settled(expired.id)).toMatchObject({ status: "error", reason: "expired" })
state.status = { status: "running" }
const slow = yield* generations.start({ model, prompt: "a snail" })
expect(yield* settled(slow.id, "30 minutes")).toMatchObject({ status: "error", reason: "unknown" })
state.start = Effect.fail(providerError("bad", 400))
const rejected = yield* generations.start({ model, prompt: "a crab" }).pipe(Effect.flip)
expect(rejected).toMatchObject({ _tag: "Generate.ProviderRequestError", message: "bad" })
}).pipe(Effect.provide(app(dir, state)))
}),
)

View file

@ -5567,7 +5567,7 @@
}
}
},
"description": "Submit a video job to a video model using the server's base configuration and return its ID once the provider accepted it. The server polls the job and stores the finished video as a blob for 7 days; read the job with GET /api/experimental/generate/video/:id and the video with GET /api/experimental/blob/:id. Behind the video_generate flag. Experimental: may change without compatibility guarantees.",
"description": "Submit a video job to a video model using the server's base configuration and return its ID once the provider accepted it. The server polls the job and stores the finished videos as blobs; read the job with GET /api/experimental/generate/video/:id and the video with GET /api/experimental/blob/:id. Behind the video_generate flag. Experimental: may change without compatibility guarantees.",
"summary": "Create a video generation",
"requestBody": {
"content": {
@ -5655,7 +5655,7 @@
}
}
},
"description": "Read a video job: running, completed with the video's blob, or error with a reason. Jobs are kept in memory, so a server restart forgets them; a finished video's blob stays readable. Behind the video_generate flag. Experimental: may change without compatibility guarantees.",
"description": "Read a video job: running, completed with its videos' blobs, or error with a reason. Jobs survive a server restart, which resumes polling running ones. A job is not found 24 hours after it finished, or once none of its blobs remain. Behind the video_generate flag. Experimental: may change without compatibility guarantees.",
"summary": "Read a video generation"
}
},
@ -12452,7 +12452,7 @@
}
}
},
"description": "Stream a stored blob's bytes, such as a generated video, with single byte Range, ETag and 304 Not Modified support. Blobs are deleted 7 days after they're written. Experimental: may change without compatibility guarantees.",
"description": "Stream a stored blob's bytes, such as a generated video, with single byte Range, ETag and 304 Not Modified support. Blobs are kept until removed. Experimental: may change without compatibility guarantees.",
"summary": "Read a blob"
}
},
@ -16791,7 +16791,8 @@
},
"Blob.ID": {
"type": "string",
"pattern": "^video_[0-9a-f]{12}[0-9A-Za-z]{14}_(0|[1-9][0-9]{0,2})$"
"pattern": "^blob_[0-9a-f]{12}[0-9A-Za-z]{14}$",
"description": "A stored blob, such as a generated video, which outlives the job that made it"
},
"Blob.Info": {
"type": "object",
@ -16804,13 +16805,9 @@
},
"bytes": {
"type": "number"
},
"expiresAt": {
"type": "number",
"description": "Epoch milliseconds after which the blob may be deleted. Read it with GET /api/experimental/blob/:id"
}
},
"required": ["id", "mime", "bytes", "expiresAt"],
"required": ["id", "mime", "bytes"],
"additionalProperties": false
},
"BlobNotFoundErrorEncoded": {
@ -20033,7 +20030,7 @@
"Generate.VideoErrorReason": {
"type": "string",
"enum": ["failed", "cancelled", "expired", "unknown"],
"description": "failed: the provider failed the job. cancelled: the provider cancelled it. expired: the provider expired it. unknown: the provider gave no result in time"
"description": "failed: the provider failed the job. cancelled: the provider cancelled it. expired: the provider expired it. unknown: the provider gave no result in time, or the server stopped while submitting the job"
},
"Generate.VideoID": {
"type": "string",

View file

@ -13,7 +13,7 @@ export const BlobGetEndpoint = HttpApiEndpoint.get("blob.get", "/api/experimenta
identifier: "experimental.blob.get",
summary: "Read a blob",
description:
"Stream a stored blob's bytes, such as a generated video, with single byte Range, ETag and 304 Not Modified support. Blobs are deleted 7 days after they're written. Experimental: may change without compatibility guarantees.",
"Stream a stored blob's bytes, such as a generated video, with single byte Range, ETag and 304 Not Modified support. Blobs are kept until removed. Experimental: may change without compatibility guarantees.",
// The route shares the `server.experimental` group with the persistent PTY prototype; tag it on its own.
transform: (operation) => ({ ...operation, tags: ["experimental"] }),
}),

View file

@ -81,7 +81,7 @@ export const GenerateGroup = HttpApiGroup.make("server.generate")
identifier: "experimental.generate.video.create",
summary: "Create a video generation",
description:
"Submit a video job to a video model using the server's base configuration and return its ID once the provider accepted it. The server polls the job and stores the finished video as a blob for 7 days; read the job with GET /api/experimental/generate/video/:id and the video with GET /api/experimental/blob/:id. Behind the video_generate flag. Experimental: may change without compatibility guarantees.",
"Submit a video job to a video model using the server's base configuration and return its ID once the provider accepted it. The server polls the job and stores the finished videos as blobs; read the job with GET /api/experimental/generate/video/:id and the video with GET /api/experimental/blob/:id. Behind the video_generate flag. Experimental: may change without compatibility guarantees.",
}),
),
)
@ -95,7 +95,7 @@ export const GenerateGroup = HttpApiGroup.make("server.generate")
identifier: "experimental.generate.video.get",
summary: "Read a video generation",
description:
"Read a video job: running, completed with the video's blob, or error with a reason. Jobs are kept in memory, so a server restart forgets them; a finished video's blob stays readable. Behind the video_generate flag. Experimental: may change without compatibility guarantees.",
"Read a video job: running, completed with its videos' blobs, or error with a reason. Jobs survive a server restart, which resumes polling running ones. A job is not found 24 hours after it finished, or once none of its blobs remain. Behind the video_generate flag. Experimental: may change without compatibility guarantees.",
}),
),
)

View file

@ -1,14 +1,20 @@
export * as BlobStore from "./blob-store.js"
import { Schema } from "effect"
import { descending } from "./identifier.js"
import { statics } from "./schema.js"
/**
* The ID of what made the blob and the blob's position among its outputs: `video_<id>_0` is a video job's first
* video. The prefix says what kind of blob it is. Strict, because the server names files after it.
*/
export const ID = Schema.String.check(
Schema.isPattern(/^video_[0-9a-f]{12}[0-9A-Za-z]{14}_(0|[1-9][0-9]{0,2})$/u),
).pipe(Schema.brand("Blob.ID"), Schema.annotate({ identifier: "Blob.ID" }))
// Strict, because the server names files after it.
export const ID = Schema.String.check(Schema.isPattern(/^blob_[0-9a-f]{12}[0-9A-Za-z]{14}$/u)).pipe(
Schema.brand("Blob.ID"),
Schema.annotate({
identifier: "Blob.ID",
description: "A stored blob, such as a generated video, which outlives the job that made it",
}),
statics((schema) => ({
create: () => schema.make("blob_" + descending()),
})),
)
export type ID = typeof ID.Type
export interface Info extends Schema.Schema.Type<typeof Info> {}
@ -16,7 +22,4 @@ export const Info = Schema.Struct({
id: ID,
mime: Schema.String,
bytes: Schema.Finite,
expiresAt: Schema.Finite.annotate({
description: "Epoch milliseconds after which the blob may be deleted. Read it with GET /api/experimental/blob/:id",
}),
}).annotate({ identifier: "Blob.Info" })

View file

@ -131,7 +131,7 @@ export const VideoRequest = Schema.Struct({
export const VideoErrorReason = Schema.Literals(["failed", "cancelled", "expired", "unknown"]).annotate({
identifier: "Generate.VideoErrorReason",
description:
"failed: the provider failed the job. cancelled: the provider cancelled it. expired: the provider expired it. unknown: the provider gave no result in time",
"failed: the provider failed the job. cancelled: the provider cancelled it. expired: the provider expired it. unknown: the provider gave no result in time, or the server stopped while submitting the job",
})
export type VideoErrorReason = typeof VideoErrorReason.Type

View file

@ -19,7 +19,7 @@ export const makeBlobGet = Effect.gen(function* () {
const etag = `"${id}"`
const headers = {
...ContentHeaders.download({ mime: blob.mime }),
"cache-control": "private, max-age=604800, immutable",
"cache-control": "private, max-age=31536000, immutable",
etag,
"accept-ranges": "bytes",
}

View file

@ -79,12 +79,12 @@ it.live("generates a video in the background and serves its blob with Range and
),
(body: { data: Record<string, unknown> }) => body.data.status !== "running",
)
const blob = `${data.id}_0`
expect(completed.data).toEqual({
id: data.id,
status: "completed",
blobs: [{ id: blob, mime: "video/mp4", bytes: 20, expiresAt: expect.any(Number) }],
blobs: [{ id: expect.stringMatching(/^blob_/), mime: "video/mp4", bytes: 20 }],
})
const blob = (completed.data.blobs as { id: string }[])[0].id
const route = `${base}/blob/${blob}`
const full = yield* call(route)
@ -112,7 +112,7 @@ it.live("generates a video in the background and serves its blob with Range and
expect(cached.status).toBe(304)
expect((yield* Effect.promise(() => cached.arrayBuffer())).byteLength).toBe(0)
// A restarted server reads the finished job back from its blobs.
// A restarted server reads the finished job back from its record.
const restarted = yield* serve(dir, true)
const reread = yield* Effect.promise(() => restarted(new Request(`${base}/generate/video/${data.id}`)))
expect(((yield* Effect.promise(() => reread.json())) as { data: unknown }).data).toEqual(completed.data)
@ -124,7 +124,7 @@ it.live("generates a video in the background and serves its blob with Range and
expect((yield* call(`${base}/generate/video/${unknown}`)).status).toBe(404)
// An ID that isn't one never reaches the disk.
expect((yield* call(`${base}/blob/video_..%2F..%2Fsecret`)).status).toBe(400)
expect((yield* call(`${base}/blob/blob_..%2F..%2Fsecret`)).status).toBe(400)
}).pipe(Effect.scoped),
)

View file

@ -72,3 +72,23 @@ story("code block actions sit in the block's top corner over the block's own bac
await page.keyboard.press("Shift+Tab")
await expect(toolbar(block)).toHaveCSS("opacity", "1")
})
// The fill sits over the block's 0.5px border, and one that reaches the hairline paints over it while hovered.
story("the fill behind code block actions stays inside the block's border", async ({ mount, page }) => {
const root = await mount("current-session-code-blocks--long-lines")
const block = root.locator('[data-component="markdown-code"]').nth(2)
const toolbar = block.locator('[data-slot="markdown-code-toolbar"]')
const box = (await block.boundingBox())!
await page.mouse.move(box.x + 40, box.y + box.height / 2)
await expect(toolbar).toHaveCSS("opacity", "1")
const fill = await toolbar.evaluate((element) => {
const bar = element.getBoundingClientRect()
const style = getComputedStyle(element, "::before")
return { top: bar.top + parseFloat(style.top), right: bar.right - parseFloat(style.right) }
})
expect(fill.top - box.y).toBeGreaterThanOrEqual(1)
expect(box.x + box.width - fill.right).toBeGreaterThanOrEqual(1)
})

View file

@ -416,13 +416,14 @@
/* Like the shell output's Copy, the ghost buttons get the block's background behind them, so code under them
doesn't show through. It fades out toward the start and the bottom, so a line it reaches softens instead of
being cut, and stops inside the block's border and rounded corner. */
being cut. It stops a pixel inside the block's 0.5px border and rounded corner: ending flush against the
hairline paints over it once the block sits at a fractional position. */
&::before {
content: "";
position: absolute;
z-index: -1;
inset: -3.5px -3.5px -8px -24px;
border-start-end-radius: 5.5px;
inset: -3px -3px -8px -24px;
border-start-end-radius: 6px;
background: var(--markdown-code-background);
mask-image:
linear-gradient(to right, transparent, #000 24px), linear-gradient(#000 calc(100% - 8px), transparent);

View file

@ -112,16 +112,49 @@
height: 100%;
}
/*
* The backing, the ring and the image composite as one group, and the surface's rounded clip cuts that group once.
* Clipped one by one, each gets its own antialiased corner and the backing shows through the image's corner pixels
* as a lighter fringe. The opaque mask is what makes the media a group.
*/
[data-slot="project-avatar-surface"][data-has-image] {
background: var(--project-avatar-bg);
background: none;
box-shadow: none;
}
[data-slot="project-avatar-surface"] [data-slot="project-avatar-image"] {
[data-slot="project-avatar-surface"] [data-slot="project-avatar-media"] {
position: relative;
display: block;
width: 100%;
height: 100%;
border-radius: inherit;
-webkit-mask-image: linear-gradient(#000, #000);
mask-image: linear-gradient(#000, #000);
}
[data-slot="project-avatar-surface"] [data-slot="project-avatar-media"]::before,
[data-slot="project-avatar-surface"] [data-slot="project-avatar-media"]::after {
content: "";
position: absolute;
inset: 0;
}
/* Square: the group clip is the only rounded edge the backing gets. */
[data-slot="project-avatar-surface"] [data-slot="project-avatar-media"]::before {
background: var(--project-avatar-bg);
}
[data-slot="project-avatar-surface"] [data-slot="project-avatar-media"]::after {
border-radius: inherit;
box-shadow: inset 0 0 0 0.5px var(--project-avatar-border);
}
[data-slot="project-avatar-surface"] [data-slot="project-avatar-image"] {
position: relative;
z-index: 1;
display: block;
width: 100%;
height: 100%;
object-fit: cover;
user-select: none;
-webkit-user-select: none;

View file

@ -195,7 +195,11 @@ export function ProjectAvatar(props: ProjectAvatarProps) {
</Show>
}
>
{(value) => <img src={value()} draggable={false} data-slot="project-avatar-image" />}
{(value) => (
<span data-slot="project-avatar-media">
<img src={value()} draggable={false} data-slot="project-avatar-image" />
</span>
)}
</Show>
<Show when={split.label}>
{(label) => (