Skip to content
Merged
50 changes: 2 additions & 48 deletions packages/app/src/runtime/server/api.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,4 @@
import {
OpenCode,
type MessageListInput,
type OpenCodeClient,
type SessionInboxListInput,
type SessionMessageGetInput,
} from "@opencode/client/promise"
import { OpenCode, withMediaRefs, type MediaRequestOptions } from "@opencode/client/promise"
import type { ServerConnection } from "@/runtime/server/registry"
import { decode64 } from "@/runtime/persistence/base64"

Expand All @@ -25,12 +19,8 @@ export function authFromToken(token: string | null) {
}
}

export const MEDIA_URI_CAPABILITY = "experimental-media-uri"

export const CAPABILITIES_HEADER = "X-OpenCode-Capabilities"

/** `mediaRefs: false` reads stored media as inline bytes, for callers such as export that need self-contained messages. */
export type ServerRequestOptions = OpenCode.RequestOptions & { readonly mediaRefs?: false }
export type ServerRequestOptions = MediaRequestOptions

export function createApiForServer(input: { server: ServerConnection.HttpBase; fetch?: typeof globalThis.fetch }) {
return withMediaRefs(
Expand All @@ -48,42 +38,6 @@ export function createApiForServer(input: { server: ServerConnection.HttpBase; f
)
}

/**
* Only the message and inbox reads can return stored media as `media:<hash>` refs, so only they carry the capability.
* A custom header makes a cross-origin request preflighted, which every other request must keep avoiding.
*/
function withMediaRefs(api: OpenCodeClient) {
return {
...api,
message: {
...api.message,
list: (input: MessageListInput, options?: ServerRequestOptions) =>
api.message.list(input, mediaRefOptions(options)),
},
session: {
...api.session,
message: {
...api.session.message,
get: (input: SessionMessageGetInput, options?: ServerRequestOptions) =>
api.session.message.get(input, mediaRefOptions(options)),
},
inbox: {
...api.session.inbox,
list: (input: SessionInboxListInput, options?: ServerRequestOptions) =>
api.session.inbox.list(input, mediaRefOptions(options)),
},
},
}
}

function mediaRefOptions(options: ServerRequestOptions | undefined): OpenCode.RequestOptions | undefined {
if (options?.mediaRefs === false) return options
const headers = new Headers(options?.headers)
headers.set(CAPABILITIES_HEADER, MEDIA_URI_CAPABILITY)

return { ...options, headers }
}

/**
* The server's ranged read of one file, for media elements. They cannot send the Authorization header, and a credential
* never goes in a DOM URL, so a server that needs a password has none: its media downloads through the API instead.
Expand Down
11 changes: 2 additions & 9 deletions packages/app/src/runtime/server/media.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,6 @@
import type { OpenCodeClient } from "@opencode/client/promise"
import { mediaHashFromUri, type OpenCodeClient } from "@opencode/client/promise"

const MEDIA_REF = /^media:([0-9a-f]{64})$/

/** The blob hash in a `media:<hash>` ref, the only form the server sends stored media in. */
export function mediaHashFromUri(uri: string | undefined): string | undefined {
if (!uri) return undefined

return MEDIA_REF.exec(uri)?.[1]
}
export { mediaHashFromUri }

export type MediaCache = {
peek(uri: string, mime?: string): string | undefined
Expand Down
1 change: 1 addition & 0 deletions packages/client/src/promise/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { OpenCode } from "./client.js"

export * from "./generated/index.js"
export { OpenCode } from "./client.js"
export { mediaHashFromUri, withMediaRefs, type MediaRequestOptions } from "./media.js"
export type {
AgentApi,
CommandApi,
Expand Down
57 changes: 57 additions & 0 deletions packages/client/src/promise/media.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import type { make, RequestOptions } from "./client.js"
import type { MessageListInput, SessionInboxListInput, SessionMessageGetInput } from "./generated/types.js"

const MEDIA_URI_CAPABILITY = "experimental-media-uri"

const CAPABILITIES_HEADER = "X-OpenCode-Capabilities"

const MEDIA_REF = /^media:([0-9a-f]{64})$/

/** `mediaRefs: false` reads stored media as inline bytes, for callers such as export that need self-contained messages. */
export type MediaRequestOptions = RequestOptions & { readonly mediaRefs?: false }

/** The blob hash in a `media:<hash>` ref, the only form the server sends stored media in. */
export function mediaHashFromUri(uri: string | undefined): string | undefined {
if (!uri) return undefined

return MEDIA_REF.exec(uri)?.[1]
}

/**
* Opts a client into the experimental `experimental-media-uri` capability: while `experimental.media_blob` is on,
* stored media comes back as `media:<hash>` refs, whose bytes `experimental.media.get` reads.
*
* Only the message and inbox reads can return refs, so only they carry the capability.
* A custom header makes a cross-origin request preflighted, which every other request must keep avoiding.
*/
export function withMediaRefs(api: ReturnType<typeof make>) {
return {
...api,
message: {
...api.message,
list: (input: MessageListInput, options?: MediaRequestOptions) =>
api.message.list(input, mediaRefOptions(options)),
},
session: {
...api.session,
message: {
...api.session.message,
get: (input: SessionMessageGetInput, options?: MediaRequestOptions) =>
api.session.message.get(input, mediaRefOptions(options)),
},
inbox: {
...api.session.inbox,
list: (input: SessionInboxListInput, options?: MediaRequestOptions) =>
api.session.inbox.list(input, mediaRefOptions(options)),
},
},
}
}

function mediaRefOptions(options: MediaRequestOptions | undefined): RequestOptions | undefined {
if (options?.mediaRefs === false) return options
const headers = new Headers(options?.headers)
headers.set(CAPABILITIES_HEADER, MEDIA_URI_CAPABILITY)

return { ...options, headers }
}
51 changes: 51 additions & 0 deletions packages/client/test/media.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { expect, test } from "bun:test"
import { mediaHashFromUri, OpenCode, withMediaRefs } from "../src/promise/index"

test("withMediaRefs asks for media refs on message and inbox reads only", async () => {
const requests: Array<{ path: string; headers: Headers }> = []
const api = withMediaRefs(
OpenCode.make({
baseUrl: "http://localhost:3000",
headers: { Authorization: "Basic secret" },
// SAFETY: the API client only calls fetch with a URL and init, which this stub accepts.
fetch: (async (input: string | URL | Request, init?: RequestInit) => {
requests.push({
path: new URL(input instanceof Request ? input.url : input).pathname,
headers: new Headers(init?.headers),
})
return Response.json({ data: [], cursor: {} })
}) as typeof fetch,
}),
)

await api.message.list({ sessionID: "ses_1" })
await api.message.list({ sessionID: "ses_1" }, { mediaRefs: false })
await api.session.message.get({ sessionID: "ses_1", messageID: "msg_1" })
await api.session.inbox.list({ sessionID: "ses_1" }, { headers: { "X-Trace": "1" } })
await api.session.list()

expect(
requests.map((request) => [
request.path,
request.headers.get("x-opencode-capabilities"),
request.headers.get("authorization"),
]),
).toEqual([
["/api/session/ses_1/message", "experimental-media-uri", "Basic secret"],
["/api/session/ses_1/message", null, "Basic secret"],
["/api/session/ses_1/message/msg_1", "experimental-media-uri", "Basic secret"],
["/api/session/ses_1/inbox", "experimental-media-uri", "Basic secret"],
["/api/session", null, "Basic secret"],
])
expect(requests[3]?.headers.get("x-trace")).toBe("1")
})

test.each([
[`media:${"a".repeat(64)}`, "a".repeat(64)],
[`media:${"A".repeat(64)}`, undefined],
[`media:${"a".repeat(63)}`, undefined],
["data:image/png;base64,AAA", undefined],
[undefined, undefined],
])("mediaHashFromUri(%p)", (uri, hash) => {
expect(mediaHashFromUri(uri)).toBe(hash)
})
16 changes: 8 additions & 8 deletions packages/tui/src/component/dialog-image-preview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { createMemo, createSignal } from "solid-js"
import { Keymap } from "../context/keymap"
import { useTheme } from "../context/theme"
import { DialogHeader, DialogLayout, useDialog } from "../ui/dialog"
import { createMediaSource } from "./media-source"

type ImagePreviewItem = Readonly<{
uri: string
Expand All @@ -14,16 +15,15 @@ export function DialogImagePreview(props: { images: readonly ImagePreviewItem[];
const dimensions = useTerminalDimensions()
const theme = useTheme().surface("dialog")
const [index, setIndex] = createSignal(Math.max(0, Math.min(props.images.length - 1, props.initial)))
const [failed, setFailed] = createSignal(false)
const current = createMemo(() => props.images[index()])
const media = createMediaSource(() => current().uri)
const imageHeight = createMemo(() => Math.max(3, dimensions().height - 8))

dialog.setSize("xlarge")
dialog.setCentered(true)

function move(direction: number) {
if (props.images.length < 2) return
setFailed(false)
setIndex((value) => (value + direction + props.images.length) % props.images.length)
}

Expand Down Expand Up @@ -51,8 +51,8 @@ export function DialogImagePreview(props: { images: readonly ImagePreviewItem[];
},
get children() {
return (
<text fg={failed() ? theme.text.feedback.error.base : theme.text.muted} wrapMode="none" truncate>
{failed() ? "No preview" : (current().mention?.text ?? `Image ${index() + 1}`)}
<text fg={media.failed() ? theme.text.feedback.error.base : theme.text.muted} wrapMode="none" truncate>
{media.failed() ? "No preview" : (current().mention?.text ?? `Image ${index() + 1}`)}
</text>
)
},
Expand All @@ -62,8 +62,8 @@ export function DialogImagePreview(props: { images: readonly ImagePreviewItem[];
<text fg={theme.text.muted} onMouseUp={() => move(-1)}>
{props.images.length > 1 ? "← previous" : ""}
</text>
<text fg={failed() ? theme.text.feedback.error.base : theme.text.muted} wrapMode="none" truncate>
{failed() ? "No preview" : (current().mention?.text ?? `Image ${index() + 1}`)}
<text fg={media.failed() ? theme.text.feedback.error.base : theme.text.muted} wrapMode="none" truncate>
{media.failed() ? "No preview" : (current().mention?.text ?? `Image ${index() + 1}`)}
</text>
<text fg={theme.text.muted} onMouseUp={() => move(1)}>
{props.images.length > 1 ? "next →" : ""}
Expand All @@ -73,12 +73,12 @@ export function DialogImagePreview(props: { images: readonly ImagePreviewItem[];
>
<image
id="prompt-image-viewer-image"
source={current().uri}
source={media.source()}
fit="fit"
protocol="auto"
width="100%"
height={imageHeight()}
onError={() => setFailed(true)}
onError={media.onError}
/>
</DialogLayout>
)
Expand Down
43 changes: 43 additions & 0 deletions packages/tui/src/component/media-source.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { mediaHashFromUri } from "@opencode/client"
import { createEffect, createSignal, on, onCleanup, useContext, type Accessor } from "solid-js"
import { ClientContext } from "../context/client"

/**
* An `<image>` source for a URI that may be a `media:<hash>` ref. A ref reads its bytes from the server once something
* shows it, so images nobody looks at fetch nothing; other URIs pass through. `failed` covers a failed read and, through
* `onError`, a failed decode, until the URI changes.
*/
export function createMediaSource(uri: Accessor<string>) {
// Optional: image dialogs also render outside a connected client, where only plain URIs can load.
const media = useContext(ClientContext)?.media
const [bytes, setBytes] = createSignal(media?.peek(uri()))
const [failed, setFailed] = createSignal(false)

createEffect(
on(uri, (current) => {
setFailed(false)
const cached = media?.peek(current)
setBytes(cached)
if (cached || !mediaHashFromUri(current)) return
if (!media) return setFailed(true)
let active = true
onCleanup(() => {
active = false
})
media.read(current).then(
(result) => {
if (active) setBytes(result)
},
() => {
if (active) setFailed(true)
},
)
}),
)

return {
source: (): string | Uint8Array | undefined => (mediaHashFromUri(uri()) ? bytes() : uri()),
failed,
onError: () => setFailed(true),
}
}
31 changes: 30 additions & 1 deletion packages/tui/src/component/prompt/draft-stash.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import type { PromptInfo } from "../../prompt/history"
import type { WidthMethod } from "@opentui/core"
import { appendPrompt, type PromptInfo } from "../../prompt/history"
import type { PromptRef } from "./index"

// Holds one in-progress draft per tab across Prompt remounts. A draft is
// consumed on take: restoring it moves it out of the stash, so a stale copy
Expand All @@ -16,3 +18,30 @@ export function takeDraft(sessionID: string | undefined) {
export function saveDraft(sessionID: string | undefined, entry: DraftEntry) {
byTab.set(sessionID, entry)
}

const composers = new Map<string | undefined, PromptRef>()

/** Marks a tab's mounted composer as the one {@link appendToSessionPrompt} writes to; returns its unregister. */
export function registerComposer(sessionID: string | undefined, composer: PromptRef) {
composers.set(sessionID, composer)
return () => {
if (composers.get(sessionID) === composer) composers.delete(sessionID)
}
}

/**
* Appends a prompt that comes back after an await (an undo or revert) to a session's composer if one is mounted, else
* to its stashed draft, after anything already typed there. A session view remounts with its tab, so the composer it
* started with may be gone by then. Returns the composer it wrote to.
*/
export function appendToSessionPrompt(sessionID: string, prompt: PromptInfo, widthMethod: WidthMethod) {
const composer = composers.get(sessionID)
if (!composer) {
const draft = takeDraft(sessionID)?.prompt
saveDraft(sessionID, { prompt: draft ? appendPrompt(draft, prompt, widthMethod) : prompt, cursor: Infinity })
return
}
composer.setMode("normal")
composer.set(appendPrompt(composer.current, prompt, widthMethod))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This adds the restored prompt after the composer's current text for every caller. Before, /undo, timeline revert and the message dialog's revert replaced the composer; only the queued-prompt undo added to it. So now pressing undo twice gives A\n\nB (or the same prompt twice), and an unsent draft is kept in front of the undone prompt. This happens even with experimental.media_blob off. I saw it with this PR's fixture: type a draft, press <leader>u twice, and the composer shows the draft plus the undone prompt twice. Could restoreToTab take a replace/append mode, so undo and revert keep replacing (both the mounted composer and the stashed draft) and only the queued-prompt undo adds to the text?

return composer
}
3 changes: 2 additions & 1 deletion packages/tui/src/component/prompt/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ import { expandPromptInputPastedText, realignPromptInputMentions } from "../../p
import { parseSlashHead } from "../../prompt/parse"
import { createStore, produce, unwrap } from "solid-js/store"
import { emptyPrompt, usePromptHistory, type PromptInfo, type PromptPartRef } from "../../prompt/history"
import { saveDraft, takeDraft } from "./draft-stash"
import { registerComposer, saveDraft, takeDraft } from "./draft-stash"
import { Skill } from "@opencode/schema/skill"
import { computePromptTraits } from "../../prompt/traits"
import { expandPastedTextPlaceholders, expandTrackedPastedText } from "../../prompt/part"
Expand Down Expand Up @@ -717,6 +717,7 @@ export function Prompt(props: PromptProps) {
const stashSessionID = props.sessionID

onMount(() => {
onCleanup(registerComposer(stashSessionID, ref))
const saved = takeDraft(stashSessionID)
if (store.prompt.text) return
if (saved && saved.prompt.text) {
Expand Down
Loading
Loading