diff --git a/packages/app/e2e/regression/composer.spec.ts b/packages/app/e2e/regression/composer.spec.ts index 87fe50661df..618b355a381 100644 --- a/packages/app/e2e/regression/composer.spec.ts +++ b/packages/app/e2e/regression/composer.spec.ts @@ -1,6 +1,6 @@ import { expect, test, type Locator, type Page } from "@playwright/test" -import { NO_PROVIDER, T0, provider } from "../utils/app" -import { openDraft, openSession } from "../utils/workspace" +import { NO_PROVIDER, T0, provider, sessionHref } from "../utils/app" +import { openDraft, openSession, type WorkspaceInput } from "../utils/workspace" test.use({ permissions: ["clipboard-read", "clipboard-write"] }) @@ -509,3 +509,99 @@ test("shows thinking on hover or a non-default selection while preserving keyboa await page.keyboard.press("Tab") await expect(control).toHaveCSS("opacity", "0") }) + +test("mentions open or running sessions by readable title, survives title changes, and opens from the transcript", async ({ + page, +}) => { + const currentID = "ses_00000000000000000000000001" + const openTabID = "ses_00000000000000000000000002" + const runningID = "ses_00000000000000000000000003" + const idleClosedID = "ses_00000000000000000000000004" + const prompts: Parameters>[0][] = [] + + const { editor } = await openSession(page, { + name: "ComposerSessionMentions", + sessionID: currentID, + sessions: [ + { id: currentID, title: "Current session" }, + { id: openTabID, title: "Auth refactor" }, + { id: runningID, title: "Background migration" }, + { id: idleClosedID, title: "Closed idle session" }, + ], + sessionStatus: { + [runningID]: { type: "running" }, + }, + seed: { + tabs: [currentID, openTabID], + }, + findFiles: () => [], + onPrompt: (input) => prompts.push(input), + }) + + await editor.click() + await editor.pressSequentially("@") + const suggestions = page.locator('[data-component="composer-suggestions"]') + await expect(suggestions.locator('[data-suggestion-id^="session:"] bdi')).toHaveText([ + "@Auth refactor", + "@Background migration", + ]) + await expect(suggestions.locator(`[data-suggestion-id="session:${currentID}"]`)).toHaveCount(0) + await expect(suggestions.locator(`[data-suggestion-id="session:${idleClosedID}"]`)).toHaveCount(0) + + await editor.pressSequentially(openTabID.slice(0, 8)) + await expect(suggestions.locator(`[data-suggestion-id="session:${openTabID}"][data-active]`)).toContainText( + "@Auth refactor", + ) + await editor.press("Enter") + + const pill = editor.locator(`[data-mention="session"][data-id="${openTabID}"]`) + await expect(pill).toHaveText("@Auth refactor") + + const tabLink = page.locator(`[data-titlebar-tab-link][href="${sessionHref(openTabID)}"]`) + const tabTitle = tabLink.locator("[data-titlebar-tab-title]") + + await tabLink.click({ button: "right" }) + await page.getByRole("menuitem", { name: "Rename", exact: true }).click() + await expect(tabTitle).toHaveAttribute("contenteditable", "true") + await page.keyboard.type("Auth v2") + await tabTitle.press("Enter") + await expect(tabTitle).toHaveText("Auth v2") + await expect(pill).toHaveText("@Auth v2") + + await editor.click() + await page.keyboard.type("compare this") + await editor.press("Enter") + + await expect.poll(() => prompts.length).toBe(1) + expect(prompts[0]).toMatchObject({ + sessionID: currentID, + body: { + text: `@Auth v2 compare this\nReferenced session "@Auth v2": \`${openTabID}\``, + metadata: { + displayText: "@Auth v2 compare this", + sessions: [ + { + id: openTabID, + mention: { start: 0, end: 8, text: "@Auth v2" }, + }, + ], + }, + }, + }) + + const transcriptLink = page.locator( + `[data-component="user-message"] button.markdown-session-link[data-highlight="session"][data-session-id="${openTabID}"]`, + ) + + await expect(transcriptLink).toHaveText("@Auth v2") + + await tabLink.click({ button: "right" }) + await page.getByRole("menuitem", { name: "Rename", exact: true }).click() + await expect(tabTitle).toHaveAttribute("contenteditable", "true") + await page.keyboard.type("Auth final") + await tabTitle.press("Enter") + await expect(transcriptLink).toHaveText("@Auth final") + + await transcriptLink.click() + await expect(page).toHaveURL(sessionHref(openTabID)) +}) diff --git a/packages/app/src/composer/comment-note.ts b/packages/app/src/composer/comment-note.ts index a3499250daf..c2358544fa6 100644 --- a/packages/app/src/composer/comment-note.ts +++ b/packages/app/src/composer/comment-note.ts @@ -1,4 +1,5 @@ import type { SessionMessageUser } from "@opencode/client/promise" +import { Session } from "@opencode/schema/session" import { Option, Schema } from "effect" import { Persistence } from "@/runtime/persistence/schema" import { uuid } from "@/runtime/persistence/uuid" @@ -27,6 +28,18 @@ export const PromptAttachmentReference = Persistence.struct({ export type PromptAttachmentReference = typeof PromptAttachmentReference.Type +/** A session referenced from a prompt, backed by its immutable session ID. */ +export const PromptSessionReference = Persistence.struct({ + id: Session.ID, + mention: Schema.Struct({ + start: Schema.Finite, + end: Schema.Finite, + text: Schema.String, + }), +}) + +export type PromptSessionReference = typeof PromptSessionReference.Type + // Presentation metadata needs a comments list, which prompts from other clients lack; a malformed comment or // attachment is skipped rather than discarding the rest. const decodePromptPresentation = Schema.decodeUnknownOption( @@ -34,6 +47,7 @@ const decodePromptPresentation = Schema.decodeUnknownOption( displayText: Schema.String, comments: Schema.Array(Schema.Unknown), attachments: Persistence.array(PromptAttachmentReference), + sessions: Persistence.array(PromptSessionReference), }), ) @@ -44,6 +58,7 @@ export function readPromptPresentation(metadata: SessionMessageUser["metadata"]) Option.map(decodePromptPresentation(metadata), (presentation) => ({ displayText: presentation.displayText, attachments: presentation.attachments, + sessions: presentation.sessions, comments: presentation.comments.flatMap((item): PromptComment[] => Option.toArray(decodePromptComment(item))), })), ) @@ -53,6 +68,10 @@ export function formatAttachmentReference(input: PromptAttachmentReference) { return `Attached file: \`${input.path}\`` } +export function formatSessionReference(input: PromptSessionReference) { + return `Referenced session ${JSON.stringify(input.mention.text)}: \`${input.id}\`` +} + /** A note reads with its live subject while it stays in the app process that attached it. */ export function formatNoteComment(input: NoteComment) { return `The user made the following comment regarding ${input.live?.subject ?? input.subject}: ${input.comment}` diff --git a/packages/app/src/composer/editor/actions.ts b/packages/app/src/composer/editor/actions.ts index 48199516e29..6230227b1ad 100644 --- a/packages/app/src/composer/editor/actions.ts +++ b/packages/app/src/composer/editor/actions.ts @@ -1,8 +1,10 @@ +import { Predicate } from "effect" import { batch, untrack, type Accessor } from "solid-js" import type { SetStoreFunction, Store } from "solid-js/store" import type { ComposerAgentPart, ComposerFilePart, + ComposerSessionPart, ComposerSkillPart, ComposerPersistedState, ComposerPrompt, @@ -17,12 +19,12 @@ export type ComposerStateStore = [ export type ComposerStateStoreInput = ComposerStateStore | Accessor export function createComposerEditorActions(input: ComposerStateStoreInput) { - const tuple = () => (typeof input === "function" ? input() : input) + const tuple = () => (Predicate.isFunction(input) ? input() : input) const store = () => { const value = tuple()[0] - return typeof value === "function" ? value() : value + return Predicate.isFunction(value) ? value() : value } const setStore = () => tuple()[1] @@ -36,8 +38,11 @@ export function createComposerEditorActions(input: ComposerStateStoreInput) { return store() }, setPrompt(prompt: ComposerPrompt, cursor?: number) { + const next: Partial = { prompt, retry: undefined } + + if (cursor !== undefined) next.cursor = cursor // Persisted setters encode on every call, even inside a reactive batch. - batch(() => setStore()({ prompt, ...(cursor !== undefined ? { cursor } : {}), retry: undefined })) + batch(() => setStore()(next)) }, setCursor(cursor: number) { if (untrack(() => store().cursor) === cursor) return @@ -74,7 +79,7 @@ export function createComposerEditorActions(input: ComposerStateStoreInput) { clearRetry() }, addMention( - mention: ComposerFilePart | ComposerAgentPart | ComposerSkillPart, + mention: ComposerFilePart | ComposerAgentPart | ComposerSkillPart | ComposerSessionPart, range?: { start: number; end: number }, ) { const text = store() @@ -127,7 +132,7 @@ function insertMention( prompt: ComposerPrompt, start: number, end: number, - mention: ComposerFilePart | ComposerAgentPart | ComposerSkillPart, + mention: ComposerFilePart | ComposerAgentPart | ComposerSkillPart | ComposerSessionPart, ): ComposerPrompt { if (start === 0 && end === 0) { return withOffsets([mention, { type: "text", content: " ", start: 0, end: 0 }, ...prompt]) diff --git a/packages/app/src/composer/editor/editor.tsx b/packages/app/src/composer/editor/editor.tsx index defbf666d0e..cdf78bbe2b5 100644 --- a/packages/app/src/composer/editor/editor.tsx +++ b/packages/app/src/composer/editor/editor.tsx @@ -32,6 +32,7 @@ import type { Upload } from "../attachments/uploads" import { CommentCard } from "@opencode/session-ui/comment-card" import { typeLabel } from "@opencode/session-ui/message-file" import { getFilename } from "@opencode/util/path" +import { Session } from "@opencode/schema/session" import { Skill } from "@opencode/schema/skill" import type { ComposerAgentPart, @@ -241,7 +242,7 @@ export function ComposerEditor(props: ComposerEditorProps) { spellcheck={state.mode === "normal"} // @ts-expect-error autocomplete="off" - class="relative z-10 block min-h-[60px] w-full whitespace-pre-wrap bg-transparent px-4 pt-4 pb-2 text-[13px] font-[440] leading-5 text-v2-text-text-base focus:outline-none [&_[data-mention=file]]:text-syntax-property [&_[data-mention=agent]]:text-syntax-type [&_[data-mention=reference]]:text-syntax-keyword" + class="relative z-10 block min-h-[60px] w-full whitespace-pre-wrap bg-transparent px-4 pt-4 pb-2 text-[13px] font-[440] leading-5 text-v2-text-text-base focus:outline-none [&_[data-mention=file]]:text-syntax-property [&_[data-mention=agent]]:text-syntax-type [&_[data-mention=session]]:text-syntax-type [&_[data-mention=reference]]:text-syntax-keyword" classList={{ "font-mono!": state.mode === "shell", "opacity-50": props.disabled }} style={{ "unicode-bidi": state.mode === "normal" ? "plaintext" : undefined, @@ -436,6 +437,10 @@ function renderComposerEditor(editor: HTMLDivElement, prompt: ComposerPrompt) { mention.dataset.name = part.name } + if (part.type === "session") { + mention.dataset.id = part.id + } + if (part.type === "file") { mention.dataset.path = part.path @@ -505,6 +510,19 @@ function parseComposerEditor(editor: HTMLDivElement) { return } + if (element.dataset.mention === "session") { + parts.push({ + type: "session", + id: Session.ID.make(element.dataset.id ?? content.slice(1)), + content, + start: position, + end: position + content.length, + }) + position += content.length + + return + } + const parsed: ComposerFilePart = { type: "file", path: element.dataset.path ?? content.slice(1), @@ -1169,6 +1187,8 @@ function ComposerSuggestionIcon(props: { item: ComposerSuggestion }) { if (props.item.kind === "skill") return + if (props.item.kind === "session") return + if (props.item.kind === "command") return null return ( diff --git a/packages/app/src/composer/editor/interaction.ts b/packages/app/src/composer/editor/interaction.ts index bde7d860d51..bc35bca06cc 100644 --- a/packages/app/src/composer/editor/interaction.ts +++ b/packages/app/src/composer/editor/interaction.ts @@ -79,7 +79,7 @@ export function createComposerEditor(input: { function addPart(part: ComposerPersistedState["prompt"][number]) { if (isAttachment(part)) return false - if (part.type === "file" || part.type === "agent") { + if (part.type !== "text") { draft.addMention(part) return true @@ -131,9 +131,11 @@ export function createComposerEditor(input: { return [...fixed, ...recent, ...files] }, key: (item) => item.id, - filterKeys: ["label"], + filterKeys: ["label", "trigger"], skipFilter: (item) => item.kind === "file" && !item.recent, groupBy: (item) => { + if (item.kind === "session") return "session" + if (item.kind === "reference") return "reference" if (item.kind === "skill") return "skill" @@ -147,7 +149,7 @@ export function createComposerEditor(input: { return "file" }, sortGroupsBy: (a, b) => { - const order = ["reference", "skill", "agent", "resource", "recent", "file"] + const order = ["session", "reference", "skill", "agent", "resource", "recent", "file"] return order.indexOf(a.category) - order.indexOf(b.category) }, diff --git a/packages/app/src/composer/history/entry.ts b/packages/app/src/composer/history/entry.ts index c8787e4fa5f..656e341abe3 100644 --- a/packages/app/src/composer/history/entry.ts +++ b/packages/app/src/composer/history/entry.ts @@ -10,12 +10,16 @@ export const MAX_HISTORY = 100 export type PromptHistoryStoredEntry = PromptHistoryEntry function cloneSelection(selection: SelectedLineRange): SelectedLineRange { - return { + const next: SelectedLineRange = { start: selection.start, end: selection.end, - ...(selection.side ? { side: selection.side } : {}), - ...(selection.endSide ? { endSide: selection.endSide } : {}), } + + if (selection.side) next.side = selection.side + + if (selection.endSide) next.endSide = selection.endSide + + return next } export function clonePromptHistoryComments(comments: PromptHistoryComment[]) { @@ -113,6 +117,10 @@ function isPromptEqual(entryA: PromptHistoryStoredEntry, entryB: PromptHistorySt if (partB.type !== "skill" || partA.id !== partB.id || partA.name !== partB.name) return false } + if (partA.type === "session") { + if (partB.type !== "session" || partA.id !== partB.id || partA.content !== partB.content) return false + } + if (isAttachment(partA) && partA.id !== (isAttachment(partB) ? partB.id : "")) return false } diff --git a/packages/app/src/composer/model.ts b/packages/app/src/composer/model.ts index 7b1a3c87595..e491e96e673 100644 --- a/packages/app/src/composer/model.ts +++ b/packages/app/src/composer/model.ts @@ -3,7 +3,7 @@ import { useDialog } from "@opencode/ui/context/dialog" import type { ReferenceInfo } from "@opencode/client/promise" import type { Links, MountedSession } from "@opencode/gui-extensions/sdk" import { createComponent, createEffect, createMemo, on } from "solid-js" -import { Predicate } from "effect" +import { Predicate, Schema } from "effect" import type { ComposerSuggestion } from "./types" import { createComposerEditor, createComposerEditorState, type ComposerEditorModel } from "./editor/interaction" import { selectionFromLines, type SelectedLineRange, useFile } from "@/workspaces/files/model" @@ -17,8 +17,11 @@ import { usePlatform } from "@/runtime/platform/platform" import { useWorkspaceLocation } from "@/workspaces/location" import { resolveBlobUrl } from "@/runtime/persistence/drafts" import { useData, useServer } from "@/runtime/server/current" +import { tabKey, useTabs } from "@/shell/tabs/tabs" +import { sessionTabTitle } from "@/shell/titlebar/tab-title" import { showToast } from "@/shell/notifications/toast" import { formatServerError } from "@/runtime/server/errors" +import { Session } from "@opencode/schema/session" import { Skill } from "@opencode/schema/skill" import type { ComposerAdapter, ComposerControls, ComposerQueue } from "./adapter" import { isAttachment } from "./prompt-parts" @@ -42,6 +45,7 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue? const sdk = useWorkspaceLocation() const data = useData() const server = useServer() + const tabs = useTabs() const available = () => server.conn.type !== "extension" || !server.conn.managed || server.ctx.sdk.connection.status() === "connected" @@ -189,7 +193,99 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue? const skills = createMemo(() => data.location.skill.list({ directory: sdk().directory }) ?? []) + const isSessionID = Schema.is(Session.ID) + + createEffect(() => { + data.session.active().forEach((id) => { + if (!data.session.get(id)) void data.session.sync(id).catch(() => undefined) + }) + }) + + const sessionTitles = createMemo(() => { + const fallback = language.t("session.tab.session") + + return new Map( + [ + ...tabs.store.flatMap((tab) => + tab.type === "session" && tab.server === server.key + ? [[tab.sessionId, data.session.get(tab.sessionId)?.title ?? tabs.info[tabKey(tab)]?.title] as const] + : [], + ), + ...data.session.list().map((session) => [session.id, session.title] as const), + ].flatMap(([id, raw]) => (raw !== undefined ? [[id, sessionTabTitle(raw, fallback)] as const] : [])), + ) + }) + + const sessions = createMemo(() => { + const current = adapter.kind === "active-session" ? adapter.session().id : undefined + const fallback = language.t("session.tab.session") + const titles = sessionTitles() + + const ids = [ + ...tabs.store.flatMap((tab) => + tab.type === "session" && tab.server === server.key && !tabs.pendingSession(tab.server, tab.sessionId) + ? [tab.sessionId] + : [], + ), + ...data.session.active(), + ...data.session + .list() + .flatMap((session) => + data.session.status(session.id) === "running" || + data.session.pending.list(session.id).some((item) => item.type !== "synthetic") + ? [session.id] + : [], + ), + ] + + return Array.from(new Set(ids)) + .filter((id): id is Session.ID => id !== current && isSessionID(id) && !data.session.get(id)?.time.archived) + .map((id) => { + const label = `@${titles.get(id) ?? fallback}` + + return { + id: `session:${id}`, + kind: "session" as const, + label, + trigger: id, + description: id, + mention: { type: "session" as const, id, content: label, start: 0, end: 0 }, + } + }) + }) + + createEffect(() => { + const titles = sessionTitles() + const current = prompt.current() + + if ( + !current.some((part) => part.type === "session" && titles.has(part.id) && part.content !== `@${titles.get(part.id)}`) + ) + return + + let offset = 0 + let delta = 0 + const cursor = prompt.cursor() + + const next = current.map((part) => { + if (isAttachment(part)) return part + const content = part.type === "session" && titles.has(part.id) ? `@${titles.get(part.id)!}` : part.content + const start = offset + const end = start + content.length + + if (cursor !== undefined && part.end <= cursor) delta += content.length - part.content.length + offset = end + + return content === part.content && start === part.start && end === part.end + ? part + : { ...part, content, start, end } + }) + + prompt.set(next, cursor !== undefined ? Math.max(0, cursor + delta) : undefined) + }) + const context = createMemo(() => [ + ...sessions(), ...references(), ...skills().map((skill) => ({ id: `skill:${skill.id}`, @@ -314,8 +410,7 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue? entries: (mode) => history.entries(mode).map((entry) => ({ prompt: entry.prompt, metadata: entry.comments })), add: (value, mode) => history.add(value, mode, mode === "shell" ? [] : historyComments()), capture: historyComments, - // SAFETY: `entries` stores each entry's comments as its metadata, and the editor restores only metadata it read there. - restore: (metadata) => restoreHistoryComments(metadata as PromptHistoryComment[]), + restore: (metadata) => restoreHistoryComments(metadata ?? []), }, commands, context, diff --git a/packages/app/src/composer/prompt.test.ts b/packages/app/src/composer/prompt.test.ts index 6c275f6e920..b5782e084aa 100644 --- a/packages/app/src/composer/prompt.test.ts +++ b/packages/app/src/composer/prompt.test.ts @@ -175,11 +175,21 @@ describe("extractPromptFromMessage", () => { ]) }) - test("restores skill mentions as structured Composer parts", () => { + test("restores skill and session mentions as structured Composer parts", () => { const message = { id: "msg_1", type: "user", - text: "Use @review", + text: 'Use @review with @Auth refactor\nReferenced session "@Auth refactor": `ses_0123456789abcdefghijklmnop`', + metadata: { + displayText: "Use @review with @Auth refactor", + comments: [], + sessions: [ + { + id: "ses_0123456789abcdefghijklmnop", + mention: { text: "@Auth refactor", start: 17, end: 31 }, + }, + ], + }, skills: [{ id: "review", name: "Review", mention: { text: "@review", start: 4, end: 11 } }], time: { created: 1 }, } satisfies SessionMessageUser @@ -192,6 +202,12 @@ describe("extractPromptFromMessage", () => { name: "Review", content: "@review", }, + { type: "text", content: " with " }, + { + type: "session", + id: "ses_0123456789abcdefghijklmnop", + content: "@Auth refactor", + }, ]) }) }) diff --git a/packages/app/src/composer/prompt.ts b/packages/app/src/composer/prompt.ts index fbceef262b7..4e416018de3 100644 --- a/packages/app/src/composer/prompt.ts +++ b/packages/app/src/composer/prompt.ts @@ -5,6 +5,7 @@ import { commentContextItem, readPromptPresentation } from "./comment-note" import { buildPromptRequest } from "./request" import { contextItemKey, type FileContextItem } from "./schema" import { createPathHelpers, decodeFilePath, stripFileProtocol, stripQueryAndHash } from "@/workspaces/files/path" +import { Session } from "@opencode/schema/session" import { Skill } from "@opencode/schema/skill" type Inline = @@ -40,6 +41,13 @@ type Inline = id: Skill.ID name: Skill.Name } + | { + type: "session" + start: number + end: number + value: string + id: Session.ID + } function selectionFromFileUrl(url: string): Extract["selection"] { const queryIndex = url.indexOf("?") @@ -149,6 +157,10 @@ export function extractPromptFromMessage( if (mention) inline.push({ ...part, start: mention.start, end: mention.end, value: mention.text }) } + for (const session of presentation?.sessions ?? []) { + inline.push({ ...session.mention, type: "session", id: Session.ID.make(session.id), value: session.mention.text }) + } + attachments.push( ...(presentation?.attachments ?? []).map( (file, index): PathAttachmentPart => ({ @@ -254,6 +266,12 @@ function buildPrompt( return } + if (item.type === "session") { + result.push({ type: "session", id: item.id, ...span }) + + return + } + result.push({ type: "file", path: item.path, diff --git a/packages/app/src/composer/request.test.ts b/packages/app/src/composer/request.test.ts index 1e7d8258ddf..b226d3b6cff 100644 --- a/packages/app/src/composer/request.test.ts +++ b/packages/app/src/composer/request.test.ts @@ -1,4 +1,5 @@ import { describe, expect, test } from "bun:test" +import { Session } from "@opencode/schema/session" import { Skill } from "@opencode/schema/skill" import type { ImageAttachmentPart, Prompt } from "@/composer/state" import type { FileSelection } from "@/workspaces/files/model" @@ -139,12 +140,14 @@ describe("buildPromptRequest", () => { expect(result.files).toEqual([{ uri: "file:///repo/src/button.css", mime: "text/plain", name: "button.css" }]) }) - test("keeps skill mentions out of file attachments", () => { + test("keeps skill and session mentions out of file attachments while preserving session IDs in model text", () => { const skill = { id: "skill-review", name: "review", } + const sessionID = Session.ID.make("ses_0123456789abcdefghijklmnop") + const result = buildPromptRequest({ prompt: [ { @@ -155,15 +158,30 @@ describe("buildPromptRequest", () => { start: 0, end: 7, }, + { type: "text", content: " ", start: 7, end: 8 }, + { + type: "session", + id: sessionID, + content: "@Auth refactor", + start: 8, + end: 22, + }, ], context: [], images: [], - text: "@review", + text: "@review @Auth refactor", sessionDirectory: "/repo", }) expect(result.files).toEqual([]) expect(result.skills).toEqual([{ id: skill.id, name: skill.name, mention: { start: 0, end: 7, text: "@review" } }]) + expect(result.sessions).toEqual([ + { id: sessionID, mention: { start: 8, end: 22, text: "@Auth refactor" } }, + ]) + expect(result.displayText).toBe("@review @Auth refactor") + expect(result.text).toBe( + '@review @Auth refactor\nReferenced session "@Auth refactor": `ses_0123456789abcdefghijklmnop`', + ) }) test.each<{ dir: string; path: string; selection?: FileSelection; context?: true; uri: string }>([ diff --git a/packages/app/src/composer/request.ts b/packages/app/src/composer/request.ts index a928b80e789..446ebddb28f 100644 --- a/packages/app/src/composer/request.ts +++ b/packages/app/src/composer/request.ts @@ -9,14 +9,17 @@ import type { NoteContextItem, PathAttachmentPart, Prompt, + SessionPart, SkillPart, } from "@/composer/state" import { formatAttachmentReference, formatCommentNote, formatNoteComment, + formatSessionReference, type PromptAttachmentReference, type PromptComment, + type PromptSessionReference, } from "@/composer/comment-note" // Network fields feed both boundaries; display fields keep desktop-only rendering details in the local echo. @@ -32,6 +35,7 @@ type PromptRequest = { }[] agents: { name: string; mention?: { start: number; end: number; text: string } }[] skills: { id: string; name: string; mention?: { start: number; end: number; text: string } }[] + sessions: PromptSessionReference[] comments: PromptComment[] attachments: PromptAttachmentReference[] } @@ -75,6 +79,8 @@ const isAgentAttachment = (part: Prompt[number]): part is AgentPart => part.type const isSkillAttachment = (part: Prompt[number]): part is SkillPart => part.type === "skill" +const isSessionAttachment = (part: Prompt[number]): part is SessionPart => part.type === "session" + const isPathAttachment = (part: Prompt[number]): part is PathAttachmentPart => part.type === "path" /** The sent form of a note: its optional link and live subject travel only when present. */ @@ -102,6 +108,11 @@ export function buildPromptRequest(input: BuildPromptRequestInput): PromptReques mention: { start: attachment.start, end: attachment.end, text: attachment.content }, })) + const sessions = input.prompt.filter(isSessionAttachment).map((attachment) => ({ + id: attachment.id, + mention: { start: attachment.start, end: attachment.end, text: attachment.content }, + })) + const files = input.prompt.filter(isFileAttachment).map((attachment) => { const path = absolute(input.sessionDirectory, attachment.path) @@ -178,6 +189,7 @@ export function buildPromptRequest(input: BuildPromptRequestInput): PromptReques return { text: [ ...(input.text.trim() ? [input.text] : []), + ...sessions.map(formatSessionReference), ...attachments.map(formatAttachmentReference), ...comments.map((comment) => (comment.type === "note" ? formatNoteComment(comment) : formatCommentNote(comment))), ].join("\n"), @@ -185,6 +197,7 @@ export function buildPromptRequest(input: BuildPromptRequestInput): PromptReques files: [...files, ...context, ...inline], agents, skills, + sessions, comments, attachments, } diff --git a/packages/app/src/composer/schema.test.ts b/packages/app/src/composer/schema.test.ts index 48a2dcc0ec9..21856699ec8 100644 --- a/packages/app/src/composer/schema.test.ts +++ b/packages/app/src/composer/schema.test.ts @@ -1,6 +1,7 @@ import { describe, expect, test } from "bun:test" import { Schema } from "effect" import { Persistence } from "@/runtime/persistence/schema" +import { Session } from "@opencode/schema/session" import { SessionMessage } from "@opencode/schema/session-message" import { CommentStore, @@ -126,13 +127,21 @@ describe("composer persistence schemas", () => { text, { type: "agent", content: "@build", start: 5, end: 11, name: "build" }, { type: "skill", content: "@effect", start: 11, end: 18, id: "effect", name: "Effect" }, + { + type: "session", + content: "@Auth refactor", + start: 18, + end: 32, + id: "ses_0123456789abcdefghijklmnop", + }, + { type: "session", content: "@broken-session", start: 32, end: 47, id: "not_a_session" }, { type: "agent", content: "@broken", start: 18, end: 25, name: 42 }, { type: "file", path: "src/app.ts", content: "@src/app.ts", - start: 18, - end: 29, + start: 32, + end: 43, selection: { startLine: "broken" }, mime: 42, filename: "app.ts", @@ -143,13 +152,20 @@ describe("composer persistence schemas", () => { retry: { id: "msg_retry", agent: "build", providerID: "provider", modelID: "model", variant: false }, }) - expect(value.prompt.map((part) => part.type)).toEqual(["text", "agent", "skill", "file"]) + expect(value.prompt.map((part) => part.type)).toEqual(["text", "agent", "skill", "session", "file"]) expect(value.prompt[3]).toEqual({ + type: "session", + content: "@Auth refactor", + start: 18, + end: 32, + id: Session.ID.make("ses_0123456789abcdefghijklmnop"), + }) + expect(value.prompt[4]).toEqual({ type: "file", path: "src/app.ts", content: "@src/app.ts", - start: 18, - end: 29, + start: 32, + end: 43, filename: "app.ts", }) expect(value.model?.variant).toBeNull() diff --git a/packages/app/src/composer/schema.ts b/packages/app/src/composer/schema.ts index 6ac7dd06fd9..15162f937dc 100644 --- a/packages/app/src/composer/schema.ts +++ b/packages/app/src/composer/schema.ts @@ -1,5 +1,6 @@ import { Schema, SchemaGetter, Struct } from "effect" import { checksum } from "@opencode/util/encode" +import { Session } from "@opencode/schema/session" import { SessionMessage } from "@opencode/schema/session-message" import { Skill } from "@opencode/schema/skill" import { Persistence } from "@/runtime/persistence/schema" @@ -59,6 +60,14 @@ export const SkillPart = Persistence.struct({ export type SkillPart = typeof SkillPart.Type +export const SessionPart = Persistence.struct({ + type: Schema.Literal("session"), + ...PartBase, + id: Session.ID, +}) + +export type SessionPart = typeof SessionPart.Type + const ImageFields = { type: Schema.Literal("image"), id: Schema.String, @@ -121,6 +130,7 @@ export const ContentPart = Schema.Union([ FileAttachmentPart, AgentPart, SkillPart, + SessionPart, ImageAttachmentPart, PathAttachmentPart, ]) diff --git a/packages/app/src/composer/state.ts b/packages/app/src/composer/state.ts index 405713bf907..e0213df3a10 100644 --- a/packages/app/src/composer/state.ts +++ b/packages/app/src/composer/state.ts @@ -27,7 +27,9 @@ export type { NoteContextItem, PathAttachmentPart, Prompt, + PromptHistoryComment, PromptModel, + SessionPart, SkillPart, TextPart, } from "./schema" diff --git a/packages/app/src/composer/submit.ts b/packages/app/src/composer/submit.ts index 4daf1ccd774..6d9d0e7ff0c 100644 --- a/packages/app/src/composer/submit.ts +++ b/packages/app/src/composer/submit.ts @@ -254,6 +254,11 @@ function handoffMessage(value: ComposerSubmission): SessionMessageUser { attachments: value.prompt.flatMap((part) => part.type === "path" ? [{ name: part.filename, mime: part.mime, path: part.path }] : [], ), + sessions: value.prompt.flatMap((part) => + part.type === "session" + ? [{ id: part.id, mention: { start: part.start, end: part.end, text: part.content } }] + : [], + ), comments: value.context.flatMap((item): PromptComment[] => { const comment = item.comment?.trim() @@ -540,6 +545,7 @@ async function sendPrompt( displayText: request.displayText, comments: request.comments, attachments: request.attachments, + sessions: request.sessions, agent: value.selection.agent, model: selectionModel(value.selection), genui: value.genui, diff --git a/packages/app/src/composer/suggestions/machine.ts b/packages/app/src/composer/suggestions/machine.ts index c2d4758c3c6..142970d1840 100644 --- a/packages/app/src/composer/suggestions/machine.ts +++ b/packages/app/src/composer/suggestions/machine.ts @@ -193,31 +193,32 @@ function suggestionSelected( persisted: ComposerPersistedState, ): ComposerEditorTransition { const current = promptText(persisted) - const commands: ComposerInteractionCommand[] = [] if (item.kind === "command") { - commands.push({ - type: "draft.setText", - value: - state.popover.type === "command-menu" - ? current.trim() - ? `${item.label} ${current.trim()}` - : `${item.label} ` - : replaceTrigger(current, "/", `${item.label} `), - }) - } else { - commands.push({ - type: "mention.add", - item, - ...(item.kind === "skill" && item.label.startsWith("/") - ? { range: { start: 0, end: state.popover.type === "command-menu" ? 0 : current.length } } - : {}), - }) + return changed({ ...state, popover: { type: "closed" }, focus: "editor" }, [ + { + type: "draft.setText", + value: + state.popover.type === "command-menu" + ? current.trim() + ? `${item.label} ${current.trim()}` + : `${item.label} ` + : replaceTrigger(current, "/", `${item.label} `), + }, + { type: "focus.editor" }, + ]) } - commands.push({ type: "focus.editor" }) + const command: Extract = { + type: "mention.add", + item, + } - return changed({ ...state, popover: { type: "closed" }, focus: "editor" }, commands) + if (item.kind === "skill" && item.label.startsWith("/")) { + command.range = { start: 0, end: state.popover.type === "command-menu" ? 0 : current.length } + } + + return changed({ ...state, popover: { type: "closed" }, focus: "editor" }, [command, { type: "focus.editor" }]) } function keyDown( @@ -276,7 +277,7 @@ function populated(persisted: ComposerPersistedState) { return ( !!promptText(persisted).trim() || persisted.context.items.length > 0 || - persisted.prompt.some((part) => part.type === "file" || isAttachment(part)) + persisted.prompt.some((part) => part.type !== "text" || isAttachment(part)) ) } diff --git a/packages/app/src/composer/types.ts b/packages/app/src/composer/types.ts index 46a56994fba..4abdcde7dac 100644 --- a/packages/app/src/composer/types.ts +++ b/packages/app/src/composer/types.ts @@ -5,6 +5,8 @@ import type { ImageAttachmentPart, PathAttachmentPart, Prompt, + PromptHistoryComment, + SessionPart, SkillPart, } from "./state" @@ -14,6 +16,8 @@ export type ComposerAgentPart = AgentPart export type ComposerSkillPart = SkillPart +export type ComposerSessionPart = SessionPart + export type ComposerAttachment = ImageAttachmentPart | PathAttachmentPart export type ComposerPrompt = Prompt @@ -24,14 +28,14 @@ export type ComposerPersistedState = ComposerStore export type ComposerHistoryEntry = { prompt: ComposerPrompt - metadata?: unknown + metadata?: PromptHistoryComment[] } export type ComposerHistory = { entries: (mode: "normal" | "shell") => ComposerHistoryEntry[] add: (prompt: ComposerPrompt, mode: "normal" | "shell") => void - capture?: () => unknown - restore?: (metadata: unknown) => void + capture?: () => PromptHistoryComment[] + restore?: (metadata: PromptHistoryComment[] | undefined) => void } export type ComposerOption = { @@ -42,7 +46,7 @@ export type ComposerOption = { export type ComposerSuggestion = { id: string - kind: "agent" | "command" | "file" | "reference" | "resource" | "skill" + kind: "agent" | "command" | "file" | "reference" | "resource" | "session" | "skill" label: string title?: string trigger?: string @@ -50,5 +54,5 @@ export type ComposerSuggestion = { path?: string keybind?: string[] recent?: boolean - mention?: ComposerFilePart | ComposerAgentPart | ComposerSkillPart + mention?: ComposerFilePart | ComposerAgentPart | ComposerSkillPart | ComposerSessionPart } diff --git a/packages/app/src/session/composer/queue.ts b/packages/app/src/session/composer/queue.ts index e5337e82498..765d32c4875 100644 --- a/packages/app/src/session/composer/queue.ts +++ b/packages/app/src/session/composer/queue.ts @@ -10,7 +10,7 @@ import type { ContextItem, ImageAttachmentPart, PathAttachmentPart, Prompt } fro import { appendPrompt, clonePrompt, isAttachment, promptLength } from "@/composer/prompt-parts" import { buildPromptRequest } from "@/composer/request" import { blobDataUrl, createLegacyBlobReference } from "@/runtime/persistence/drafts" -import { readPromptPresentation } from "@/composer/comment-note" +import { formatSessionReference, readPromptPresentation } from "@/composer/comment-note" import { extractPromptContext, extractPromptFromMessage } from "@/composer/prompt" import { useData } from "@/runtime/server/current" import { useServerSDK } from "@/runtime/server/client" @@ -454,7 +454,15 @@ async function editedPromptInput( const request = buildPromptRequest({ prompt, context: [], images, text, sessionDirectory: directory }) const payload = item?.payload - const display = item ? queuedPromptText(item) : "" + const presented = readPromptPresentation(payload?.metadata) + + const display = [ + ...(item ? [queuedPromptText(item)] : []), + ...(presented?.sessions ?? []).map(formatSessionReference), + ] + .filter(Boolean) + .join("\n") + const notes = payload && display && payload.text.startsWith(display) ? payload.text.slice(display.length) : "" const mention = (value: { start: number; end: number; text: string } | undefined) => { @@ -467,8 +475,8 @@ async function editedPromptInput( } // Structured mentions degrade to plain text in the editor, so an original - // agent or skill reference survives the edit as long as its mention text - // still appears; newly typed structured mentions come from the request. + // agent, skill, or session reference survives the edit as long as its mention + // text still appears; newly typed structured mentions come from the request. const agents = [ ...(payload?.agents?.filter( (agent) => @@ -486,9 +494,19 @@ async function editedPromptInput( ...request.skills, ] + const retainedSessions = (presented?.sessions ?? []).flatMap((session) => { + if (request.sessions.some((entry) => entry.id === session.id)) return [] + const resolved = mention(session.mention) + + return resolved ? [{ id: session.id, mention: resolved }] : [] + }) + + const sessions = [...retainedSessions, ...request.sessions] + const retainedSessionLines = retainedSessions.map((session) => `\n${formatSessionReference(session)}`).join("") + return { sessionID, - text: request.text + notes, + text: request.text + retainedSessionLines + notes, files: [ // A stored file whose mention the edit deleted is dropped; unmentioned context stays. ...(payload?.files @@ -521,6 +539,7 @@ async function editedPromptInput( comments: notes ? (payload?.metadata?.["comments"] ?? []) : [], displayText: request.displayText, attachments: request.attachments, + sessions, }, } } diff --git a/packages/app/src/session/timeline/message-timeline.tsx b/packages/app/src/session/timeline/message-timeline.tsx index 85acc85e02b..951fed495a3 100644 --- a/packages/app/src/session/timeline/message-timeline.tsx +++ b/packages/app/src/session/timeline/message-timeline.tsx @@ -300,6 +300,7 @@ function MessageTimelineView( displayText: voice ? (voice.framing ?? voice.instruction) : value?.displayText, comments: value?.comments ?? (parsed ? [parsed] : []), references: value?.attachments, + sessions: value?.sessions, voice: !!voice, } }, diff --git a/packages/session-ui/src/actions.ts b/packages/session-ui/src/actions.ts index a78ad656a5c..fde71eb87ee 100644 --- a/packages/session-ui/src/actions.ts +++ b/packages/session-ui/src/actions.ts @@ -25,6 +25,16 @@ export type SessionUserAttachmentReference = { path: string } +/** A session referenced from a user prompt. */ +export type SessionUserSessionReference = { + id: string + mention: { + start: number + end: number + text: string + } +} + export type SessionUserActions = { openAttachment?: (file: PromptFileAttachment) => void revert?: (input: { sessionID: string; messageID: string }) => Promise | void diff --git a/packages/session-ui/src/components/message-part.css b/packages/session-ui/src/components/message-part.css index 6636ae6edb9..ea6ea3573f6 100644 --- a/packages/session-ui/src/components/message-part.css +++ b/packages/session-ui/src/components/message-part.css @@ -186,13 +186,35 @@ } [data-highlight="file"], - [data-highlight="agent"] { + [data-highlight="agent"], + [data-highlight="session"] { color: inherit; font-weight: 600; direction: ltr; unicode-bidi: isolate; } + button[data-highlight="session"] { + display: inline; + padding: 0; + border: 0; + background: none; + font: inherit; + font-weight: 600; + cursor: pointer; + + &:hover { + text-decoration: underline; + text-underline-offset: 2px; + } + + &:focus-visible { + outline: 2px solid currentColor; + outline-offset: 2px; + border-radius: 2px; + } + } + [data-slot="user-message-mention-prefix"] { color: var(--user-message-mention-prefix-color); transition: color 200ms ease; diff --git a/packages/session-ui/src/message/current-message.tsx b/packages/session-ui/src/message/current-message.tsx index c28b8159348..3402147bb3a 100644 --- a/packages/session-ui/src/message/current-message.tsx +++ b/packages/session-ui/src/message/current-message.tsx @@ -1,7 +1,12 @@ import type { SessionMessageAssistant, SessionMessageAssistantTool, SessionMessageUser } from "@opencode/client/promise" import { Match, Switch, type ComponentProps } from "solid-js" import { GenUI } from "@opencode/plugin-genui/genui" -import type { SessionUserActions, SessionUserAttachmentReference, SessionUserComment } from "../actions" +import type { + SessionUserActions, + SessionUserAttachmentReference, + SessionUserComment, + SessionUserSessionReference, +} from "../actions" import { AssistantReasoningContent, AssistantTextContent, CurrentUserMessageDisplay } from "./message-content" import { CurrentContextToolGroup, @@ -14,7 +19,12 @@ import { currentStreamingInput } from "./streaming-input" // Registers the genui_render renderer with the tool registry. import "../genui/tool" -export type { SessionUserActions, SessionUserAttachmentReference, SessionUserComment } from "../actions" +export type { + SessionUserActions, + SessionUserAttachmentReference, + SessionUserComment, + SessionUserSessionReference, +} from "../actions" export { SessionShellMessage } from "../tools/tool-renderer" @@ -26,6 +36,7 @@ export function SessionUserMessage(props: { displayText?: string comments?: SessionUserComment[] references?: SessionUserAttachmentReference[] + sessions?: SessionUserSessionReference[] voice?: boolean historicalAgent: string historicalModel: SessionMessageAssistant["model"] @@ -38,6 +49,7 @@ export function SessionUserMessage(props: { text={props.displayText ?? props.message.text} comments={props.comments} references={props.references} + sessions={props.sessions} voice={props.voice} agent={props.historicalAgent} model={props.historicalModel} diff --git a/packages/session-ui/src/message/message-content.tsx b/packages/session-ui/src/message/message-content.tsx index 8b06a8e3917..fd0209acf8a 100644 --- a/packages/session-ui/src/message/message-content.tsx +++ b/packages/session-ui/src/message/message-content.tsx @@ -12,11 +12,13 @@ import { import { createStore } from "solid-js/store" import { createMediaQuery } from "@solid-primitives/media" import { useData } from "../context" +import { useMarkdown } from "../context/markdown" import { useDialog } from "@opencode/ui/context/dialog" import { useI18n } from "@opencode/ui/context/i18n" import { Markdown } from "../components/markdown" import { ImagePreview } from "@opencode/ui/image-preview" import { getFilename } from "@opencode/util/path" +import { isFallbackTitle } from "@opencode/util/session-title-fallback" import { AttachmentCard } from "./attachment-card" import { CommentCard } from "./comment-card" import { TimelineSeparator } from "../components/timeline-separator" @@ -38,7 +40,12 @@ import type { SessionMessageCompaction, SessionMessageUser, } from "@opencode/client/promise" -import type { SessionUserActions, SessionUserAttachmentReference, SessionUserComment } from "../actions" +import type { + SessionUserActions, + SessionUserAttachmentReference, + SessionUserComment, + SessionUserSessionReference, +} from "../actions" import { attached, typeLabel } from "../components/message-file" export async function writeClipboard(text: string): Promise { @@ -266,6 +273,7 @@ export function CurrentUserMessageDisplay(props: { actions?: SessionUserActions comments?: SessionUserComment[] references?: SessionUserAttachmentReference[] + sessions?: SessionUserSessionReference[] voice?: boolean }) { const data = useData() @@ -279,6 +287,7 @@ export function CurrentUserMessageDisplay(props: { const waiting = createMemo(() => status() === "steering" || status() === "stranded") const attachments = createMemo(() => (props.message.files ?? []).filter(attached)) const references = createMemo(() => props.references ?? []) + const sessions = createMemo(() => props.sessions ?? []) const inlineFiles = createMemo(() => (props.message.files ?? []).filter((file) => !!file.mention)) const agents = createMemo(() => props.message.agents ?? []) const comments = createMemo(() => props.comments ?? []) @@ -402,7 +411,12 @@ export function CurrentUserMessageDisplay(props: {
0 ? "true" : undefined}> - + 0}> @@ -522,8 +536,33 @@ function CurrentHighlightedText(props: { text: string files: PromptFileAttachment[] agents: PromptAgentAttachment[] + sessions?: SessionUserSessionReference[] }) { + const data = useData() + const markdown = useMarkdown() + const segments = createMemo(() => { + let searchFrom = 0 + + const sessionMentions = (props.sessions ?? []).flatMap((session) => { + const mention = session.mention + + if (!mention.text) return [] + + const exact = + mention.start >= searchFrom && + mention.end >= mention.start && + props.text.slice(mention.start, mention.end) === mention.text + + const start = exact ? mention.start : props.text.indexOf(mention.text, searchFrom) + + if (start < 0) return [] + const end = start + mention.text.length + searchFrom = end + + return [{ start, end, type: "session" as const, sessionID: session.id }] + }) + const references = [ ...props.files.flatMap((file) => file.mention ? [{ start: file.mention.start, end: file.mention.end, type: "file" as const }] : [], @@ -531,6 +570,7 @@ function CurrentHighlightedText(props: { ...props.agents.flatMap((agent) => agent.mention ? [{ start: agent.mention.start, end: agent.mention.end, type: "agent" as const }] : [], ), + ...sessionMentions, ].sort((a, b) => a.start - b.start) const result: HighlightSegment[] = [] @@ -539,7 +579,11 @@ function CurrentHighlightedText(props: { if (reference.start < last) return if (reference.start > last) result.push({ text: props.text.slice(last, reference.start) }) - result.push({ text: props.text.slice(reference.start, reference.end), type: reference.type }) + result.push({ + text: props.text.slice(reference.start, reference.end), + type: reference.type, + sessionID: "sessionID" in reference ? reference.sessionID : undefined, + }) last = reference.end }) @@ -550,19 +594,45 @@ function CurrentHighlightedText(props: { return ( - {(segment) => ( - - + {(segment) => { + const text = createMemo(() => { + if (segment.type !== "session" || !segment.sessionID || !segment.text.startsWith("@")) return segment.text + const live = data.store.session.find((item) => item.id === segment.sessionID)?.title + + return live && !isFallbackTitle(live) ? `@${live}` : segment.text + }) + + const content = ( + @ - {segment.text.slice(1)} + {text().slice(1)} - - )} + ) + + if (segment.type === "session" && segment.sessionID) { + return ( + + ) + } + + return {content} + }} ) } -type HighlightSegment = { text: string; type?: "file" | "agent" } +type HighlightSegment = { text: string; type?: "file" | "agent" | "session"; sessionID?: string } /** A compaction the server admitted but has not started, drawn as the divider a started one opens with. */ export function SessionCompactionQueued() { diff --git a/packages/session-ui/src/timeline/session-timeline-row.tsx b/packages/session-ui/src/timeline/session-timeline-row.tsx index 901c6bd22be..5ab7093e110 100644 --- a/packages/session-ui/src/timeline/session-timeline-row.tsx +++ b/packages/session-ui/src/timeline/session-timeline-row.tsx @@ -9,7 +9,12 @@ import { Option, Predicate, Schema } from "effect" import { For, Show, createEffect, createMemo, type Accessor, type JSX } from "solid-js" import { DiffChanges } from "@opencode/ui/diff-changes" import { Dynamic } from "solid-js/web" -import type { SessionUserActions, SessionUserAttachmentReference, SessionUserComment } from "../actions" +import type { + SessionUserActions, + SessionUserAttachmentReference, + SessionUserComment, + SessionUserSessionReference, +} from "../actions" import { useData } from "../context" import { TimelineSeparator } from "../components/timeline-separator" import { @@ -56,6 +61,7 @@ export type SessionUserPresentation = { displayText?: string comments?: SessionUserComment[] references?: SessionUserAttachmentReference[] + sessions?: SessionUserSessionReference[] /** A voice call's agent sent it on the user's behalf. */ voice?: boolean } @@ -810,6 +816,7 @@ export function createSessionTimelineRowRenderer(input: { displayText={presentation()?.displayText} comments={presentation()?.comments} references={presentation()?.references} + sessions={presentation()?.sessions} voice={presentation()?.voice} historicalAgent={context()?.agent ?? ""} historicalModel={context()?.model ?? { id: "", providerID: "" }}