From f0d2089f34dbadf52cde059a4d615499d5a3ec45 Mon Sep 17 00:00:00 2001 From: Kit Langton Date: Fri, 23 Oct 2026 15:38:32 -0700 Subject: [PATCH 1/4] feat(app): hydrate user attachments on demand --- packages/app/src/composer/prompt.test.ts | 31 +++- packages/app/src/composer/prompt.ts | 20 ++- .../app/src/runtime/server/attachment.test.ts | 67 +++++++ packages/app/src/runtime/server/attachment.ts | 73 ++++++++ packages/app/src/runtime/server/client.tsx | 3 + packages/app/src/runtime/server/runtime.tsx | 9 +- .../app/src/session/commands/fork-dialog.tsx | 66 ++++--- packages/app/src/session/revert.ts | 54 +++--- .../src/shell/routes/session-ui-provider.tsx | 2 + packages/client/package.json | 1 + packages/client/src/attachment-reference.ts | 1 + packages/core/src/session/store.ts | 27 ++- packages/protocol/src/groups/message.ts | 4 + packages/schema/src/attachment-reference.ts | 23 +++ packages/server/test/message.test.ts | 12 +- .../session-message-projection.spec.ts | 66 +++++++ .../session-ui/src/components/message-file.ts | 3 + packages/session-ui/src/context/data.tsx | 6 + .../message/attachment-hydration.stories.tsx | 79 +++++++++ .../src/message/message-content.tsx | 167 +++++++++++++----- 20 files changed, 621 insertions(+), 93 deletions(-) create mode 100644 packages/app/src/runtime/server/attachment.test.ts create mode 100644 packages/app/src/runtime/server/attachment.ts create mode 100644 packages/client/src/attachment-reference.ts create mode 100644 packages/schema/src/attachment-reference.ts create mode 100644 packages/session-ui/src/message/attachment-hydration.stories.tsx 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..6775a76fd248 100644 --- a/packages/app/src/runtime/server/runtime.tsx +++ b/packages/app/src/runtime/server/runtime.tsx @@ -192,7 +192,14 @@ function createServerController( const sdk = createServerSdkContext(conn, scope) const source = createData({ - api: () => sdk.api, + // Only the timeline store opts into references; every other caller gets original bytes. + api: () => ({ + ...sdk.api, + message: { + ...sdk.api.message, + list: (query, options) => sdk.api.message.list({ attachments: "reference", ...query }, options), + }, + }), 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/revert.ts b/packages/app/src/session/revert.ts index cdedf8d8ccd9..b501ece3ae8c 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() @@ -49,32 +50,45 @@ export function createSessionRevert(input: { const stage = async (message: SessionMessageUser, previous: SessionMessageUser | undefined) => { const sessionID = input.session.identity.params.id - if (!sessionID) return + if (!sessionID || staging) return const owner = input.session.ownership.capture() const target = prompt.capture() + const unchanged = unchangedDraft(target) + const current = () => owner.current() && prompt.capture() === target && unchanged() + // Recheck the draft after every await: typing during hydration or server work must never be + // overwritten by this restore. + const step = async (action: () => Promise) => (await request(action)) && current() + staging = true + + try { + const original = await server.attachments.hydrate(sessionID, message).catch(() => { + showToast({ title: language.t("common.requestFailed") }) + }) - // 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)) + if (!original || !current()) return - 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)) - // 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 + return + } - if (!(await request(() => server.api.session.wait({ 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.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.wait({ sessionID })))) return + + 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) => { 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/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/src/groups/message.ts b/packages/protocol/src/groups/message.ts index 7260b3c87da2..2a881b13194a 100644 --- a/packages/protocol/src/groups/message.ts +++ b/packages/protocol/src/groups/message.ts @@ -21,6 +21,10 @@ const MessageTypes = { } satisfies Record export const SessionMessagesQuery = Schema.Struct({ + attachments: Schema.optional(Schema.Literals(["inline", "reference"])).annotate({ + description: + "Defaults to inline. Reference replaces inline user attachment bytes with opencode-attachment: URIs; resolve them with session.message.get before display or reuse. Pass the same mode on each page.", + }), limit: Schema.optional( Schema.NumberFromString.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(1), Schema.isLessThanOrEqualTo(200)), ).annotate({ diff --git a/packages/schema/src/attachment-reference.ts b/packages/schema/src/attachment-reference.ts new file mode 100644 index 000000000000..26544b7bb9ea --- /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/server/test/message.test.ts b/packages/server/test/message.test.ts index 2899f87d03f2..9a5111c8923d 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", 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[] From 976943f4071409bceb4e0d4e210cc59776be194e Mon Sep 17 00:00:00 2001 From: Kit Langton Date: Fri, 23 Oct 2026 15:41:55 -0700 Subject: [PATCH 2/4] feat(protocol): serve attachment references from an experimental timeline route --- AGENTS.md | 1 + packages/app/src/runtime/server/runtime.tsx | 10 +- packages/client/src/effect/api/api.ts | 28 +++ .../client/src/effect/generated/client.ts | 15 +- .../client/src/promise/generated/client.ts | 14 ++ .../client/src/promise/generated/types.ts | 83 ++++++++ packages/protocol/openapi.json | 196 ++++++++++++++++++ packages/protocol/src/groups/message.ts | 39 +++- packages/server/src/handlers/message.ts | 73 ++++--- packages/server/test/message.test.ts | 33 +++ services/www/openapi.json | 196 ++++++++++++++++++ services/www/public/openapi.json | 196 ++++++++++++++++++ 12 files changed, 831 insertions(+), 53 deletions(-) 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/runtime/server/runtime.tsx b/packages/app/src/runtime/server/runtime.tsx index 6775a76fd248..43c7e12b8a2e 100644 --- a/packages/app/src/runtime/server/runtime.tsx +++ b/packages/app/src/runtime/server/runtime.tsx @@ -192,14 +192,8 @@ function createServerController( const sdk = createServerSdkContext(conn, scope) const source = createData({ - // Only the timeline store opts into references; every other caller gets original bytes. - api: () => ({ - ...sdk.api, - message: { - ...sdk.api.message, - list: (query, options) => sdk.api.message.list({ attachments: "reference", ...query }, options), - }, - }), + // Only the timeline store reads attachment references; every other caller gets original bytes. + api: () => ({ ...sdk.api, message: { ...sdk.api.message, list: sdk.api.message.timeline } }), initialMessageLimit: () => (timelinePreset(settings.general.timelineDetail())?.id === "compact" ? 40 : 20), event: { on: sdk.event.on, diff --git a/packages/client/src/effect/api/api.ts b/packages/client/src/effect/api/api.ts index 414e353f43a4..48f9f4f39227 100644 --- a/packages/client/src/effect/api/api.ts +++ b/packages/client/src/effect/api/api.ts @@ -1395,8 +1395,36 @@ export type MessageListOutput = { } export type MessageListOperation = (input: MessageListInput) => Effect.Effect +export type MessageTimelineInput = { + 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 MessageTimelineOutput = { + readonly data: ReadonlyArray + readonly cursor: { readonly previous?: string | undefined; readonly next?: string | undefined } +} +export type MessageTimelineOperation = ( + input: MessageTimelineInput, +) => Effect.Effect + export interface MessageApi { readonly list: MessageListOperation + readonly timeline: MessageTimelineOperation } export type ModelListInput = { 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..c5e7aa27a700 100644 --- a/packages/client/src/effect/generated/client.ts +++ b/packages/client/src/effect/generated/client.ts @@ -109,6 +109,8 @@ import type { SessionViewOutput, MessageListInput, MessageListOutput, + MessageTimelineInput, + MessageTimelineOutput, ModelListInput, ModelListOutput, ModelDefaultInput, @@ -857,7 +859,18 @@ const EndpointMessageList = (raw: RawClient["server.message"]) => (input: Messag }).pipe(Effect.mapError(mapClientError)), ) -const adaptGroupMessage = (raw: RawClient["server.message"]) => ({ list: EndpointMessageList(raw) }) +const EndpointMessageTimeline = (raw: RawClient["server.message"]) => (input: MessageTimelineInput) => + 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 adaptGroupMessage = (raw: RawClient["server.message"]) => ({ + list: EndpointMessageList(raw), + timeline: EndpointMessageTimeline(raw), +}) const EndpointModelList = (raw: RawClient["server.model"]) => (input?: ModelListInput) => preserveEffect()( diff --git a/packages/client/src/promise/generated/client.ts b/packages/client/src/promise/generated/client.ts index 7dcb3c51e9f5..e9bc0aa5bf84 100644 --- a/packages/client/src/promise/generated/client.ts +++ b/packages/client/src/promise/generated/client.ts @@ -103,6 +103,8 @@ import type { SessionViewOutput, MessageListInput, MessageListOutput, + MessageTimelineInput, + MessageTimelineOutput, ModelListInput, ModelListOutput, ModelDefaultInput, @@ -1131,6 +1133,18 @@ export function make(options: ClientOptions) { }, requestOptions, ), + timeline: (input: MessageTimelineInput, 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, + ), }, model: { list: (input?: ModelListInput, requestOptions?: RequestOptions) => diff --git a/packages/client/src/promise/generated/types.ts b/packages/client/src/promise/generated/types.ts index 07acab8c49d4..a469b633e5aa 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 @@ -4961,6 +4966,84 @@ export type MessageListInput = { export type MessageListOutput = SessionMessagesResponse +export type MessageTimelineInput = { + 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 MessageTimelineOutput = SessionTimelineResponse + export type ModelListInput = { readonly location?: { readonly location?: { readonly directory?: string | undefined } | undefined }["location"] } diff --git a/packages/protocol/openapi.json b/packages/protocol/openapi.json index 7fdddfa85d90..4a1cbe6603ec 100644 --- a/packages/protocol/openapi.json +++ b/packages/protocol/openapi.json @@ -5087,6 +5087,162 @@ "summary": "Get session messages" } }, + "/api/experimental/session/{sessionID}/timeline": { + "get": { + "tags": ["session"], + "operationId": "experimental.session.message.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/model": { "get": { "tags": ["model"], @@ -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/groups/message.ts b/packages/protocol/src/groups/message.ts index 2a881b13194a..72335726c496 100644 --- a/packages/protocol/src/groups/message.ts +++ b/packages/protocol/src/groups/message.ts @@ -21,10 +21,6 @@ const MessageTypes = { } satisfies Record export const SessionMessagesQuery = Schema.Struct({ - attachments: Schema.optional(Schema.Literals(["inline", "reference"])).annotate({ - description: - "Defaults to inline. Reference replaces inline user attachment bytes with opencode-attachment: URIs; resolve them with session.message.get before display or reuse. Pass the same mode on each page.", - }), limit: Schema.optional( Schema.NumberFromString.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(1), Schema.isLessThanOrEqualTo(200)), ).annotate({ @@ -69,18 +65,20 @@ 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), + }), +} + 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({ @@ -91,6 +89,25 @@ export const MessageGroup = HttpApiGroup.make("server.message") }), ), ) + .add( + 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.message.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.", + }), + ), + ) .annotateMerge( OpenApi.annotations({ title: "session", diff --git a/packages/server/src/handlers/message.ts b/packages/server/src/handlers/message.ts index 5328c7a98b08..08f43e02c6c2 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 @@ -29,38 +30,44 @@ export const MessageHandler = HttpApiBuilder.group(Api, "server.message", (handl Effect.gen(function* () { const session = yield* Session.Service - 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, - }, - } - }), - ) + const list = 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, + }, + } + }) + + return handlers + .handle("session.messages", (ctx) => list(ctx.params.sessionID, ctx.query, "inline")) + .handle("session.timeline", (ctx) => list(ctx.params.sessionID, ctx.query, "reference")) }), ) diff --git a/packages/server/test/message.test.ts b/packages/server/test/message.test.ts index 9a5111c8923d..4ac20ee48726 100644 --- a/packages/server/test/message.test.ts +++ b/packages/server/test/message.test.ts @@ -99,6 +99,39 @@ 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.message.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.message.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/services/www/openapi.json b/services/www/openapi.json index 7fdddfa85d90..4a1cbe6603ec 100644 --- a/services/www/openapi.json +++ b/services/www/openapi.json @@ -5087,6 +5087,162 @@ "summary": "Get session messages" } }, + "/api/experimental/session/{sessionID}/timeline": { + "get": { + "tags": ["session"], + "operationId": "experimental.session.message.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/model": { "get": { "tags": ["model"], @@ -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..4a1cbe6603ec 100644 --- a/services/www/public/openapi.json +++ b/services/www/public/openapi.json @@ -5087,6 +5087,162 @@ "summary": "Get session messages" } }, + "/api/experimental/session/{sessionID}/timeline": { + "get": { + "tags": ["session"], + "operationId": "experimental.session.message.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/model": { "get": { "tags": ["model"], @@ -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": { From 2164385e53004f783923b4171ac6e6175c479ca3 Mon Sep 17 00:00:00 2001 From: Kit Langton Date: Fri, 23 Oct 2026 15:59:27 -0700 Subject: [PATCH 3/4] fix(app): hydrate attachments before recalling a failed prompt --- packages/app/src/session/composer/region.tsx | 2 +- packages/app/src/session/revert.ts | 36 +++++++++++++------ packages/schema/src/attachment-reference.ts | 2 +- .../schema/test/attachment-reference.test.ts | 16 +++++++++ 4 files changed, 44 insertions(+), 12 deletions(-) create mode 100644 packages/schema/test/attachment-reference.test.ts 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 b501ece3ae8c..e3a826370b5c 100644 --- a/packages/app/src/session/revert.ts +++ b/packages/app/src/session/revert.ts @@ -47,23 +47,31 @@ 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 || staging) return - const owner = input.session.ownership.capture() - const target = prompt.capture() - const unchanged = unchangedDraft(target) - const current = () => owner.current() && prompt.capture() === target && unchanged() - // Recheck the draft after every await: typing during hydration or server work must never be - // overwritten by this restore. + const { owner, target, current } = capture() const step = async
(action: () => Promise) => (await request(action)) && current() staging = true try { - const original = await server.attachments.hydrate(sessionID, message).catch(() => { - showToast({ title: language.t("common.requestFailed") }) - }) + const original = await hydrate(sessionID, message) if (!original || !current()) return @@ -131,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/schema/src/attachment-reference.ts b/packages/schema/src/attachment-reference.ts index 26544b7bb9ea..0d9eeadf444c 100644 --- a/packages/schema/src/attachment-reference.ts +++ b/packages/schema/src/attachment-reference.ts @@ -15,7 +15,7 @@ export function make(sessionID: string, messageID: string, index: number) { 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) + const match = /^opencode-attachment:(ses[^/]+)\/(msg_[^/]+)\/(\d+)$/.exec(file.source.uri) if (!match) throw new Error("Invalid attachment reference") 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() +}) From 34aa36b6086c35b35d51e5788d0e267fb31085ef Mon Sep 17 00:00:00 2001 From: Kit Langton Date: Fri, 23 Oct 2026 18:44:07 -0700 Subject: [PATCH 4/4] refactor(protocol): expose the timeline under the experimental client group --- packages/app/src/runtime/server/runtime.tsx | 2 +- packages/client/src/effect/api/api.ts | 56 ++-- .../client/src/effect/generated/client.ts | 27 +- .../client/src/promise/generated/client.ts | 30 +- .../client/src/promise/generated/types.ts | 156 ++++----- packages/client/test/promise.test.ts | 3 +- packages/protocol/openapi.json | 312 +++++++++--------- packages/protocol/src/api.ts | 6 +- packages/protocol/src/groups/experimental.ts | 5 + packages/protocol/src/groups/message.ts | 44 +-- packages/server/src/handlers/message.ts | 83 ++--- .../server/src/handlers/persistent-pty.ts | 3 + packages/server/test/message.test.ts | 9 +- services/www/openapi.json | 312 +++++++++--------- services/www/public/openapi.json | 312 +++++++++--------- 15 files changed, 689 insertions(+), 671 deletions(-) create mode 100644 packages/protocol/src/groups/experimental.ts diff --git a/packages/app/src/runtime/server/runtime.tsx b/packages/app/src/runtime/server/runtime.tsx index 43c7e12b8a2e..d50396ddb486 100644 --- a/packages/app/src/runtime/server/runtime.tsx +++ b/packages/app/src/runtime/server/runtime.tsx @@ -193,7 +193,7 @@ function createServerController( const source = createData({ // Only the timeline store reads attachment references; every other caller gets original bytes. - api: () => ({ ...sdk.api, message: { ...sdk.api.message, list: sdk.api.message.timeline } }), + 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/client/src/effect/api/api.ts b/packages/client/src/effect/api/api.ts index 48f9f4f39227..dfd1d4629f1c 100644 --- a/packages/client/src/effect/api/api.ts +++ b/packages/client/src/effect/api/api.ts @@ -1395,36 +1395,8 @@ export type MessageListOutput = { } export type MessageListOperation = (input: MessageListInput) => Effect.Effect -export type MessageTimelineInput = { - 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 MessageTimelineOutput = { - readonly data: ReadonlyArray - readonly cursor: { readonly previous?: string | undefined; readonly next?: string | undefined } -} -export type MessageTimelineOperation = ( - input: MessageTimelineInput, -) => Effect.Effect - export interface MessageApi { readonly list: MessageListOperation - readonly timeline: MessageTimelineOperation } export type ModelListInput = { readonly location?: { readonly directory?: string | undefined } | undefined } @@ -2156,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 @@ -2169,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 c5e7aa27a700..8bd853c895d4 100644 --- a/packages/client/src/effect/generated/client.ts +++ b/packages/client/src/effect/generated/client.ts @@ -109,8 +109,6 @@ import type { SessionViewOutput, MessageListInput, MessageListOutput, - MessageTimelineInput, - MessageTimelineOutput, ModelListInput, ModelListOutput, ModelDefaultInput, @@ -240,6 +238,8 @@ import type { ExperimentalPersistentPtyRemoveOutput, ExperimentalPersistentPtyConnectTokenInput, ExperimentalPersistentPtyConnectTokenOutput, + ExperimentalSessionTimelineInput, + ExperimentalSessionTimelineOutput, ShellListInput, ShellListOutput, ShellCreateInput, @@ -859,18 +859,7 @@ const EndpointMessageList = (raw: RawClient["server.message"]) => (input: Messag }).pipe(Effect.mapError(mapClientError)), ) -const EndpointMessageTimeline = (raw: RawClient["server.message"]) => (input: MessageTimelineInput) => - 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 adaptGroupMessage = (raw: RawClient["server.message"]) => ({ - list: EndpointMessageList(raw), - timeline: EndpointMessageTimeline(raw), -}) +const adaptGroupMessage = (raw: RawClient["server.message"]) => ({ list: EndpointMessageList(raw) }) const EndpointModelList = (raw: RawClient["server.model"]) => (input?: ModelListInput) => preserveEffect()( @@ -1515,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), @@ -1528,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 e9bc0aa5bf84..6a3451e82468 100644 --- a/packages/client/src/promise/generated/client.ts +++ b/packages/client/src/promise/generated/client.ts @@ -103,8 +103,6 @@ import type { SessionViewOutput, MessageListInput, MessageListOutput, - MessageTimelineInput, - MessageTimelineOutput, ModelListInput, ModelListOutput, ModelDefaultInput, @@ -238,6 +236,8 @@ import type { ExperimentalPersistentPtyRemoveOutput, ExperimentalPersistentPtyConnectTokenInput, ExperimentalPersistentPtyConnectTokenOutput, + ExperimentalSessionTimelineInput, + ExperimentalSessionTimelineOutput, ShellListInput, ShellListOutput, ShellCreateInput, @@ -1133,18 +1133,6 @@ export function make(options: ClientOptions) { }, requestOptions, ), - timeline: (input: MessageTimelineInput, 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, - ), }, model: { list: (input?: ModelListInput, requestOptions?: RequestOptions) => @@ -2050,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 a469b633e5aa..248462c0a8cb 100644 --- a/packages/client/src/promise/generated/types.ts +++ b/packages/client/src/promise/generated/types.ts @@ -4966,84 +4966,6 @@ export type MessageListInput = { export type MessageListOutput = SessionMessagesResponse -export type MessageTimelineInput = { - 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 MessageTimelineOutput = SessionTimelineResponse - export type ModelListInput = { readonly location?: { readonly location?: { readonly directory?: string | undefined } | undefined }["location"] } @@ -5906,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/protocol/openapi.json b/packages/protocol/openapi.json index 4a1cbe6603ec..3fa14849d45f 100644 --- a/packages/protocol/openapi.json +++ b/packages/protocol/openapi.json @@ -5087,162 +5087,6 @@ "summary": "Get session messages" } }, - "/api/experimental/session/{sessionID}/timeline": { - "get": { - "tags": ["session"], - "operationId": "experimental.session.message.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/model": { "get": { "tags": ["model"], @@ -12204,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"], 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 72335726c496..f01efc162252 100644 --- a/packages/protocol/src/groups/message.ts +++ b/packages/protocol/src/groups/message.ts @@ -73,6 +73,31 @@ const SessionMessagesPage = { }), } +/** 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", { @@ -89,25 +114,6 @@ export const MessageGroup = HttpApiGroup.make("server.message") }), ), ) - .add( - 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.message.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.", - }), - ), - ) .annotateMerge( OpenApi.annotations({ title: "session", diff --git a/packages/server/src/handlers/message.ts b/packages/server/src/handlers/message.ts index 08f43e02c6c2..2f1ec2512f97 100644 --- a/packages/server/src/handlers/message.ts +++ b/packages/server/src/handlers/message.ts @@ -26,48 +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 = 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, - }, - } - }) + const list = yield* MessageList - return handlers - .handle("session.messages", (ctx) => list(ctx.params.sessionID, ctx.query, "inline")) - .handle("session.timeline", (ctx) => list(ctx.params.sessionID, ctx.query, "reference")) + 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 4ac20ee48726..6a5106c9f9c4 100644 --- a/packages/server/test/message.test.ts +++ b/packages/server/test/message.test.ts @@ -105,7 +105,7 @@ it.live("keeps attachment bytes on the stable list and references them on the ex 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.message.timeline({ ...input, order: "asc" }) + const timeline = await fixture.api.experimental.session.timeline({ ...input, order: "asc" }) expect(timeline.data[0]).toMatchObject({ id: "msg_z", text: "First request", @@ -124,10 +124,9 @@ it.live("keeps attachment bytes on the stable list and references them on the ex messages[0], ) if (!timeline.cursor.next) throw new Error("Expected a next cursor") - expect((await fixture.api.message.timeline({ ...input, cursor: timeline.cursor.next })).data).toEqual([ - messages[5], - messages[7], - ]) + expect( + (await fixture.api.experimental.session.timeline({ ...input, cursor: timeline.cursor.next })).data, + ).toEqual([messages[5], messages[7]]) }) }), ) diff --git a/services/www/openapi.json b/services/www/openapi.json index 4a1cbe6603ec..3fa14849d45f 100644 --- a/services/www/openapi.json +++ b/services/www/openapi.json @@ -5087,162 +5087,6 @@ "summary": "Get session messages" } }, - "/api/experimental/session/{sessionID}/timeline": { - "get": { - "tags": ["session"], - "operationId": "experimental.session.message.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/model": { "get": { "tags": ["model"], @@ -12204,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"], diff --git a/services/www/public/openapi.json b/services/www/public/openapi.json index 4a1cbe6603ec..3fa14849d45f 100644 --- a/services/www/public/openapi.json +++ b/services/www/public/openapi.json @@ -5087,162 +5087,6 @@ "summary": "Get session messages" } }, - "/api/experimental/session/{sessionID}/timeline": { - "get": { - "tags": ["session"], - "operationId": "experimental.session.message.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/model": { "get": { "tags": ["model"], @@ -12204,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"],