diff --git a/AGENTS.md b/AGENTS.md index 0971dbb1c03f..953fd9a6cc1c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,4 +1,5 @@ - After changing the public Protocol or Server `HttpApi`, run `bun run generate` from `packages/client`. Do not edit generated client files directly. +- Put new or uncertain API surface under `/api/experimental/` first, with an `experimental.*` identifier; promote it once clients have used it and the shape has settled. - Keep runtime dependencies directed from Schema to Core and Protocol, then from Core and Protocol to Server. Client runtime code may depend on Schema and Protocol but never Core or Server; `sdk` composes Client, Core, and Server. - This repository does not use Changesets. Do not add `.changeset` files; follow the existing release workflow instead. - The default branch is `dev`. Base branches and worktrees on `origin/dev`, target PRs at `dev`, and diff against `origin/dev` unless told otherwise. diff --git a/packages/app/src/composer/prompt.test.ts b/packages/app/src/composer/prompt.test.ts index 8262ad61346e..af555c5de484 100644 --- a/packages/app/src/composer/prompt.test.ts +++ b/packages/app/src/composer/prompt.test.ts @@ -1,10 +1,39 @@ import { describe, expect, test } from "bun:test" import type { SessionMessageUser } from "@opencode/client/promise" -import { extractPromptContext, extractPromptFromMessage } from "./prompt" +import { extractPromptContext, extractPromptFromMessage, unchangedDraft } from "./prompt" +import { createMemoryComposerState } from "./state" import { buildPromptRequest } from "./request" import { contextItemKey } from "./schema" describe("extractPromptFromMessage", () => { + test("draft restoration guard notices edits and context changes during hydration", () => { + const target = createMemoryComposerState({ prompt: "before" }).capture() + const unchanged = unchangedDraft(target) + expect(unchanged()).toBe(true) + target.set([{ type: "text", content: "typed while loading", start: 0, end: 19 }]) + expect(unchanged()).toBe(false) + const next = unchangedDraft(target) + target.mode.set("shell") + expect(next()).toBe(false) + }) + test("refuses to restore a prompt whose attachments are still references", () => { + const projected: SessionMessageUser = { + id: "msg_original", + type: "user", + text: "keep these", + time: { created: 1 }, + files: [ + { + name: "image.png", + mime: "image/png", + data: "", + source: { type: "uri", uri: "opencode-attachment:ses_test/msg_original/0" }, + }, + ], + } + + expect(() => extractPromptFromMessage(projected)).toThrow("Resolve attachments") + }) test("restores a renamed session and preserves file offsets when resubmitted", () => { const id = "ses_0123456789abcdefghijklmnop" const text = `@session:${id} @a.ts` diff --git a/packages/app/src/composer/prompt.ts b/packages/app/src/composer/prompt.ts index d326c67e05ae..2686b1630bf4 100644 --- a/packages/app/src/composer/prompt.ts +++ b/packages/app/src/composer/prompt.ts @@ -1,6 +1,13 @@ -import type { FileAttachmentPart, ImageAttachmentPart, PathAttachmentPart, Prompt } from "@/composer/state" +import type { + ComposerState, + FileAttachmentPart, + ImageAttachmentPart, + PathAttachmentPart, + Prompt, +} from "@/composer/state" import { createLegacyBlobReference } from "@/runtime/persistence/drafts" import type { SessionMessageUser } from "@opencode/client/promise" +import { AttachmentReference } from "@opencode/client/attachment-reference" import { commentContextItem, readPromptPresentation } from "./comment-note" import { buildPromptRequest } from "./request" import { contextItemKey, type FileContextItem } from "./schema" @@ -65,6 +72,16 @@ function selectionFromFileUrl(url: string): Extract["s // A user message or a pending inbox item: the materialized transcript row shares the inbox payload's shape. export type PromptSource = Pick +/** Check the captured draft again after asynchronous preparation, before replacing it. */ +export function unchangedDraft(target: ReturnType) { + const snapshot = () => + JSON.stringify([target.current(), target.context.items(), target.model.current(), target.mode.current()]) + + const before = snapshot() + + return () => snapshot() === before +} + // Restores the composer content that produced a prompt, losing nothing it carried. File references // without a mention return as context through extractPromptContext; unmentioned agents and skills // return as trailing mentions, and inline files as attachments. @@ -72,6 +89,7 @@ export function extractPromptFromMessage( message: PromptSource, opts?: { directory?: string; attachmentName?: string; sessionTitle?: (id: string) => string | undefined }, ): Prompt { + if (message.files?.some(AttachmentReference.is)) throw new Error("Resolve attachments before restoring a prompt") const presentation = readPromptPresentation(message.metadata) const text = presentation?.displayText ?? message.text const directory = opts?.directory diff --git a/packages/app/src/runtime/server/attachment.test.ts b/packages/app/src/runtime/server/attachment.test.ts new file mode 100644 index 000000000000..1e1ca1b1bf3a --- /dev/null +++ b/packages/app/src/runtime/server/attachment.test.ts @@ -0,0 +1,67 @@ +import { expect, test } from "bun:test" +import type { PromptFileAttachment, SessionMessageUser } from "@opencode/client/promise" +import { createAttachmentReader } from "./attachment" + +const original: SessionMessageUser = { + id: "msg_original", + type: "user", + text: "keep these", + time: { created: 1 }, + files: [{ name: "image.png", mime: "image/png", data: "AQID", source: { type: "inline" } }], +} + +const reference: PromptFileAttachment = { + name: "image.png", + mime: "image/png", + data: "", + source: { type: "uri", uri: "opencode-attachment:ses_test/msg_original/0" }, +} + +test("display, remount and prompt restoration share one original, including offline", async () => { + const response = Promise.withResolvers() + let calls = 0 + + const reader = createAttachmentReader(async () => { + calls++ + + if (calls > 1) throw new Error("offline") + + return response.promise + }) + + const first = reader.file(reference) + const concurrent = reader.file({ ...reference }) + response.resolve(original) + expect(await first).toEqual(original.files![0]) + expect(await concurrent).toEqual(original.files![0]) + expect(await reader.file({ ...reference })).toEqual(original.files![0]) + expect(await reader.hydrate("ses_test", { ...original, files: [reference] })).toEqual(original) + expect(calls).toBe(1) +}) + +test("failed reads retry and resolved entries are LRU-bounded by count and byte size", async () => { + const calls: string[] = [] + + const reader = createAttachmentReader(async ({ messageID }) => { + calls.push(messageID) + + if (calls.length === 1) throw new Error("offline") + + return { ...original, id: messageID, text: messageID === "msg_large" ? "x".repeat(9 * 1024 * 1024) : original.text } + }) + + const read = (messageID: string) => reader.hydrate("ses_test", { ...original, id: messageID, files: [reference] }) + await expect(read("msg_0")).rejects.toThrow("offline") + + for (const index of Array.from({ length: 32 }, (_, index) => index)) await read(`msg_${index}`) + await read("msg_0") // Touch the oldest; the next addition must evict msg_1 instead. + await read("msg_32") + const before = calls.length + await read("msg_0") + expect(calls.length).toBe(before) + await read("msg_1") + expect(calls.length).toBe(before + 1) + await read("msg_large") + await read("msg_large") + expect(calls.filter((id) => id === "msg_large")).toHaveLength(2) +}) diff --git a/packages/app/src/runtime/server/attachment.ts b/packages/app/src/runtime/server/attachment.ts new file mode 100644 index 000000000000..670aaec3eb40 --- /dev/null +++ b/packages/app/src/runtime/server/attachment.ts @@ -0,0 +1,73 @@ +import { AttachmentReference } from "@opencode/client/attachment-reference" +import type { PromptFileAttachment, SessionMessageUser } from "@opencode/client/promise" +import type { ServerApi } from "./api" + +const MAX_MESSAGES = 32 + +const MAX_BYTES = 16 * 1024 * 1024 + +/** One server's original user messages, shared by display, Revert and Fork; bounded by count and bytes. */ +export function createAttachmentReader(read: ServerApi["session"]["message"]["get"]) { + const pending = new Map>() + const resolved = new Map() + let bytes = 0 + + const load = (sessionID: string, messageID: string) => { + const key = `${sessionID}/${messageID}` + const cached = resolved.get(key) + + if (cached) { + resolved.delete(key) + resolved.set(key, cached) + + return Promise.resolve(cached.message) + } + + const existing = pending.get(key) + + if (existing) return existing + + const request = read({ sessionID, messageID }) + .then((message) => { + if (message?.type !== "user" || message.files?.some(AttachmentReference.is)) + throw new Error("Original attachment message is unavailable") + // Count UTF-16 storage conservatively. Oversized originals may be shown but are not retained. + const size = JSON.stringify(message).length * 2 + + if (size <= MAX_BYTES) { + resolved.set(key, { message, bytes: size }) + bytes += size + + for (const [oldest, entry] of resolved) { + if (resolved.size <= MAX_MESSAGES && bytes <= MAX_BYTES) break + bytes -= entry.bytes + resolved.delete(oldest) + } + } + + return message + }) + .finally(() => pending.delete(key)) + + pending.set(key, request) + + return request + } + + return { + /** The message with original attachment bytes, for restoring it into a composer. */ + async hydrate(sessionID: string, message: SessionMessageUser) { + return message.files?.some(AttachmentReference.is) ? load(sessionID, message.id) : message + }, + async file(file: PromptFileAttachment) { + const reference = AttachmentReference.parse(file) + + if (!reference) return file + const original = (await load(reference.sessionID, reference.messageID)).files?.[reference.index] + + if (!original) throw new Error("Original attachment is unavailable") + + return original + }, + } +} diff --git a/packages/app/src/runtime/server/client.tsx b/packages/app/src/runtime/server/client.tsx index ea83db554168..3bf837eefd99 100644 --- a/packages/app/src/runtime/server/client.tsx +++ b/packages/app/src/runtime/server/client.tsx @@ -7,6 +7,7 @@ import { usePlatform } from "@/runtime/platform/platform" import { ServerConnection } from "./registry" import { createRefCountMap } from "@/runtime/server/refcount" import { createRequestQueue } from "@/runtime/server/request-queue" +import { createAttachmentReader } from "./attachment" import { ServerScope } from "@/runtime/server/scope" import { useServer } from "./current" @@ -65,6 +66,7 @@ type ServerSDKBase = { /** The connection the API currently uses, which a managed server's reconnect may replace. */ http: ServerConnection.HttpBase api: ServerApi + attachments: ReturnType pty: ReturnType connection: { status: Accessor @@ -109,6 +111,7 @@ function createServerSdkContextBase(server: ServerConnection.Any, scope: ServerS return { server, scope, + attachments: createAttachmentReader((input) => transport.api.session.message.get(input)), get url() { return transport.url }, diff --git a/packages/app/src/runtime/server/runtime.tsx b/packages/app/src/runtime/server/runtime.tsx index e488f69a20cd..d50396ddb486 100644 --- a/packages/app/src/runtime/server/runtime.tsx +++ b/packages/app/src/runtime/server/runtime.tsx @@ -192,7 +192,8 @@ function createServerController( const sdk = createServerSdkContext(conn, scope) const source = createData({ - api: () => sdk.api, + // Only the timeline store reads attachment references; every other caller gets original bytes. + api: () => ({ ...sdk.api, message: { ...sdk.api.message, list: sdk.api.experimental.session.timeline } }), initialMessageLimit: () => (timelinePreset(settings.general.timelineDetail())?.id === "compact" ? 40 : 20), event: { on: sdk.event.on, diff --git a/packages/app/src/session/commands/fork-dialog.tsx b/packages/app/src/session/commands/fork-dialog.tsx index 6cccb8ebac10..fe84590cfe9c 100644 --- a/packages/app/src/session/commands/fork-dialog.tsx +++ b/packages/app/src/session/commands/fork-dialog.tsx @@ -1,4 +1,4 @@ -import { Component, createMemo, For, Show } from "solid-js" +import { Component, createMemo, For, Show, onCleanup } from "solid-js" import { useNavigate, useParams } from "@solidjs/router" import { useData } from "@/runtime/server/current" import { useComposerState } from "@/composer/persistence" @@ -38,6 +38,11 @@ export const DialogFork: Component = () => { const dialog = useDialog() const language = useLanguage() const server = useServer() + let pending = false + let active = true + onCleanup(() => { + active = false + }) const messages = createMemo((): ForkableMessage[] => { const sessionID = params.id @@ -60,8 +65,8 @@ export const DialogFork: Component = () => { return result.reverse() }) - const handleSelect = (item: ForkableMessage | undefined) => { - if (!item) return + const handleSelect = async (item: ForkableMessage | undefined) => { + if (!item || pending) return const sessionID = params.id @@ -69,30 +74,43 @@ export const DialogFork: Component = () => { const message = data.session.message.get(sessionID, item.id) if (message?.type !== "user") return + const directory = location().directory + pending = true - const restored = extractPromptFromMessage(message, { - directory: location().directory, - attachmentName: language.t("common.attachment"), - sessionTitle: (id) => data.session.get(id)?.title, - }) - - const context = extractPromptContext(message, { directory: location().directory }) - const dir = base64Encode(location().directory) - - serverSDK.api.session - .fork({ sessionID, before: item.id }) - .then((forked) => { - data.session.remember(forked) - dialog.close() - const target = prompt.capture({ dir, id: forked.id }) - target.set(restored) - target.context.replace([...context.comments, ...context.files]) - navigate(sessionHref(server.key, forked.id)) + try { + const original = await serverSDK.attachments.hydrate(sessionID, message).catch(() => { + showToast({ title: language.t("common.requestFailed") }) }) - .catch((cause: unknown) => { - const message = cause instanceof Error ? cause.message : String(cause) - showToast({ title: language.t("common.requestFailed"), description: message }) + + // Closing the dialog while originals load cancels the fork. + if (!original || !active) return + + const restored = extractPromptFromMessage(original, { + directory, + attachmentName: language.t("common.attachment"), + sessionTitle: (id) => data.session.get(id)?.title, }) + + const context = extractPromptContext(original, { directory }) + const dir = base64Encode(directory) + + await serverSDK.api.session + .fork({ sessionID, before: item.id }) + .then((forked) => { + data.session.remember(forked) + dialog.close() + const target = prompt.capture({ dir, id: forked.id }) + target.set(restored) + target.context.replace([...context.comments, ...context.files]) + navigate(sessionHref(server.key, forked.id)) + }) + .catch((cause: unknown) => { + const message = cause instanceof Error ? cause.message : String(cause) + showToast({ title: language.t("common.requestFailed"), description: message }) + }) + } finally { + pending = false + } } const list = useFilteredList({ diff --git a/packages/app/src/session/composer/region.tsx b/packages/app/src/session/composer/region.tsx index cdda0c84c4c4..3f30ff76e2b3 100644 --- a/packages/app/src/session/composer/region.tsx +++ b/packages/app/src/session/composer/region.tsx @@ -231,7 +231,7 @@ export function createActiveSessionRegion(input: { if (!item || item.type === "shell" || item.type === "idle") return if (item.type === "user" && !data.session.input.has(sessionID, item.id)) { - revert.recall(item) + void revert.recall(item) return } diff --git a/packages/app/src/session/revert.ts b/packages/app/src/session/revert.ts index cdedf8d8ccd9..e3a826370b5c 100644 --- a/packages/app/src/session/revert.ts +++ b/packages/app/src/session/revert.ts @@ -5,7 +5,7 @@ import { useServerSDK } from "@/runtime/server/client" import { useWorkspaceLocation } from "@/workspaces/location" import { useLanguage } from "@/runtime/i18n/language" -import { extractPromptContext, extractPromptFromMessage } from "@/composer/prompt" +import { extractPromptContext, extractPromptFromMessage, unchangedDraft } from "@/composer/prompt" import { promptLength } from "@/composer/prompt-parts" import { showToast } from "@/shell/notifications/toast" import type { SessionModel } from "./model" @@ -19,6 +19,7 @@ export function createSessionRevert(input: { const data = useData() const location = useWorkspaceLocation() const language = useLanguage() + let staging = false const request = async (action: () => Promise) => action() @@ -46,35 +47,56 @@ export function createSessionRevert(input: { target.context.replace([...context.comments, ...context.files]) } + // Recheck the draft after every await: typing during hydration or server work must never be + // overwritten by a restore. + const capture = () => { + const owner = input.session.ownership.capture() + const target = prompt.capture() + const unchanged = unchangedDraft(target) + + return { owner, target, current: () => owner.current() && prompt.capture() === target && unchanged() } + } + + const hydrate = (sessionID: string, message: SessionMessageUser) => + server.attachments.hydrate(sessionID, message).catch(() => { + showToast({ title: language.t("common.requestFailed") }) + }) + const stage = async (message: SessionMessageUser, previous: SessionMessageUser | undefined) => { const sessionID = input.session.identity.params.id - if (!sessionID) return - const owner = input.session.ownership.capture() - const target = prompt.capture() + if (!sessionID || staging) return + const { owner, target, current } = capture() + const step = async (action: () => Promise) => (await request(action)) && current() + staging = true - // An undelivered prompt has no history to rewind. Withdraw it like the TUI - // instead of interrupting the work it is waiting behind. - if (data.session.input.has(sessionID, message.id)) { - if (!(await request(() => server.api.session.inbox.cancel({ sessionID, inboxID: message.id })))) return - restore(target, message) - owner.run(() => input.setActiveMessage(previous)) + try { + const original = await hydrate(sessionID, message) - return - } + if (!original || !current()) return + + // An undelivered prompt has no history to rewind. Withdraw it like the TUI + // instead of interrupting the work it is waiting behind. + if (data.session.input.has(sessionID, message.id)) { + if (!(await step(() => server.api.session.inbox.cancel({ sessionID, inboxID: message.id })))) return + restore(target, original) + owner.run(() => input.setActiveMessage(previous)) + + return + } - // Interrupt acknowledges before the execution settles, and staging a busy Session fails. The - // local status can lag the server either way, so always settle first; both are idle no-ops. - // Like the TUI, stop at the first failure instead of waiting on work that was never interrupted. - if (!(await request(() => server.api.session.interrupt({ sessionID })))) return + // Interrupt acknowledges before execution settles, and staging a busy Session fails. + if (!(await step(() => server.api.session.interrupt({ sessionID })))) return - if (!(await request(() => server.api.session.wait({ sessionID })))) return + if (!(await step(() => server.api.session.wait({ sessionID })))) return - if (!(await request(() => server.api.session.revert.stage({ sessionID, messageID: message.id })))) return - // Like the TUI, pending inputs are left alone: the revert hides them, committing it drops them, - // and redo delivers them. - restore(target, message) - owner.run(() => input.setActiveMessage(previous)) + if (!(await step(() => server.api.session.revert.stage({ sessionID, messageID: message.id })))) return + // Pending inputs remain until the revert commits, or redo delivers them. + restore(target, original) + owner.run(() => input.setActiveMessage(previous)) + } finally { + staging = false + } } const to = async (messageID: string) => { @@ -117,7 +139,15 @@ export function createSessionRevert(input: { } /** Puts a sent prompt back in the composer without rewinding the Session. */ - const recall = (message: SessionMessageUser) => restore(prompt.capture(), message) + const recall = async (message: SessionMessageUser) => { + const sessionID = input.session.identity.params.id + + if (!sessionID) return + const { target, current } = capture() + const original = await hydrate(sessionID, message) + + if (original && current()) restore(target, original) + } return { to, undo, redo, recall } } diff --git a/packages/app/src/shell/routes/session-ui-provider.tsx b/packages/app/src/shell/routes/session-ui-provider.tsx index 5f4aea58461f..47fe39068c01 100644 --- a/packages/app/src/shell/routes/session-ui-provider.tsx +++ b/packages/app/src/shell/routes/session-ui-provider.tsx @@ -119,6 +119,8 @@ export function SessionUIProvider( agents={useLocal().agent.visible()} shellRunning={(id) => !!data.shell.get(id)} shellOutput={(input) => serverSDK.api.shell.output(input)} + readAttachment={(file) => serverSDK.attachments.file(file)} + onAttachmentError={() => showToast({ title: language.t("common.requestFailed") })} turnDiff={{ get: (input) => turnDiffs()?.get(input), load: (input) => turnDiffs()?.load(input, () => serverSDK.api.session.diff(input)), diff --git a/packages/client/package.json b/packages/client/package.json index 6e9d08bdbc30..608dff23b9fb 100644 --- a/packages/client/package.json +++ b/packages/client/package.json @@ -18,6 +18,7 @@ "exports": { ".": "./src/promise/index.ts", "./promise": "./src/promise/index.ts", + "./attachment-reference": "./src/attachment-reference.ts", "./promise/api": "./src/promise/api.ts", "./service": "./src/promise/service.ts", "./solid": "./src/solid/index.ts", diff --git a/packages/client/src/attachment-reference.ts b/packages/client/src/attachment-reference.ts new file mode 100644 index 000000000000..42e1ce66582c --- /dev/null +++ b/packages/client/src/attachment-reference.ts @@ -0,0 +1 @@ +export { AttachmentReference } from "@opencode/schema/attachment-reference" diff --git a/packages/client/src/effect/api/api.ts b/packages/client/src/effect/api/api.ts index 414e353f43a4..dfd1d4629f1c 100644 --- a/packages/client/src/effect/api/api.ts +++ b/packages/client/src/effect/api/api.ts @@ -2128,6 +2128,33 @@ export type ExperimentalPersistentPtyConnectTokenOperation = ( input: ExperimentalPersistentPtyConnectTokenInput, ) => Effect.Effect +export type ExperimentalSessionTimelineInput = { + readonly sessionID: Session.ID + readonly limit?: number | undefined + readonly order?: "asc" | "desc" | undefined + readonly cursor?: string | undefined + readonly type?: + | "agent-switched" + | "model-switched" + | "location-switched" + | "user" + | "synthetic" + | "system" + | "skill" + | "shell" + | "assistant" + | "compaction" + | "idle" + | undefined +} +export type ExperimentalSessionTimelineOutput = { + readonly data: ReadonlyArray + readonly cursor: { readonly previous?: string | undefined; readonly next?: string | undefined } +} +export type ExperimentalSessionTimelineOperation = ( + input: ExperimentalSessionTimelineInput, +) => Effect.Effect + export interface ExperimentalApi { readonly persistentPty: { readonly read: ExperimentalPersistentPtyReadOperation @@ -2141,6 +2168,7 @@ export interface ExperimentalApi { readonly remove: ExperimentalPersistentPtyRemoveOperation readonly connectToken: ExperimentalPersistentPtyConnectTokenOperation } + readonly session: { readonly timeline: ExperimentalSessionTimelineOperation } } export type ShellListInput = { readonly location?: { readonly directory?: string | undefined } | undefined } diff --git a/packages/client/src/effect/generated/client.ts b/packages/client/src/effect/generated/client.ts index ce44064b2193..8bd853c895d4 100644 --- a/packages/client/src/effect/generated/client.ts +++ b/packages/client/src/effect/generated/client.ts @@ -238,6 +238,8 @@ import type { ExperimentalPersistentPtyRemoveOutput, ExperimentalPersistentPtyConnectTokenInput, ExperimentalPersistentPtyConnectTokenOutput, + ExperimentalSessionTimelineInput, + ExperimentalSessionTimelineOutput, ShellListInput, ShellListOutput, ShellCreateInput, @@ -1502,6 +1504,15 @@ const EndpointExperimentalPersistentPtyConnectToken = ), ) +const EndpointExperimentalSessionTimeline = + (raw: RawClient["server.experimental"]) => (input: ExperimentalSessionTimelineInput) => + preserveEffect()( + raw["session.timeline"]({ + params: { sessionID: input["sessionID"] }, + query: { limit: input["limit"], order: input["order"], cursor: input["cursor"], type: input["type"] }, + }).pipe(Effect.mapError(mapClientError)), + ) + const adaptGroupExperimental = (raw: RawClient["server.experimental"]) => ({ persistentPty: { read: EndpointExperimentalPersistentPtyRead(raw), @@ -1515,6 +1526,7 @@ const adaptGroupExperimental = (raw: RawClient["server.experimental"]) => ({ remove: EndpointExperimentalPersistentPtyRemove(raw), connectToken: EndpointExperimentalPersistentPtyConnectToken(raw), }, + session: { timeline: EndpointExperimentalSessionTimeline(raw) }, }) const EndpointShellList = (raw: RawClient["server.shell"]) => (input?: ShellListInput) => diff --git a/packages/client/src/promise/generated/client.ts b/packages/client/src/promise/generated/client.ts index 7dcb3c51e9f5..6a3451e82468 100644 --- a/packages/client/src/promise/generated/client.ts +++ b/packages/client/src/promise/generated/client.ts @@ -236,6 +236,8 @@ import type { ExperimentalPersistentPtyRemoveOutput, ExperimentalPersistentPtyConnectTokenInput, ExperimentalPersistentPtyConnectTokenOutput, + ExperimentalSessionTimelineInput, + ExperimentalSessionTimelineOutput, ShellListInput, ShellListOutput, ShellCreateInput, @@ -2036,6 +2038,20 @@ export function make(options: ClientOptions) { requestOptions, ).then((value) => value.data), }, + session: { + timeline: (input: ExperimentalSessionTimelineInput, requestOptions?: RequestOptions) => + request( + { + method: "GET", + path: `/api/experimental/session/${encodeURIComponent(input.sessionID)}/timeline`, + query: { limit: input["limit"], order: input["order"], cursor: input["cursor"], type: input["type"] }, + successStatus: 200, + declaredStatuses: [400, 401, 404, 500], + empty: false, + }, + requestOptions, + ), + }, }, shell: { list: (input?: ShellListInput, requestOptions?: RequestOptions) => diff --git a/packages/client/src/promise/generated/types.ts b/packages/client/src/promise/generated/types.ts index 07acab8c49d4..248462c0a8cb 100644 --- a/packages/client/src/promise/generated/types.ts +++ b/packages/client/src/promise/generated/types.ts @@ -2525,6 +2525,11 @@ export type SessionMessagesResponse = { cursor: { previous?: string | null; next?: string | null } } +export type SessionTimelineResponse = { + data: Array + cursor: { previous?: string | null; next?: string | null } +} + export type SessionEventDurable = | SessionCreated | SessionAgentSelected @@ -5823,6 +5828,84 @@ export type ExperimentalPersistentPtyConnectTokenInput = { export type ExperimentalPersistentPtyConnectTokenOutput = { data: PtyTicketConnectToken }["data"] +export type ExperimentalSessionTimelineInput = { + readonly sessionID: { readonly sessionID: string }["sessionID"] + readonly limit?: { + readonly limit?: number | undefined + readonly order?: "asc" | "desc" | undefined + readonly cursor?: string | undefined + readonly type?: + | "agent-switched" + | "model-switched" + | "location-switched" + | "user" + | "synthetic" + | "system" + | "skill" + | "shell" + | "assistant" + | "compaction" + | "idle" + | undefined + }["limit"] + readonly order?: { + readonly limit?: number | undefined + readonly order?: "asc" | "desc" | undefined + readonly cursor?: string | undefined + readonly type?: + | "agent-switched" + | "model-switched" + | "location-switched" + | "user" + | "synthetic" + | "system" + | "skill" + | "shell" + | "assistant" + | "compaction" + | "idle" + | undefined + }["order"] + readonly cursor?: { + readonly limit?: number | undefined + readonly order?: "asc" | "desc" | undefined + readonly cursor?: string | undefined + readonly type?: + | "agent-switched" + | "model-switched" + | "location-switched" + | "user" + | "synthetic" + | "system" + | "skill" + | "shell" + | "assistant" + | "compaction" + | "idle" + | undefined + }["cursor"] + readonly type?: { + readonly limit?: number | undefined + readonly order?: "asc" | "desc" | undefined + readonly cursor?: string | undefined + readonly type?: + | "agent-switched" + | "model-switched" + | "location-switched" + | "user" + | "synthetic" + | "system" + | "skill" + | "shell" + | "assistant" + | "compaction" + | "idle" + | undefined + }["type"] +} + +export type ExperimentalSessionTimelineOutput = SessionTimelineResponse + export type ShellListInput = { readonly location?: { readonly location?: { readonly directory?: string | undefined } | undefined }["location"] } diff --git a/packages/client/test/promise.test.ts b/packages/client/test/promise.test.ts index bcd6f4ab02c9..007c9083c347 100644 --- a/packages/client/test/promise.test.ts +++ b/packages/client/test/promise.test.ts @@ -51,8 +51,9 @@ test("exposes every standard HTTP API group", () => { expect(Object.keys(client.vcs)).toEqual(["init", "get", "base", "status", "branch", "diff"]) expect(Object.keys(client.pty)).toEqual(["list", "create", "get", "update", "remove", "connect"]) expect(Object.keys(client.pty.connect)).toEqual(["token"]) - expect(Object.keys(client.experimental)).toEqual(["persistentPty"]) + expect(Object.keys(client.experimental)).toEqual(["persistentPty", "session"]) expect(client.experimental.persistentPty.read).toBeFunction() + expect(Object.keys(client.experimental.session)).toEqual(["timeline"]) expect(Object.keys(client.shell)).toEqual(["list", "create", "get", "output", "remove"]) expect(Object.keys(client.project)).toEqual(["list", "update"]) expect(Object.keys(client.worktree)).toEqual(["list", "create", "remove", "refresh"]) diff --git a/packages/core/src/session/store.ts b/packages/core/src/session/store.ts index c9698231bbcf..6d90f34c4590 100644 --- a/packages/core/src/session/store.ts +++ b/packages/core/src/session/store.ts @@ -8,6 +8,7 @@ import { AbsolutePath, PositiveInt, RelativePath } from "@opencode/schema/schema import { Database } from "../database/database.js" import { makeGlobalNode } from "@opencode/util/effect/app-node" import { SessionHistory } from "./history.js" +import { AttachmentReference } from "@opencode/schema/attachment-reference" import { MessageDecodeError } from "./error.js" import { SessionMessage } from "./message.js" import { Session } from "@opencode/schema/session" @@ -45,6 +46,7 @@ export type MessagesInput = { limit?: number order?: "asc" | "desc" type?: SessionMessage.Type + attachments?: "inline" | "reference" cursor?: { id: SessionMessage.ID direction: "previous" | "next" @@ -174,10 +176,27 @@ const layer = Layer.effect( const rows = yield* (input.limit === undefined ? query.all() : query.limit(input.limit).all()).pipe( Effect.orDie, ) - return yield* Effect.forEach( - direction === "previous" ? rows.toReversed() : rows, - SessionHistory.decodeMessageRow, - ) + return yield* Effect.forEach(direction === "previous" ? rows.toReversed() : rows, (row) => { + if (input.attachments !== "reference" || row.type !== "user" || !("files" in row.data)) + return SessionHistory.decodeMessageRow(row) + + return SessionHistory.decodeMessageRow({ + ...row, + data: { + ...row.data, + files: row.data.files?.map((file, index) => + (file.source.type === "inline" && file.data) || + (file.source.type === "uri" && file.source.uri.startsWith("data:")) + ? { + ...file, + data: "", + source: { type: "uri", uri: AttachmentReference.make(input.sessionID, row.id, index) }, + } + : file, + ), + }, + }) + }) }), context: Effect.fn("SessionStore.context")((sessionID) => SessionHistory.load(db, sessionID, "latest")), message: Effect.fn("SessionStore.message")(function* (messageID) { diff --git a/packages/protocol/openapi.json b/packages/protocol/openapi.json index 7fdddfa85d90..3fa14849d45f 100644 --- a/packages/protocol/openapi.json +++ b/packages/protocol/openapi.json @@ -12048,6 +12048,162 @@ "x-websocket": true } }, + "/api/experimental/session/{sessionID}/timeline": { + "get": { + "tags": ["session"], + "operationId": "experimental.session.timeline", + "parameters": [ + { + "name": "sessionID", + "in": "path", + "schema": { + "$ref": "#/components/schemas/Session.ID" + }, + "required": true + }, + { + "name": "limit", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Maximum number of messages to return. When omitted, the endpoint returns its default page size." + }, + "required": false + }, + { + "name": "order", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "string", + "enum": ["asc", "desc"] + }, + { + "type": "null" + } + ], + "description": "Message order for the first page. Use desc for newest first or asc for oldest first." + }, + "required": false + }, + { + "name": "cursor", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "string", + "description": "Opaque pagination cursor returned as cursor.previous or cursor.next in the previous response. Do not combine with order." + }, + { + "type": "null" + } + ] + }, + "required": false + }, + { + "name": "type", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "string", + "enum": [ + "agent-switched", + "model-switched", + "location-switched", + "user", + "synthetic", + "system", + "skill", + "shell", + "assistant", + "compaction", + "idle" + ] + }, + { + "type": "null" + } + ], + "description": "Filter by message type before pagination. When omitted, all message types are returned. Pass the same type when following cursors." + }, + "required": false + } + ], + "security": [], + "responses": { + "200": { + "description": "Messages for display. User attachment bytes are replaced by experimental opencode-attachment:// URIs with empty data; resolve them with session.message.get before display or reuse.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SessionTimelineResponse" + } + } + } + }, + "400": { + "description": "InvalidCursorError | InvalidRequestError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/InvalidCursorErrorEncoded" + }, + { + "$ref": "#/components/schemas/InvalidRequestErrorEncoded" + } + ] + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedErrorEncoded" + } + } + } + }, + "404": { + "description": "SessionNotFoundError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SessionNotFoundErrorEncoded" + } + } + } + }, + "500": { + "description": "UnknownError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnknownErrorEncoded" + } + } + } + } + }, + "description": "Retrieve the same pages as session.message.list, with user attachment bytes replaced by references. Experimental: may change without compatibility guarantees.", + "summary": "Get session timeline" + } + }, "/api/shell": { "get": { "tags": ["shell"], @@ -20917,6 +21073,46 @@ } ] }, + "SessionTimelineResponse": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Session.Message.Info" + } + }, + "cursor": { + "type": "object", + "properties": { + "previous": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "next": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + } + }, + "required": ["data", "cursor"], + "additionalProperties": false, + "description": "Messages for display. User attachment bytes are replaced by experimental opencode-attachment:// URIs with empty data; resolve them with session.message.get before display or reuse." + }, "SessionTransfer.Data": { "type": "object", "properties": { diff --git a/packages/protocol/src/api.ts b/packages/protocol/src/api.ts index 4a7d793a02de..3376ec0ac598 100644 --- a/packages/protocol/src/api.ts +++ b/packages/protocol/src/api.ts @@ -20,7 +20,7 @@ import { PluginGroup } from "./groups/plugin.js" import { ServerGroup } from "./groups/server.js" import { DebugGroup } from "./groups/debug.js" import { makePtyGroup } from "./groups/pty.js" -import { PersistentPtyGroup } from "./groups/persistent-pty.js" +import { ExperimentalGroup } from "./groups/experimental.js" import { ShellGroup } from "./groups/shell.js" import { ReferenceGroup } from "./groups/reference.js" import { Authorization } from "./middleware/authorization.js" @@ -99,7 +99,7 @@ type ApiGroups< | typeof WorktreeGroup | typeof GenerateGroup | typeof VoiceGroup - | typeof PersistentPtyGroup + | typeof ExperimentalGroup | typeof CredentialGroup | LocationGroups | LocationGroup @@ -185,7 +185,7 @@ const makeApiFromGroup = < .add(RpcGroup.middleware(locationMiddleware)) .add(eventGroup) .add(makePtyGroup(locationMiddleware)) - .add(PersistentPtyGroup) + .add(ExperimentalGroup) .add(ShellGroup.middleware(locationMiddleware)) .add(ReferenceGroup.middleware(locationMiddleware)) .add(WorktreeGroup) diff --git a/packages/protocol/src/groups/experimental.ts b/packages/protocol/src/groups/experimental.ts new file mode 100644 index 000000000000..bdf20107d2c9 --- /dev/null +++ b/packages/protocol/src/groups/experimental.ts @@ -0,0 +1,5 @@ +import { SessionTimelineEndpoint } from "./message.js" +import { PersistentPtyGroup } from "./persistent-pty.js" + +/** Every endpoint here is generated under the client's `experimental` namespace. */ +export const ExperimentalGroup = PersistentPtyGroup.add(SessionTimelineEndpoint) diff --git a/packages/protocol/src/groups/message.ts b/packages/protocol/src/groups/message.ts index 7260b3c87da2..f01efc162252 100644 --- a/packages/protocol/src/groups/message.ts +++ b/packages/protocol/src/groups/message.ts @@ -65,18 +65,45 @@ export const PublicSessionMessage = Schema.Union([ SessionMessage.Idle, ]).annotate({ identifier: "Session.Message.Info" }) +const SessionMessagesPage = { + data: Schema.Array(PublicSessionMessage), + cursor: Schema.Struct({ + previous: Schema.String.pipe(Schema.optional), + next: Schema.String.pipe(Schema.optional), + }), +} + +/** Served from the experimental group, so clients reach it as `experimental.session.timeline`. */ +export const SessionTimelineEndpoint = HttpApiEndpoint.get( + "session.timeline", + "/api/experimental/session/:sessionID/timeline", + { + params: { sessionID: Session.ID }, + query: SessionMessagesQuery, + success: Schema.Struct(SessionMessagesPage).annotate({ + identifier: "SessionTimelineResponse", + description: + "Messages for display. User attachment bytes are replaced by experimental opencode-attachment:// URIs with empty data; resolve them with session.message.get before display or reuse.", + }), + error: [InvalidCursorError, SessionNotFoundError, UnknownError], + }, +).annotateMerge( + OpenApi.annotations({ + identifier: "experimental.session.timeline", + summary: "Get session timeline", + description: + "Retrieve the same pages as session.message.list, with user attachment bytes replaced by references. Experimental: may change without compatibility guarantees.", + // The experimental group is titled for persistent PTYs; list this beside the other session routes. + transform: (operation) => ({ ...operation, tags: ["session"] }), + }), +) + export const MessageGroup = HttpApiGroup.make("server.message") .add( HttpApiEndpoint.get("session.messages", "/api/session/:sessionID/message", { params: { sessionID: Session.ID }, query: SessionMessagesQuery, - success: Schema.Struct({ - data: Schema.Array(PublicSessionMessage), - cursor: Schema.Struct({ - previous: Schema.String.pipe(Schema.optional), - next: Schema.String.pipe(Schema.optional), - }), - }).annotate({ identifier: "SessionMessagesResponse" }), + success: Schema.Struct(SessionMessagesPage).annotate({ identifier: "SessionMessagesResponse" }), error: [InvalidCursorError, SessionNotFoundError, UnknownError], }).annotateMerge( OpenApi.annotations({ diff --git a/packages/schema/src/attachment-reference.ts b/packages/schema/src/attachment-reference.ts new file mode 100644 index 000000000000..0d9eeadf444c --- /dev/null +++ b/packages/schema/src/attachment-reference.ts @@ -0,0 +1,23 @@ +export * as AttachmentReference from "./attachment-reference.js" + +import type { FileAttachment } from "./prompt.js" + +const prefix = "opencode-attachment:" + +/** A list-only reference. Single-message reads always return the original attachment. */ +export function is(file: FileAttachment) { + return file.source.type === "uri" && file.source.uri.startsWith(prefix) +} + +export function make(sessionID: string, messageID: string, index: number) { + return `${prefix}${sessionID}/${messageID}/${index}` +} + +export function parse(file: FileAttachment) { + if (file.source.type !== "uri" || !file.source.uri.startsWith(prefix)) return + const match = /^opencode-attachment:(ses[^/]+)\/(msg_[^/]+)\/(\d+)$/.exec(file.source.uri) + + if (!match) throw new Error("Invalid attachment reference") + + return { sessionID: match[1]!, messageID: match[2]!, index: Number(match[3]) } +} diff --git a/packages/schema/test/attachment-reference.test.ts b/packages/schema/test/attachment-reference.test.ts new file mode 100644 index 000000000000..ef1c280a486d --- /dev/null +++ b/packages/schema/test/attachment-reference.test.ts @@ -0,0 +1,16 @@ +import { expect, test } from "bun:test" +import { AttachmentReference } from "../src/attachment-reference.js" + +const file = (uri: string) => + ({ name: "image.png", mime: "image/png", data: "", source: { type: "uri", uri } }) as const + +test("parses references for any Session.ID shape", () => { + for (const sessionID of ["ses_test", "ses01J"]) { + const reference = file(AttachmentReference.make(sessionID, "msg_a", 2)) + + expect(AttachmentReference.is(reference)).toBe(true) + expect(AttachmentReference.parse(reference)).toEqual({ sessionID, messageID: "msg_a", index: 2 }) + } + expect(AttachmentReference.parse(file("file:///image.png"))).toBeUndefined() + expect(() => AttachmentReference.parse(file("opencode-attachment:prj_a/msg_a/0"))).toThrow() +}) diff --git a/packages/server/src/handlers/message.ts b/packages/server/src/handlers/message.ts index 5328c7a98b08..2f1ec2512f97 100644 --- a/packages/server/src/handlers/message.ts +++ b/packages/server/src/handlers/message.ts @@ -4,6 +4,7 @@ import { Effect, Option, Schema } from "effect" import { HttpApiBuilder } from "effect/http-api" import { Api } from "../api" import { InvalidCursorError } from "@opencode/protocol/errors" +import { SessionMessagesQuery } from "@opencode/protocol/groups/message" import { failedMessageDecode, missingSession } from "./session-error" const DefaultMessagesLimit = 50 @@ -25,42 +26,51 @@ const cursor = { }, } +/** Shared by the stable message list and the experimental timeline, which differ only in attachment mode. */ +export const MessageList = Effect.gen(function* () { + const session = yield* Session.Service + + return Effect.fn(function* ( + sessionID: Session.ID, + query: typeof SessionMessagesQuery.Type, + attachments: "inline" | "reference", + ) { + if (query.cursor && query.order !== undefined) + return yield* new InvalidCursorError({ message: "Cursor cannot be combined with order" }) + const decoded = query.cursor + ? (Option.getOrUndefined(cursor.decode(query.cursor)) ?? + (yield* new InvalidCursorError({ message: "Invalid cursor" }))) + : undefined + const order = decoded?.order ?? query.order ?? "desc" + const messages = yield* session + .messages({ + sessionID, + limit: query.limit ?? DefaultMessagesLimit, + order, + type: query.type, + attachments, + cursor: decoded ? { id: decoded.id, direction: decoded.direction } : undefined, + }) + .pipe( + Effect.catchTag("Session.NotFoundError", missingSession), + Effect.catchTag("Session.MessageDecodeError", failedMessageDecode), + ) + const first = messages[0] + const last = messages.at(-1) + return { + data: messages, + cursor: { + previous: first ? cursor.encode(first, order, "previous") : undefined, + next: last ? cursor.encode(last, order, "next") : undefined, + }, + } + }) +}) + export const MessageHandler = HttpApiBuilder.group(Api, "server.message", (handlers) => Effect.gen(function* () { - const session = yield* Session.Service + const list = yield* MessageList - return handlers.handle( - "session.messages", - Effect.fn(function* (ctx) { - if (ctx.query.cursor && ctx.query.order !== undefined) - return yield* new InvalidCursorError({ message: "Cursor cannot be combined with order" }) - const decoded = ctx.query.cursor - ? Option.getOrUndefined(cursor.decode(ctx.query.cursor)) ?? - (yield* new InvalidCursorError({ message: "Invalid cursor" })) - : undefined - const order = decoded?.order ?? ctx.query.order ?? "desc" - const messages = yield* session - .messages({ - sessionID: ctx.params.sessionID, - limit: ctx.query.limit ?? DefaultMessagesLimit, - order, - type: ctx.query.type, - cursor: decoded ? { id: decoded.id, direction: decoded.direction } : undefined, - }) - .pipe( - Effect.catchTag("Session.NotFoundError", missingSession), - Effect.catchTag("Session.MessageDecodeError", failedMessageDecode), - ) - const first = messages[0] - const last = messages.at(-1) - return { - data: messages, - cursor: { - previous: first ? cursor.encode(first, order, "previous") : undefined, - next: last ? cursor.encode(last, order, "next") : undefined, - }, - } - }), - ) + return handlers.handle("session.messages", (ctx) => list(ctx.params.sessionID, ctx.query, "inline")) }), ) diff --git a/packages/server/src/handlers/persistent-pty.ts b/packages/server/src/handlers/persistent-pty.ts index cb452e96e4e2..0a93167eed2b 100644 --- a/packages/server/src/handlers/persistent-pty.ts +++ b/packages/server/src/handlers/persistent-pty.ts @@ -12,6 +12,7 @@ import { HttpApiBuilder, HttpApiSchema } from "effect/http-api" import { Socket } from "effect/socket" import { Api } from "../api" import { CorsConfig, isAllowedRequestOrigin } from "../cors" +import { MessageList } from "./message" import { type Outbound, runPtySocket } from "./pty-socket" export const PersistentPtyHandler = HttpApiBuilder.group(Api, "server.experimental", (handlers) => @@ -19,8 +20,10 @@ export const PersistentPtyHandler = HttpApiBuilder.group(Api, "server.experiment const tickets = yield* PtyTicket.Service const cors = yield* CorsConfig const pty = yield* PersistentPty.Service + const messages = yield* MessageList return handlers + .handle("session.timeline", (ctx) => messages(ctx.params.sessionID, ctx.query, "reference")) .handle( "persistentPty.read", Effect.fn(function* (ctx) { diff --git a/packages/server/test/message.test.ts b/packages/server/test/message.test.ts index 2899f87d03f2..6a5106c9f9c4 100644 --- a/packages/server/test/message.test.ts +++ b/packages/server/test/message.test.ts @@ -6,7 +6,17 @@ import { it } from "../../core/test/lib/effect" import { ServerFetch } from "../src/fetch" const messages: SessionMessageInfo[] = [ - { id: "msg_z", type: "user", text: "First request", time: { created: 300 } }, + { + id: "msg_z", + type: "user", + text: "First request", + time: { created: 300 }, + files: [ + { name: "image.png", data: "AQID", mime: "image/png", source: { type: "inline" } }, + { name: "empty.txt", data: "", mime: "text/plain", source: { type: "inline" } }, + { name: "note.txt", data: "YWJj", mime: "text/plain", source: { type: "uri", uri: "file:///project/note.txt" } }, + ], + }, { id: "msg_assistant", type: "assistant", @@ -89,6 +99,38 @@ it.live("filters message types before paginating in either direction through the }), ) +it.live("keeps attachment bytes on the stable list and references them on the experimental timeline", () => + Effect.gen(function* () { + const fixture = yield* setup + yield* Effect.promise(async () => { + const input = { sessionID: fixture.sessionID, type: "user", limit: 2 } as const + expect((await fixture.api.message.list({ ...input, order: "asc" })).data[0]).toEqual(messages[0]) + const timeline = await fixture.api.experimental.session.timeline({ ...input, order: "asc" }) + expect(timeline.data[0]).toMatchObject({ + id: "msg_z", + text: "First request", + files: [ + { + name: "image.png", + data: "", + mime: "image/png", + source: { type: "uri", uri: `opencode-attachment:${fixture.sessionID}/msg_z/0` }, + }, + { name: "empty.txt", data: "", source: { type: "inline" } }, + { name: "note.txt", data: "YWJj", source: { type: "uri", uri: "file:///project/note.txt" } }, + ], + }) + expect(await fixture.api.session.message.get({ sessionID: fixture.sessionID, messageID: "msg_z" })).toEqual( + messages[0], + ) + if (!timeline.cursor.next) throw new Error("Expected a next cursor") + expect( + (await fixture.api.experimental.session.timeline({ ...input, cursor: timeline.cursor.next })).data, + ).toEqual([messages[5], messages[7]]) + }) + }), +) + it.live("rejects unknown message type filters at the HTTP boundary", () => Effect.gen(function* () { const fixture = yield* setup diff --git a/packages/session-ui/component-tests/session-message-projection.spec.ts b/packages/session-ui/component-tests/session-message-projection.spec.ts index 3f071ea5d252..c4671885094e 100644 --- a/packages/session-ui/component-tests/session-message-projection.spec.ts +++ b/packages/session-ui/component-tests/session-message-projection.spec.ts @@ -262,6 +262,72 @@ story("renders aliased and long custom model notices", async ({ mount, page }) = await expect.poll(() => long.evaluate((element) => element.scrollWidth <= element.clientWidth)).toBe(true) }) +story("hydrates user attachments before preview or opening", async ({ page, mount }) => { + const png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a0WQAAAAASUVORK5CYII=" + const requests: string[] = [] + const release = Promise.withResolvers() + await page.route("**/attachment-fixture/*", async (route) => { + const name = route.request().url().split("/").at(-1)! + requests.push(name) + + if (name === "pixel.png") await release.promise + await route.fulfill({ + json: { + name, + mime: name === "pixel.png" ? "image/png" : "text/plain", + data: name === "pixel.png" ? png : "YWJj", + source: { type: "inline" }, + }, + }) + }) + const view = await mount("attachment-hydration--deferred") + const image = view.getByRole("img", { name: "pixel.png" }) + await expect(image).toHaveAttribute("aria-busy", "true") + await expect(image).toHaveAttribute("draggable", "false") + await expect(view.locator("img")).toHaveCount(0) + await view.getByRole("button", { name: "Replace attachment proxies" }).click() + release.resolve() + await expect(image).toHaveAttribute("src", `data:image/png;base64,${png}`) + await expect(image).toHaveJSProperty("naturalWidth", 1) + expect(requests).toEqual(["pixel.png"]) + await view.locator('[data-component="attachment-card"]').filter({ hasText: "note.txt" }).click() + await expect(view.getByLabel("Opened attachment")).toHaveText("note.txt:YWJj") + await image.click() + await expect(page.getByRole("dialog").getByRole("img")).toHaveAttribute("src", `data:image/png;base64,${png}`) + expect(requests).toEqual(["pixel.png", "note.txt"]) +}) + +story("retries passive attachment failures on re-entry and reports only explicit failures", async ({ page, mount }) => { + const png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a0WQAAAAASUVORK5CYII=" + let images = 0 + await page.route("**/attachment-fixture/*", async (route) => { + const image = route.request().url().endsWith("pixel.png") + + if (image) images++ + + if (!image || images === 1) return route.fulfill({ status: 503, body: "offline" }) + + return route.fulfill({ json: { name: "pixel.png", mime: "image/png", data: png, source: { type: "inline" } } }) + }) + + const failed = page.waitForResponse( + (response) => response.url().endsWith("attachment-fixture/pixel.png") && response.status() === 503, + ) + + const view = await mount("attachment-hydration--deferred") + await failed + const image = view.getByRole("img", { name: "pixel.png" }) + await expect(image).toHaveAttribute("aria-busy", "true") + await view.getByRole("button", { name: "Move image away" }).click() + await expect(image).not.toBeInViewport() + await view.getByRole("button", { name: "Bring image back" }).click() + await expect(image).toHaveAttribute("src", `data:image/png;base64,${png}`) + await expect(view.getByLabel("Attachment errors")).toHaveText("0") + await view.locator('[data-component="attachment-card"]').filter({ hasText: "note.txt" }).click() + await expect(view.getByLabel("Attachment errors")).toHaveText("1") + expect(images).toBe(2) +}) + // Moved from packages/app/e2e/regression/session-timeline-projection.spec.ts story("renders user image, file attachment, file reference, and agent reference", async ({ mount }) => { const timeline = await mount("current-session-timeline-rows--conversation", { args: { scenario: "attachments" } }) diff --git a/packages/session-ui/src/components/message-file.ts b/packages/session-ui/src/components/message-file.ts index 8c72e3a1cf40..b64ec0ba77f3 100644 --- a/packages/session-ui/src/components/message-file.ts +++ b/packages/session-ui/src/components/message-file.ts @@ -1,11 +1,14 @@ import { getFilename } from "@opencode/util/path" import type { PromptFileAttachment } from "@opencode/client/promise" +import { AttachmentReference } from "@opencode/client/attachment-reference" export function attached(file: PromptFileAttachment) { if (file.mention) return false if (file.source.type === "inline") return true + if (AttachmentReference.is(file)) return true + return file.source.uri.startsWith("data:") || file.source.uri.startsWith("blob:") } diff --git a/packages/session-ui/src/context/data.tsx b/packages/session-ui/src/context/data.tsx index fb8ce2521db5..482780ce46d6 100644 --- a/packages/session-ui/src/context/data.tsx +++ b/packages/session-ui/src/context/data.tsx @@ -1,5 +1,6 @@ import type { FileDiffInfo, + PromptFileAttachment, JsonValue, SessionInfo, SessionMessageUser, @@ -63,6 +64,9 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ agents?: boolean shellRunning?: (id: string) => boolean shellOutput?: (input: ShellOutputInput) => Promise + readAttachment?: (file: PromptFileAttachment) => Promise + /** Reports a failed explicit attachment action; passive viewport loads stay silent. */ + onAttachmentError?: () => void turnDiff?: TurnDiffSource onNavigateToSession?: NavigateToSessionFn onSessionHref?: SessionHrefFn @@ -88,6 +92,8 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ sessionHref: props.onSessionHref, shellRunning: props.shellRunning, shellOutput: props.shellOutput, + readAttachment: props.readAttachment, + onAttachmentError: props.onAttachmentError, turnDiff: props.turnDiff, prompt: props.onPrompt, promptMetadata: props.promptMetadata, diff --git a/packages/session-ui/src/message/attachment-hydration.stories.tsx b/packages/session-ui/src/message/attachment-hydration.stories.tsx new file mode 100644 index 000000000000..8c7b9ebc26b4 --- /dev/null +++ b/packages/session-ui/src/message/attachment-hydration.stories.tsx @@ -0,0 +1,79 @@ +import { createStore } from "solid-js/store" +import type { PromptFileAttachment, SessionMessageUser } from "@opencode/client/promise" +import { DataProvider } from "../context/data" +import { CurrentUserMessageDisplay } from "./message-content" + +export default { title: "OpenCode/Conversation/Attachment hydration", id: "attachment-hydration" } + +export const Deferred = { + render: () => { + const message: SessionMessageUser = { + id: "msg_files", + type: "user", + text: "Keep both attachments", + time: { created: 1 }, + files: [ + { + name: "pixel.png", + mime: "image/png", + data: "", + source: { type: "uri", uri: "opencode-attachment:ses_files/msg_files/0" }, + }, + { + name: "note.txt", + mime: "text/plain", + data: "", + source: { type: "uri", uri: "opencode-attachment:ses_files/msg_files/1" }, + }, + ], + } + + const [state, setState] = createStore({ opened: "", errors: 0, away: false, message }) + + return ( + => { + const response = await fetch(`/attachment-fixture/${file.name}`) + + if (!response.ok) throw new Error("Fixture request failed") + + return response.json() + }} + onAttachmentError={() => setState("errors", (value) => value + 1)} + > + {state.opened} + {state.errors} + + +
+ { + setState("opened", `${file.name}:${file.data}`) + }, + }} + /> +
+
+ ) + }, +} diff --git a/packages/session-ui/src/message/message-content.tsx b/packages/session-ui/src/message/message-content.tsx index e46805434787..cb505930fdce 100644 --- a/packages/session-ui/src/message/message-content.tsx +++ b/packages/session-ui/src/message/message-content.tsx @@ -49,6 +49,7 @@ import type { import type { SessionUserActions, SessionUserAttachmentReference, SessionUserComment } from "../actions" import { agentLabel } from "./agent-label" import { attached, typeLabel } from "../components/message-file" +import { AttachmentReference } from "@opencode/client/attachment-reference" export async function writeClipboard(text: string): Promise { const body = typeof document === "undefined" ? undefined : document.body @@ -318,7 +319,6 @@ export function CurrentUserMessageDisplay(props: { run?: UserRun }) { const data = useData() - const dialog = useDialog() const i18n = useI18n() const menu = useMessageMenu() @@ -536,46 +536,7 @@ export function CurrentUserMessageDisplay(props: { )} - - {(file) => { - const url = () => { - const source = file().source - - return source.type === "uri" ? source.uri : `data:${file().mime};base64,${file().data}` - } - - const name = () => file().name ?? i18n.t("ui.message.attachment.alt") - const image = () => file().mime.startsWith("image/") - - return ( - { - const origin = event.currentTarget - dialog.show(() => ) - }} - > - {name()} - - } - > - props.actions?.openAttachment?.(file())} - > - {typeLabel(name(), file().mime, i18n.t("ui.common.file"))} - - - ) - }} - + {(file) => } ) @@ -708,6 +669,130 @@ export function CurrentUserMessageDisplay(props: { ) } +const fileUrl = (file: PromptFileAttachment) => + file.source.type === "uri" ? file.source.uri : `data:${file.mime};base64,${file.data}` + +function UserMessageAttachment(props: { file: PromptFileAttachment; actions?: SessionUserActions }) { + const data = useData() + const dialog = useDialog() + const i18n = useI18n() + + // Keyed by reference URI, so a refetched proxy of the same file neither reloads nor flashes. + const reference = createMemo(() => + AttachmentReference.is(props.file) && props.file.source.type === "uri" ? props.file.source.uri : undefined, + ) + + const [loaded, setLoaded] = createSignal<{ reference: string; file: PromptFileAttachment }>() + + const file = () => { + const key = reference() + + if (!key) return props.file + + return loaded()?.reference === key ? loaded()?.file : undefined + } + + const url = () => { + const value = file() + + return value && fileUrl(value) + } + + const name = () => props.file.name ?? i18n.t("ui.message.attachment.alt") + + const load = async () => { + const current = file() + + if (current) return current + const key = reference()! + + if (!data.readAttachment) throw new Error("Attachment reader is unavailable") + const value = await data.readAttachment(props.file) + + if (reference() === key) setLoaded({ reference: key, file: value }) + + return value + } + + // Explicit clicks that settle after the row unmounts (e.g. a session switch) must not open or report. + let disposed = false + onCleanup(() => { + disposed = true + }) + + const fail = () => { + if (!disposed) data.onAttachmentError?.() + } + + return ( + + createEffect(() => { + if (!reference()) return + + const observer = new IntersectionObserver( + (entries) => { + if (!entries.some((entry) => entry.isIntersecting)) return + // A failed passive load stays observed so leaving and re-entering can retry. + void load() + .then(() => observer.disconnect()) + .catch(() => undefined) + }, + { rootMargin: "200px" }, + ) + + observer.observe(element) + onCleanup(() => observer.disconnect()) + }) + } + onClick={(event) => { + const origin = event.currentTarget + const key = reference() + void load() + .then((value) => { + if (reference() !== key || !origin.isConnected) return + dialog.show(() => ) + }) + .catch(fail) + }} + > + } + > + {(src) => {name()}} + + + } + > + { + const open = props.actions?.openAttachment + + if (!open) return + const key = reference() + void load() + .then((value) => { + if (!disposed && reference() === key) open(value) + }) + .catch(fail) + }} + > + {typeLabel(name(), props.file.mime, i18n.t("ui.common.file"))} + + + ) +} + function CurrentHighlightedText(props: { text: string files: PromptFileAttachment[] diff --git a/services/www/openapi.json b/services/www/openapi.json index 7fdddfa85d90..3fa14849d45f 100644 --- a/services/www/openapi.json +++ b/services/www/openapi.json @@ -12048,6 +12048,162 @@ "x-websocket": true } }, + "/api/experimental/session/{sessionID}/timeline": { + "get": { + "tags": ["session"], + "operationId": "experimental.session.timeline", + "parameters": [ + { + "name": "sessionID", + "in": "path", + "schema": { + "$ref": "#/components/schemas/Session.ID" + }, + "required": true + }, + { + "name": "limit", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Maximum number of messages to return. When omitted, the endpoint returns its default page size." + }, + "required": false + }, + { + "name": "order", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "string", + "enum": ["asc", "desc"] + }, + { + "type": "null" + } + ], + "description": "Message order for the first page. Use desc for newest first or asc for oldest first." + }, + "required": false + }, + { + "name": "cursor", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "string", + "description": "Opaque pagination cursor returned as cursor.previous or cursor.next in the previous response. Do not combine with order." + }, + { + "type": "null" + } + ] + }, + "required": false + }, + { + "name": "type", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "string", + "enum": [ + "agent-switched", + "model-switched", + "location-switched", + "user", + "synthetic", + "system", + "skill", + "shell", + "assistant", + "compaction", + "idle" + ] + }, + { + "type": "null" + } + ], + "description": "Filter by message type before pagination. When omitted, all message types are returned. Pass the same type when following cursors." + }, + "required": false + } + ], + "security": [], + "responses": { + "200": { + "description": "Messages for display. User attachment bytes are replaced by experimental opencode-attachment:// URIs with empty data; resolve them with session.message.get before display or reuse.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SessionTimelineResponse" + } + } + } + }, + "400": { + "description": "InvalidCursorError | InvalidRequestError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/InvalidCursorErrorEncoded" + }, + { + "$ref": "#/components/schemas/InvalidRequestErrorEncoded" + } + ] + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedErrorEncoded" + } + } + } + }, + "404": { + "description": "SessionNotFoundError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SessionNotFoundErrorEncoded" + } + } + } + }, + "500": { + "description": "UnknownError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnknownErrorEncoded" + } + } + } + } + }, + "description": "Retrieve the same pages as session.message.list, with user attachment bytes replaced by references. Experimental: may change without compatibility guarantees.", + "summary": "Get session timeline" + } + }, "/api/shell": { "get": { "tags": ["shell"], @@ -20917,6 +21073,46 @@ } ] }, + "SessionTimelineResponse": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Session.Message.Info" + } + }, + "cursor": { + "type": "object", + "properties": { + "previous": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "next": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + } + }, + "required": ["data", "cursor"], + "additionalProperties": false, + "description": "Messages for display. User attachment bytes are replaced by experimental opencode-attachment:// URIs with empty data; resolve them with session.message.get before display or reuse." + }, "SessionTransfer.Data": { "type": "object", "properties": { diff --git a/services/www/public/openapi.json b/services/www/public/openapi.json index 7fdddfa85d90..3fa14849d45f 100644 --- a/services/www/public/openapi.json +++ b/services/www/public/openapi.json @@ -12048,6 +12048,162 @@ "x-websocket": true } }, + "/api/experimental/session/{sessionID}/timeline": { + "get": { + "tags": ["session"], + "operationId": "experimental.session.timeline", + "parameters": [ + { + "name": "sessionID", + "in": "path", + "schema": { + "$ref": "#/components/schemas/Session.ID" + }, + "required": true + }, + { + "name": "limit", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Maximum number of messages to return. When omitted, the endpoint returns its default page size." + }, + "required": false + }, + { + "name": "order", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "string", + "enum": ["asc", "desc"] + }, + { + "type": "null" + } + ], + "description": "Message order for the first page. Use desc for newest first or asc for oldest first." + }, + "required": false + }, + { + "name": "cursor", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "string", + "description": "Opaque pagination cursor returned as cursor.previous or cursor.next in the previous response. Do not combine with order." + }, + { + "type": "null" + } + ] + }, + "required": false + }, + { + "name": "type", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "string", + "enum": [ + "agent-switched", + "model-switched", + "location-switched", + "user", + "synthetic", + "system", + "skill", + "shell", + "assistant", + "compaction", + "idle" + ] + }, + { + "type": "null" + } + ], + "description": "Filter by message type before pagination. When omitted, all message types are returned. Pass the same type when following cursors." + }, + "required": false + } + ], + "security": [], + "responses": { + "200": { + "description": "Messages for display. User attachment bytes are replaced by experimental opencode-attachment:// URIs with empty data; resolve them with session.message.get before display or reuse.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SessionTimelineResponse" + } + } + } + }, + "400": { + "description": "InvalidCursorError | InvalidRequestError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/InvalidCursorErrorEncoded" + }, + { + "$ref": "#/components/schemas/InvalidRequestErrorEncoded" + } + ] + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedErrorEncoded" + } + } + } + }, + "404": { + "description": "SessionNotFoundError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SessionNotFoundErrorEncoded" + } + } + } + }, + "500": { + "description": "UnknownError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnknownErrorEncoded" + } + } + } + } + }, + "description": "Retrieve the same pages as session.message.list, with user attachment bytes replaced by references. Experimental: may change without compatibility guarantees.", + "summary": "Get session timeline" + } + }, "/api/shell": { "get": { "tags": ["shell"], @@ -20917,6 +21073,46 @@ } ] }, + "SessionTimelineResponse": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Session.Message.Info" + } + }, + "cursor": { + "type": "object", + "properties": { + "previous": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "next": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + } + }, + "required": ["data", "cursor"], + "additionalProperties": false, + "description": "Messages for display. User attachment bytes are replaced by experimental opencode-attachment:// URIs with empty data; resolve them with session.message.get before display or reuse." + }, "SessionTransfer.Data": { "type": "object", "properties": {