mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-29 11:42:17 +00:00
fix(app): take stored media as the media:<hash> refs the server sends
The server sends media:<hash> refs, never route paths, and user files keep their source, so drop the legacy route parsing and the origin fallback.
This commit is contained in:
parent
d5d6f1e079
commit
392fedb748
10 changed files with 40 additions and 73 deletions
|
|
@ -195,7 +195,7 @@ describe("extractPromptFromMessage", () => {
|
|||
])
|
||||
})
|
||||
|
||||
test("restores experimental-media-uri attachments and file:// origins when data and source are omitted", () => {
|
||||
test("restores experimental-media-uri attachments, whose bytes stay on the server", () => {
|
||||
const imageHash = "a".repeat(64)
|
||||
|
||||
const message = {
|
||||
|
|
@ -204,26 +204,27 @@ describe("extractPromptFromMessage", () => {
|
|||
text: "inspect @src/app.ts",
|
||||
files: [
|
||||
{
|
||||
uri: `/api/experimental/media/${imageHash}`,
|
||||
uri: `media:${imageHash}`,
|
||||
mime: "image/png",
|
||||
source: { type: "inline" },
|
||||
width: 640,
|
||||
height: 480,
|
||||
bytes: 4096,
|
||||
name: "screen.png",
|
||||
},
|
||||
{
|
||||
uri: `/api/experimental/media/${"b".repeat(64)}`,
|
||||
uri: `media:${"b".repeat(64)}`,
|
||||
mime: "text/plain",
|
||||
bytes: 128,
|
||||
origin: { type: "uri", uri: "file:///repo/src/app.ts?start=3&end=7" },
|
||||
source: { type: "uri", uri: "file:///repo/src/app.ts?start=3&end=7" },
|
||||
name: "app.ts",
|
||||
mention: { text: "@src/app.ts", start: 8, end: 19 },
|
||||
},
|
||||
{
|
||||
uri: `/api/experimental/media/${"c".repeat(64)}`,
|
||||
uri: `media:${"c".repeat(64)}`,
|
||||
mime: "text/plain",
|
||||
bytes: 256,
|
||||
origin: { type: "uri", uri: "file:///repo/src/context.ts" },
|
||||
source: { type: "uri", uri: "file:///repo/src/context.ts" },
|
||||
name: "context.ts",
|
||||
},
|
||||
],
|
||||
|
|
|
|||
|
|
@ -1,6 +1,5 @@
|
|||
import type { FileAttachmentPart, ImageAttachmentPart, PathAttachmentPart, Prompt } from "@/composer/state"
|
||||
import { createLegacyBlobReference } from "@/runtime/persistence/drafts"
|
||||
import { toMediaRef } from "@/runtime/server/media"
|
||||
import type { PromptAttachment, SessionMessageUser } from "@opencode/client/promise"
|
||||
import { commentContextItem, readPromptPresentation } from "./comment-note"
|
||||
import { buildPromptRequest } from "./request"
|
||||
|
|
@ -95,14 +94,14 @@ export function extractPromptFromMessage(
|
|||
|
||||
for (const file of message.files ?? []) {
|
||||
const mention = file.mention
|
||||
const source = "source" in file ? file.source : file.origin
|
||||
const source = file.source
|
||||
const fileUri = "uri" in file ? file.uri : undefined
|
||||
const fileData = "data" in file ? file.data : undefined
|
||||
const uri =
|
||||
source?.type === "uri"
|
||||
? source.uri
|
||||
: fileUri !== undefined
|
||||
? toMediaRef(fileUri)
|
||||
? fileUri
|
||||
: fileData !== undefined
|
||||
? `data:${file.mime};base64,${fileData}`
|
||||
: ""
|
||||
|
|
@ -197,15 +196,12 @@ export function extractPromptContext(message: PromptSource, opts?: { directory?:
|
|||
)
|
||||
|
||||
const files = (message.files ?? []).flatMap((file): FileContextItem[] => {
|
||||
const source = "source" in file ? file.source : file.origin
|
||||
const source = file.source
|
||||
if (file.mention || source?.type !== "uri" || !source.uri.startsWith("file:")) return []
|
||||
|
||||
if (regenerated.has(source.uri)) return []
|
||||
|
||||
const absolute = decodeFilePath(stripQueryAndHash(stripFileProtocol(source.uri))).replace(
|
||||
/^\/([A-Za-z]:)/,
|
||||
"$1",
|
||||
)
|
||||
const absolute = decodeFilePath(stripQueryAndHash(stripFileProtocol(source.uri))).replace(/^\/([A-Za-z]:)/, "$1")
|
||||
|
||||
return [
|
||||
{
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import type { AsyncStorage } from "@solid-primitives/storage"
|
||||
import { Option, Schema } from "effect"
|
||||
import { mediaHashFromUri, toMediaRef } from "@/runtime/server/media"
|
||||
import { mediaHashFromUri } from "@/runtime/server/media"
|
||||
|
||||
export type BlobReference = { id: string; url: string }
|
||||
|
||||
|
|
@ -330,8 +330,7 @@ export function createDraftStore(driver: Driver, options: { grace?: number } = {
|
|||
// A live reference keeps the id it was created with; publish the id its bytes now live under.
|
||||
const id = aliases.get(blob.id) ?? blob.id
|
||||
const kept = retained.get(id)?.blob
|
||||
const url =
|
||||
typeof blob.url === "string" && !mediaHashFromUri(blob.url) ? blob.url : retained.get(id)?.url
|
||||
const url = typeof blob.url === "string" && !mediaHashFromUri(blob.url) ? blob.url : retained.get(id)?.url
|
||||
|
||||
if (kept) sources.set(id, { blob: async () => kept })
|
||||
else if (url) sources.set(id, { blob: () => fetch(url).then((response) => response.blob()) })
|
||||
|
|
@ -616,7 +615,7 @@ export async function blobDataUrl(blob: BlobReference, mime: string) {
|
|||
const kept = retained.get(aliases.get(blob.id) ?? blob.id)
|
||||
const url = kept ? undefined : await resolveBlobUrl(blob)
|
||||
|
||||
if (!kept && !url && mediaHashFromUri(blob.id)) return toMediaRef(blob.id)
|
||||
if (!kept && !url && mediaHashFromUri(blob.id)) return blob.id
|
||||
if (!kept && !url) throw new Error(`Attachment ${blob.id} has no stored bytes`)
|
||||
const data = kept ? kept.blob : await fetch(url!).then((response) => response.blob())
|
||||
|
||||
|
|
@ -632,7 +631,5 @@ export async function blobDataUrl(blob: BlobReference, mime: string) {
|
|||
}
|
||||
|
||||
export function createLegacyBlobReference(dataUrl: string): BlobReference {
|
||||
const id = toMediaRef(dataUrl)
|
||||
|
||||
return { id, url: id }
|
||||
return { id: dataUrl, url: dataUrl }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import { describe, expect, test } from "bun:test"
|
|||
import { resolveBlobUrl, setMediaBlobLoader } from "../persistence/drafts"
|
||||
import { createApiForServer } from "./api"
|
||||
import { readLocalImage } from "./image"
|
||||
import { createMediaCache, toMediaRef } from "./media"
|
||||
import { createMediaCache } from "./media"
|
||||
|
||||
function setup(
|
||||
respond: (init?: RequestInit) => Response | Promise<Response> = () => new Response(new Uint8Array([0, 127, 255])),
|
||||
|
|
@ -148,15 +148,12 @@ describe("readLocalImage", () => {
|
|||
const hashC = "c".repeat(64)
|
||||
const { api, requests } = setup(() => new Response(new Uint8Array([137, 80, 78, 71])))
|
||||
const cache = createMediaCache(() => api, { maxEntries: 2 })
|
||||
expect(toMediaRef(`/api/experimental/media/${hashA}`)).toBe(`media:${hashA}`)
|
||||
expect(toMediaRef(`media:${hashA}`)).toBe(`media:${hashA}`)
|
||||
expect(toMediaRef("data:image/png;base64,AAAA")).toBe("data:image/png;base64,AAAA")
|
||||
|
||||
try {
|
||||
expect(cache.peek(`media:${hashA}`, "image/png")).toBeUndefined()
|
||||
const [first, second] = await Promise.all([
|
||||
cache.load(`media:${hashA}`, "image/png"),
|
||||
cache.load(`/api/experimental/media/${hashA}`, "image/png"),
|
||||
cache.load(`media:${hashA}`, "image/png"),
|
||||
])
|
||||
|
||||
expect(first).toStartWith("blob:")
|
||||
|
|
|
|||
|
|
@ -1,24 +1,14 @@
|
|||
import type { OpenCodeClient } from "@opencode/client/promise"
|
||||
|
||||
export const MEDIA_REF_SCHEME = "media:"
|
||||
|
||||
export const DEFAULT_MAX_MEDIA_CACHE_ENTRIES = 128
|
||||
|
||||
const MEDIA_REF = /^media:([0-9a-f]{64})$/
|
||||
const MEDIA_URL = /^(?:https?:\/\/[^/?#]+)?\/api\/(?:experimental\/)?media\/([0-9a-f]{64})(?:[?#].*)?$/
|
||||
|
||||
/** The blob hash in a `media:<hash>` ref or a media route path or URL, matching the server's `hashFromUri`. */
|
||||
/** 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) ?? MEDIA_URL.exec(uri))?.[1]
|
||||
}
|
||||
|
||||
/** Drafts keep the URL-neutral `media:<hash>` ref; a fetch URL is built only when the bytes load. */
|
||||
export function toMediaRef(uri: string) {
|
||||
const hash = mediaHashFromUri(uri)
|
||||
|
||||
return hash ? `${MEDIA_REF_SCHEME}${hash}` : uri
|
||||
return MEDIA_REF.exec(uri)?.[1]
|
||||
}
|
||||
|
||||
export type MediaCache = {
|
||||
|
|
|
|||
|
|
@ -78,7 +78,7 @@ describe("queuedPromptAttachments", () => {
|
|||
|
||||
test("undoQueuedPrompt rehydrates media:<hash> attachments before inbox.cancel sweeps the server blob", async () => {
|
||||
const hash = "e".repeat(64)
|
||||
const mediaUri = `/api/experimental/media/${hash}`
|
||||
const mediaUri = `media:${hash}`
|
||||
const pngBase64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="
|
||||
const pngBytes = Uint8Array.from(Buffer.from(pngBase64, "base64"))
|
||||
const blobs = new Map<string, Uint8Array>([[hash, pngBytes]])
|
||||
|
|
@ -91,6 +91,7 @@ describe("queuedPromptAttachments", () => {
|
|||
{
|
||||
uri: mediaUri,
|
||||
mime: "image/png",
|
||||
source: { type: "inline" },
|
||||
width: 1,
|
||||
height: 1,
|
||||
bytes: pngBytes.byteLength,
|
||||
|
|
@ -99,7 +100,6 @@ describe("queuedPromptAttachments", () => {
|
|||
],
|
||||
})
|
||||
|
||||
// The draft keeps the URL-neutral ref, not the route the server sent.
|
||||
expect(extracted.find((part) => part.type === "image")).toMatchObject({
|
||||
blob: { id: `media:${hash}`, url: `media:${hash}` },
|
||||
})
|
||||
|
|
|
|||
|
|
@ -417,9 +417,7 @@ export function queuedPromptAttachments(item: QueuedPrompt): (ImageAttachmentPar
|
|||
id: `${item.id}:file:${index}`,
|
||||
filename: file.name ?? "attachment",
|
||||
mime: file.mime,
|
||||
blob: createLegacyBlobReference(
|
||||
"uri" in file ? file.uri : `data:${file.mime};base64,${file.data}`,
|
||||
),
|
||||
blob: createLegacyBlobReference("uri" in file ? file.uri : `data:${file.mime};base64,${file.data}`),
|
||||
}),
|
||||
),
|
||||
...(readPromptPresentation(item.payload.metadata)?.attachments ?? []).map(
|
||||
|
|
@ -475,14 +473,12 @@ export async function undoQueuedPrompt(input: {
|
|||
// A stored file re-admits by the URI it came from, as the TUI does, so a file:// reference keeps its
|
||||
// provenance (review comment files stay recognizable) instead of turning into an inline snapshot.
|
||||
function storedFileUri(file: QueuedPromptFile) {
|
||||
const source = "source" in file ? file.source : file.origin
|
||||
return source?.type === "uri"
|
||||
? source.uri
|
||||
: ("uri" in file ? file.uri : `data:${file.mime};base64,${file.data}`)
|
||||
const source = file.source
|
||||
return source?.type === "uri" ? source.uri : "uri" in file ? file.uri : `data:${file.mime};base64,${file.data}`
|
||||
}
|
||||
|
||||
function isComposerAttachment(file: QueuedPromptFile) {
|
||||
const source = "source" in file ? file.source : file.origin
|
||||
const source = file.source
|
||||
return !file.mention && (!source || source.type === "inline")
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -89,15 +89,11 @@ export function createActiveSessionRegion(input: {
|
|||
)
|
||||
|
||||
const openAttachment: NonNullable<SessionUserActions["openAttachment"]> = (file) => {
|
||||
const source = "source" in file ? file.source : file.origin
|
||||
const source = file.source
|
||||
const fileData = "data" in file ? file.data : undefined
|
||||
const fileUri = "uri" in file ? file.uri : undefined
|
||||
const inlineUrl =
|
||||
source?.type === "uri"
|
||||
? source.uri
|
||||
: fileData !== undefined
|
||||
? `data:${file.mime};base64,${fileData}`
|
||||
: undefined
|
||||
source?.type === "uri" ? source.uri : fileData !== undefined ? `data:${file.mime};base64,${fileData}` : undefined
|
||||
|
||||
const download = () => {
|
||||
void (
|
||||
|
|
@ -106,15 +102,13 @@ export function createActiveSessionRegion(input: {
|
|||
: fileUri
|
||||
? server.media.load(fileUri, file.mime)
|
||||
: Promise.resolve(undefined)
|
||||
).then(
|
||||
(url) => {
|
||||
if (!url) return
|
||||
const anchor = document.createElement("a")
|
||||
anchor.href = url
|
||||
anchor.download = getFilename(file.name) || "attachment"
|
||||
anchor.click()
|
||||
},
|
||||
)
|
||||
).then((url) => {
|
||||
if (!url) return
|
||||
const anchor = document.createElement("a")
|
||||
anchor.href = url
|
||||
anchor.download = getFilename(file.name) || "attachment"
|
||||
anchor.click()
|
||||
})
|
||||
}
|
||||
|
||||
const path = file.name ?? ""
|
||||
|
|
|
|||
|
|
@ -17,21 +17,21 @@ export function imageAttachmentPlaceholderStyle(input: {
|
|||
"min-width": `${Math.min(input.width, MIN_IMAGE_PLACEHOLDER_PX)}px`,
|
||||
"min-height": `${Math.min(input.height, MIN_IMAGE_PLACEHOLDER_PX)}px`,
|
||||
}),
|
||||
} as const
|
||||
}
|
||||
}
|
||||
|
||||
return input.loaded
|
||||
? undefined
|
||||
: ({
|
||||
: {
|
||||
"min-width": `${MIN_IMAGE_PLACEHOLDER_PX}px`,
|
||||
"min-height": `${MIN_IMAGE_PLACEHOLDER_PX}px`,
|
||||
} as const)
|
||||
}
|
||||
}
|
||||
|
||||
export function attached(file: PromptAttachment) {
|
||||
if (file.mention) return false
|
||||
|
||||
const source = "source" in file ? file.source : file.origin
|
||||
const source = file.source
|
||||
if (!source || source.type === "inline") return true
|
||||
|
||||
return source.uri.startsWith("data:") || source.uri.startsWith("blob:")
|
||||
|
|
|
|||
|
|
@ -342,7 +342,7 @@ export function CurrentUserMessageDisplay(props: {
|
|||
{(file) => {
|
||||
const directUrl = () => {
|
||||
const current = file()
|
||||
const source = "source" in current ? current.source : current.origin
|
||||
const source = current.source
|
||||
|
||||
if (source?.type === "uri") return source.uri
|
||||
|
||||
|
|
@ -593,11 +593,7 @@ export function CurrentUserMessageDisplay(props: {
|
|||
)
|
||||
}
|
||||
|
||||
function CurrentHighlightedText(props: {
|
||||
text: string
|
||||
files: PromptAttachment[]
|
||||
agents: PromptAgentAttachment[]
|
||||
}) {
|
||||
function CurrentHighlightedText(props: { text: string; files: PromptAttachment[]; agents: PromptAgentAttachment[] }) {
|
||||
const segments = createMemo(() => {
|
||||
const references = [
|
||||
...props.files.flatMap((file) =>
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue