Skip to content

Commit d257125

Browse files
authored
feat(app): support @mentioning attached prompt media (#68157)
1 parent 5018d7a commit d257125

33 files changed

Lines changed: 1797 additions & 186 deletions

‎packages/app/src/composer/attachments/attachments.ts‎

Lines changed: 92 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { dragOutText, draggingOut } from "@/runtime/platform/drag-out"
55
import { uuid } from "@opencode/util/uuid"
66
import type { ComposerPrompt } from "../types"
77
import type { ImageAttachmentPart, PathAttachmentPart } from "../state"
8+
import { insertAttachmentMention, isAttachment } from "../prompt-parts"
89
import type { AttachmentDestination } from "./destination"
910
import { uploads } from "./uploads"
1011

@@ -42,6 +43,7 @@ export function createComposerAttachments(
4243
focusEditor: () => void
4344
addPart: (part: ComposerPrompt[number]) => boolean
4445
setDraggingType: (type: "image" | "@mention" | null) => void
46+
shouldMentionPaste?: () => boolean
4547
},
4648
) {
4749
const clearDrag = () => {
@@ -61,63 +63,130 @@ export function createComposerAttachments(
6163
const fallbackScope = {}
6264
const scopeOf = (prompt = input.capture()) => prompt.scope ?? fallbackScope
6365

66+
type AddOptions = {
67+
clipboard?: boolean
68+
paste?: boolean
69+
snapshot?: { text: string; cursor: number }
70+
}
71+
72+
const canMentionPaste = (target: NonNullable<ReturnType<typeof capture>>, mime: string, options?: AddOptions) => {
73+
if (!options?.paste || !mime.startsWith("image/")) return false
74+
75+
if (input.shouldMentionPaste && !input.shouldMentionPaste()) return false
76+
77+
if (!options.snapshot) return true
78+
const cursor = target.prompt.cursor() ?? target.cursor
79+
80+
return inlineText(target.prompt.current()) === options.snapshot.text && cursor === options.snapshot.cursor
81+
}
82+
6483
// Media the model reads natively travels inline with the prompt, so its bytes live in the draft
6584
// store. Everything else, including text, reaches the model as a path on the server that its
6685
// tools open; those bytes never enter the store, and never get base64-encoded into the request.
67-
const add = async (file: File, target = capture(), clipboard = false) => {
86+
const add = async (file: File, target = capture(), options?: AddOptions) => {
6887
if (!target) return false
6988
const mime = await attachmentMime(file)
7089
const destination = input.destination()
7190

72-
if (native(mime, destination.input) && file.size <= MAX_INLINE_BYTES) return addInline(file, mime, target, clipboard)
91+
if (native(mime, destination.input) && file.size <= MAX_INLINE_BYTES) return addInline(file, mime, target, options)
7392
const sourcePath = input.getPathForFile?.(file) || undefined
7493

75-
if (destination.local && sourcePath) return addPath(target, { filename: file.name, mime, path: sourcePath })
76-
void stage(file, mime, target, destination)
94+
if (destination.local && sourcePath)
95+
return addPath(target, { filename: file.name, mime, path: sourcePath }, options)
96+
97+
const snapshot = options?.paste
98+
? { text: inlineText(target.prompt.current()), cursor: target.prompt.cursor() ?? target.cursor }
99+
: undefined
100+
101+
void stage(file, mime, target, destination, options ? { ...options, snapshot } : undefined)
77102

78103
return true
79104
}
80105

81-
const addInline = async (file: File, mime: string, target: NonNullable<ReturnType<typeof capture>>, clipboard: boolean) => {
106+
const commitAttachment = (
107+
target: NonNullable<ReturnType<typeof capture>>,
108+
attachment: ImageAttachmentPart | PathAttachmentPart,
109+
options?: AddOptions,
110+
) => {
111+
const next = [...target.prompt.current(), attachment]
112+
const cursor = target.prompt.cursor() ?? target.cursor
113+
114+
if (canMentionPaste(target, attachment.mime, options)) {
115+
const inserted = insertAttachmentMention(next, cursor, attachment)
116+
target.prompt.set(inserted.prompt, inserted.cursor)
117+
118+
return
119+
}
120+
121+
target.prompt.set(next, cursor)
122+
}
123+
124+
const addInline = async (
125+
file: File,
126+
mime: string,
127+
target: NonNullable<ReturnType<typeof capture>>,
128+
options?: AddOptions,
129+
) => {
82130
const blob = input.store ? await input.store(file) : await createBlobReference(file)
83131
const sourcePath = input.getPathForFile?.(file) || undefined
84132

85133
// Native clipboard images arrive with a fresh timestamped filename on every paste, so identical
86134
// clipboard content is matched on bytes alone.
87-
const duplicate = target.prompt
135+
const existing = target.prompt
88136
.current()
89-
.some(
90-
(part) =>
137+
.find(
138+
(part): part is ImageAttachmentPart =>
91139
part.type === "image" &&
92140
part.blob.id === blob.id &&
93141
(sourcePath
94142
? part.sourcePath === sourcePath
95-
: !part.sourcePath && (clipboard || part.filename === file.name)),
143+
: !part.sourcePath && (options?.clipboard || part.filename === file.name)),
96144
)
97145

98-
if (duplicate) {
146+
if (existing) {
147+
if (canMentionPaste(target, existing.mime, options)) {
148+
const cursor = target.prompt.cursor() ?? target.cursor
149+
const inserted = insertAttachmentMention(target.prompt.current(), cursor, existing)
150+
target.prompt.set(inserted.prompt, inserted.cursor)
151+
152+
return true
153+
}
154+
99155
input.duplicate()
100156

101157
return true
102158
}
103159

104160
const attachment: ImageAttachmentPart = { type: "image", id: uuid(), filename: file.name, sourcePath, mime, blob }
105-
target.prompt.set([...target.prompt.current(), attachment], target.cursor)
161+
commitAttachment(target, attachment, options)
106162

107163
return true
108164
}
109165

110166
const addPath = (
111167
target: NonNullable<ReturnType<typeof capture>>,
112168
attachment: Pick<PathAttachmentPart, "filename" | "mime" | "path">,
169+
options?: AddOptions,
113170
) => {
114-
if (target.prompt.current().some((part) => part.type === "path" && part.path === attachment.path)) {
171+
const existing = target.prompt
172+
.current()
173+
.find((part): part is PathAttachmentPart => part.type === "path" && part.path === attachment.path)
174+
175+
if (existing) {
176+
if (canMentionPaste(target, existing.mime, options)) {
177+
const cursor = target.prompt.cursor() ?? target.cursor
178+
const inserted = insertAttachmentMention(target.prompt.current(), cursor, existing)
179+
target.prompt.set(inserted.prompt, inserted.cursor)
180+
181+
return true
182+
}
183+
115184
input.duplicate()
116185

117186
return true
118187
}
119188

120-
target.prompt.set([...target.prompt.current(), { type: "path", id: uuid(), ...attachment }], target.prompt.cursor())
189+
commitAttachment(target, { type: "path", id: uuid(), ...attachment }, options)
121190

122191
return true
123192
}
@@ -127,6 +196,7 @@ export function createComposerAttachments(
127196
mime: string,
128197
target: NonNullable<ReturnType<typeof capture>>,
129198
destination: AttachmentDestination,
199+
options?: AddOptions,
130200
) => {
131201
const path = await uploads
132202
.track(
@@ -139,17 +209,17 @@ export function createComposerAttachments(
139209
return undefined
140210
})
141211

142-
if (path) addPath(target, { filename: file.name, mime, path })
212+
if (path) addPath(target, { filename: file.name, mime, path }, options)
143213
}
144214

145215
// Callers start this without awaiting it, so a failure (for example a blob write on a full disk)
146216
// is reported through onError instead of escaping as an unhandled rejection.
147-
const addAttachments = (files: File[], target = capture(), clipboard = false) =>
217+
const addAttachments = (files: File[], target = capture(), options?: AddOptions) =>
148218
files
149219
.reduce(async (result, file) => {
150220
const previous = await result
151221

152-
return (await add(file, target, clipboard)) || previous
222+
return (await add(file, target, options)) || previous
153223
}, Promise.resolve(false))
154224
.catch((error) => {
155225
input.onError(error)
@@ -175,7 +245,7 @@ export function createComposerAttachments(
175245
})
176246

177247
if (files.length > 0) {
178-
await addAttachments(files, target)
248+
await addAttachments(files, target, { paste: true })
179249

180250
return
181251
}
@@ -185,7 +255,7 @@ export function createComposerAttachments(
185255
if (input.readClipboardImage && !plainText) {
186256
const file = await input.readClipboardImage()
187257

188-
if (file && (await addAttachments([file], target, true))) return
258+
if (file && (await addAttachments([file], target, { clipboard: true, paste: true }))) return
189259
}
190260

191261
if (!plainText) return
@@ -356,6 +426,10 @@ function cursorPosition(editor: HTMLElement) {
356426
return before.toString().replace(/\u200B/g, "").length
357427
}
358428

429+
function inlineText(prompt: ComposerPrompt) {
430+
return prompt.map((part) => (isAttachment(part) ? "" : part.content)).join("")
431+
}
432+
359433
function largePaste(text: string) {
360434
if (text.length >= 8000) return true
361435

‎packages/app/src/composer/comment-note.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import type { SessionMessageUser } from "@opencode/client/promise"
22
import { Option, Schema } from "effect"
33
import { Persistence } from "@/runtime/persistence/schema"
4+
import { getFilename } from "@opencode/util/path"
45
import { uuid } from "@opencode/util/uuid"
56
import { FileSelection } from "@/workspaces/files/types"
67
import { durableNote, LegacyBrowserNote, NoteComment, QuoteComment, type ContextItem } from "./schema"
@@ -18,11 +19,18 @@ type PromptFileComment = typeof PromptFileComment.Type
1819

1920
export type PromptComment = PromptFileComment | NoteComment | QuoteComment
2021

22+
const PromptAttachmentMention = Persistence.struct({
23+
start: Schema.Finite,
24+
end: Schema.Finite,
25+
text: Schema.String,
26+
})
27+
2128
/** An attachment the model receives as a path on the server rather than inline bytes. */
2229
export const PromptAttachmentReference = Persistence.struct({
2330
name: Schema.String,
2431
mime: Schema.String,
2532
path: Schema.String,
33+
mentions: Persistence.optional(Persistence.array(PromptAttachmentMention)),
2634
})
2735

2836
export type PromptAttachmentReference = typeof PromptAttachmentReference.Type
@@ -52,6 +60,12 @@ export function readPromptPresentation(metadata: SessionMessageUser["metadata"])
5260
}
5361

5462
export function formatAttachmentReference(input: PromptAttachmentReference) {
63+
const label = input.mentions?.[0]?.text
64+
const name = label?.startsWith("@") ? label.slice(1) : label
65+
66+
if (name && name !== input.path && name !== getFilename(input.path))
67+
return `Attached file (${label}): \`${input.path}\``
68+
5569
return `Attached file: \`${input.path}\``
5670
}
5771

‎packages/app/src/composer/editor/actions.test.ts‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,4 +173,45 @@ describe("Composer store", () => {
173173
])
174174
expect(prompt.state.cursor).toBe(19)
175175
})
176+
177+
test("degrades linked attachment mention pills to plain text when their attachment is removed", () => {
178+
const prompt = createPromptStore()
179+
180+
prompt.addText(" @not")
181+
prompt.addMention({
182+
type: "attachment",
183+
attachmentID: "attachment-1",
184+
filename: "notes.txt",
185+
mime: "text/plain",
186+
content: "@notes.txt",
187+
start: 0,
188+
end: 0,
189+
})
190+
prompt.addText("done")
191+
192+
expect(prompt.state.prompt).toEqual([
193+
{ type: "text", content: "old ", start: 0, end: 4 },
194+
{
195+
type: "attachment",
196+
attachmentID: "attachment-1",
197+
filename: "notes.txt",
198+
mime: "text/plain",
199+
content: "@notes.txt",
200+
start: 4,
201+
end: 14,
202+
},
203+
{ type: "text", content: " done", start: 14, end: 19 },
204+
{
205+
type: "image",
206+
id: "attachment-1",
207+
filename: "notes.txt",
208+
mime: "text/plain",
209+
blob: { id: "a", url: "blob:a" },
210+
},
211+
])
212+
213+
prompt.removeAttachment("attachment-1")
214+
215+
expect(prompt.state.prompt).toEqual([{ type: "text", content: "old @notes.txt done", start: 0, end: 19 }])
216+
})
176217
})

‎packages/app/src/composer/editor/actions.ts‎

Lines changed: 29 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,14 @@ import { batch, untrack, type Accessor } from "solid-js"
22
import type { SetStoreFunction, Store } from "solid-js/store"
33
import type {
44
ComposerAgentPart,
5+
ComposerAttachmentMentionPart,
56
ComposerFilePart,
67
ComposerSkillPart,
78
ComposerSessionPart,
89
ComposerPersistedState,
910
ComposerPrompt,
1011
} from "../types"
11-
import { isAttachment, promptLength } from "../prompt-parts"
12+
import { isAttachment, mergeAdjacentText, promptLength, withOffsets } from "../prompt-parts"
1213

1314
type ComposerStateStore = [
1415
Store<ComposerPersistedState> | Accessor<Store<ComposerPersistedState>>,
@@ -75,7 +76,12 @@ export function createComposerEditorActions(input: ComposerStateStoreInput) {
7576
setStore()("context", "items", (items) => items.filter((item) => item.key !== key))
7677
},
7778
addMention(
78-
mention: ComposerFilePart | ComposerAgentPart | ComposerSkillPart | ComposerSessionPart,
79+
mention:
80+
| ComposerFilePart
81+
| ComposerAgentPart
82+
| ComposerSkillPart
83+
| ComposerSessionPart
84+
| ComposerAttachmentMentionPart,
7985
range?: { start: number; end: number },
8086
) {
8187
const prompt = withOffsets(store().prompt)
@@ -93,7 +99,21 @@ export function createComposerEditorActions(input: ComposerStateStoreInput) {
9399
setStore()("cursor", start + mention.content.length + 1)
94100
},
95101
removeAttachment(id: string) {
96-
setStore()("prompt", (parts) => parts.filter((part) => !isAttachment(part) || part.id !== id))
102+
setStore()("prompt", (parts) => {
103+
const remaining = parts.filter((part) => !isAttachment(part) || part.id !== id)
104+
105+
if (!remaining.some((part) => part.type === "attachment" && part.attachmentID === id)) return remaining
106+
107+
return withOffsets(
108+
mergeAdjacentText(
109+
remaining.map((part) =>
110+
part.type === "attachment" && part.attachmentID === id
111+
? { type: "text" as const, content: part.content, start: 0, end: 0 }
112+
: part,
113+
),
114+
),
115+
)
116+
})
97117
},
98118
}
99119
}
@@ -143,7 +163,12 @@ function insertMention(
143163
prompt: ComposerPrompt,
144164
start: number,
145165
end: number,
146-
mention: ComposerFilePart | ComposerAgentPart | ComposerSkillPart | ComposerSessionPart,
166+
mention:
167+
| ComposerFilePart
168+
| ComposerAgentPart
169+
| ComposerSkillPart
170+
| ComposerSessionPart
171+
| ComposerAttachmentMentionPart,
147172
): ComposerPrompt {
148173
let position = 0
149174
let inserted = false
@@ -177,15 +202,3 @@ function insertMention(
177202

178203
return withOffsets(parts)
179204
}
180-
181-
function withOffsets(prompt: ComposerPrompt): ComposerPrompt {
182-
let offset = 0
183-
184-
return prompt.map((part) => {
185-
if (isAttachment(part)) return part
186-
const next = { ...part, start: offset, end: offset + part.content.length }
187-
offset = next.end
188-
189-
return next
190-
})
191-
}

0 commit comments

Comments
 (0)