Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -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.
Expand Down
31 changes: 30 additions & 1 deletion packages/app/src/composer/prompt.test.ts
Original file line number Diff line number Diff line change
@@ -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`
Expand Down
20 changes: 19 additions & 1 deletion packages/app/src/composer/prompt.ts
Original file line number Diff line number Diff line change
@@ -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"
Expand Down Expand Up @@ -65,13 +72,24 @@ function selectionFromFileUrl(url: string): Extract<Inline, { type: "file" }>["s
// A user message or a pending inbox item: the materialized transcript row shares the inbox payload's shape.
export type PromptSource = Pick<SessionMessageUser, "id" | "text" | "files" | "agents" | "skills" | "metadata">

/** Check the captured draft again after asynchronous preparation, before replacing it. */
export function unchangedDraft(target: ReturnType<ComposerState["capture"]>) {
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.
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
Expand Down
67 changes: 67 additions & 0 deletions packages/app/src/runtime/server/attachment.test.ts
Original file line number Diff line number Diff line change
@@ -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<SessionMessageUser>()
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)
})
73 changes: 73 additions & 0 deletions packages/app/src/runtime/server/attachment.ts
Original file line number Diff line number Diff line change
@@ -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<string, Promise<SessionMessageUser>>()
const resolved = new Map<string, { message: SessionMessageUser; bytes: number }>()
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
},
}
}
3 changes: 3 additions & 0 deletions packages/app/src/runtime/server/client.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down Expand Up @@ -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<typeof createAttachmentReader>
pty: ReturnType<typeof createPtyClient>
connection: {
status: Accessor<ServerConnectionStatus>
Expand Down Expand Up @@ -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
},
Expand Down
3 changes: 2 additions & 1 deletion packages/app/src/runtime/server/runtime.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,8 @@ function createServerController(
const sdk = createServerSdkContext(conn, scope)

const source = createData({
api: () => sdk.api,
// Only the timeline store reads attachment references; every other caller gets original bytes.
api: () => ({ ...sdk.api, message: { ...sdk.api.message, list: sdk.api.experimental.session.timeline } }),
initialMessageLimit: () => (timelinePreset(settings.general.timelineDetail())?.id === "compact" ? 40 : 20),
event: {
on: sdk.event.on,
Expand Down
66 changes: 42 additions & 24 deletions packages/app/src/session/commands/fork-dialog.tsx
Original file line number Diff line number Diff line change
@@ -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"
Expand Down Expand Up @@ -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
Expand All @@ -60,39 +65,52 @@ 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

if (!sessionID) return
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({
Expand Down
2 changes: 1 addition & 1 deletion packages/app/src/session/composer/region.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
Loading
Loading