feat(app): make session IDs easier to find and copy (#63083)

This commit is contained in:
usrnk1
2026-11-10 11:39:21 +01:00
committed by GitHub
Unverified
parent 57719d7fd4
commit d619c94090
22 changed files with 737 additions and 49 deletions
+7 -1
View File
@@ -32,11 +32,17 @@ test("mention a session by title, send its stable token, and open its own tab",
await view.editor.pressSequentially(" mid")
await suggestions.getByRole("button", { name: /Auth middleware/ }).click()
await expect(view.editor.locator('[data-mention="session"]')).toHaveText("@Auth middleware")
// The mention's context menu copies the ID it stands for; the rest of the editor keeps the native menu.
await view.editor.locator('[data-mention="session"]').click({ button: "right" })
await page.getByRole("menuitem", { name: "Copy Session ID", exact: true }).click()
await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe(target)
await expect(page.getByRole("menu")).toHaveCount(0)
await view.editor.press("End")
await view.editor.press("Enter")
await expect.poll(() => prompts.length).toBe(1)
expect(prompts[0]?.text).toBe(`Compare with @session:${target} `)
const message = page.locator('[data-timeline-row="UserMessage"]')
const chip = message.getByRole("button", { name: "Auth middleware", exact: true })
const chip = message.getByRole("button", { name: "@Auth middleware", exact: true })
await expect(chip).toBeVisible()
await chip.click()
await expect(page).toHaveURL(new RegExp(`${target}$`))
@@ -331,16 +331,37 @@ test.describe("session ID links", () => {
await expectSessionTitle(page, "Timeline visual stability")
const markdown = page.locator('[data-component="markdown"]').filter({ hasText: "Visit" })
await expect(markdown).toHaveAttribute("data-markdown-ready", "")
await expect(markdown.getByRole("button", { name: "Linked session", exact: true })).toHaveCount(2)
await expect(markdown.getByRole("button", { name: "@Linked session", exact: true })).toHaveCount(2)
await markdown
.locator("p")
.filter({ hasText: "Or" })
.getByRole("button", { name: "Linked session", exact: true })
.getByRole("button", { name: "@Linked session", exact: true })
.press("Enter")
await expectPath(page, sessionHref(target))
await expect(page.locator(`[data-titlebar-tab-link][href$="/session/${target}"]`)).toContainText("Linked session")
})
test("titles a session this window never loaded and copies its ID from the context menu", async ({
page,
context,
}) => {
await context.grantPermissions(["clipboard-read", "clipboard-write"])
await setupTimeline(page, {
sessions: [session(), session({ id: target, title: "Linked session" })],
messages: [userMessage(), assistantMessage([textPart("prt_session_menu", `Visit ${target}.`)])],
})
await expectSessionTitle(page, "Timeline visual stability")
const markdown = page.locator('[data-component="markdown"]').filter({ hasText: "Visit" })
await expect(markdown).toHaveAttribute("data-markdown-ready", "")
await markdown.getByRole("button", { name: "@Linked session", exact: true }).click({ button: "right" })
await expect(page.getByRole("menuitem", { name: "Open Session", exact: true })).toBeVisible()
await expect(page.getByRole("menuitem", { name: "Copy Session Title", exact: true })).toBeVisible()
await page.getByRole("menuitem", { name: "Copy Session ID", exact: true }).click()
await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe(target)
await expect(page.getByRole("menu")).toHaveCount(0)
await expectPath(page, sessionHref(sessionID))
})
test("does not navigate to an ID that is absent from the current server", async ({ page }) => {
await setupTimeline(page, {
messages: [userMessage(), assistantMessage([textPart("prt_session_missing", `See ${missing}.`)])],
@@ -2,8 +2,10 @@
content: "\200B";
}
/* Transcript session references match this (packages/session-ui/src/components/markdown.css). */
[data-component="composer-editor"] [data-mention="session"] {
color: var(--v2-text-text-muted);
font-weight: var(--font-weight-medium);
}
/* Matches the 16px session title fade. The top fade only covers the editor's 16px top padding until text scrolls
@@ -28,6 +28,7 @@ import { Menu } from "@opencode/ui/menu"
import { MenuScroll } from "@opencode/ui/menu-scroll"
import { Tooltip } from "@opencode/ui/tooltip"
import { AttachmentCard } from "@opencode/session-ui/attachment-card"
import { useMarkdown } from "@opencode/session-ui/context/markdown"
import { ProgressCircle } from "@opencode/ui/progress-circle"
import type { Upload } from "../attachments/uploads"
import { CommentCard, commentCardTarget, quoteTooltip } from "@opencode/session-ui/comment-card"
@@ -98,6 +99,7 @@ export type ComposerEditorProps = {
export function ComposerEditor(props: ComposerEditorProps) {
const i18n = useI18n()
const markdown = useMarkdown()
const state = props.controller.state
const view = props.controller.view
const suggestionsID = createUniqueId()
@@ -324,6 +326,16 @@ export function ComposerEditor(props: ComposerEditorProps) {
"unicode-bidi": mode() === "normal" ? "plaintext" : undefined,
"text-align": "start",
}}
onContextMenu={(event) => {
const target = event.target instanceof Element ? event.target : undefined
const mention = target?.closest<HTMLElement>('[data-mention="session"]')
const part = mention ? mentionParts.get(mention) : undefined
const menu = markdown?.sessionMenu
if (part?.type !== "session" || !menu) return
event.preventDefault()
menu({ sessionID: part.id, x: event.clientX, y: event.clientY })
}}
onInput={(event) => {
const prompt = parseComposerEditor(event.currentTarget)
const cursor = getCursorPosition(event.currentTarget) ?? promptLength(prompt)
+3
View File
@@ -620,6 +620,9 @@ export const dict = {
"session.panel.bottom": "Bottom panel",
"session.panel.bottom.hide": "Hide bottom panel",
"session.error.notFound": "This session cannot be found",
"session.reference.open": "Open Session",
"session.reference.copyTitle": "Copy Session Title",
"session.reference.copyTitle.failed": "Failed to copy session title",
"session.error.notFound.description": "This tab points to a session that no longer exists on this server.",
"session.error.notFound.closeTab": "Close Tab",
"session.error.incompatible": "This server version isn't supported",
@@ -16,6 +16,7 @@ import type { Schema } from "effect"
import { useDialog } from "@opencode/ui/context/dialog"
import { useTheme } from "@opencode/ui/theme/context"
import { toaster } from "@opencode/ui/toast"
import { writeClipboard } from "@opencode/session-ui/copy"
import { base64Encode } from "@opencode/util/encode"
import { uuid } from "@opencode/util/uuid"
import {
@@ -294,7 +295,11 @@ export function createHostApis() {
},
}),
system: () => ({
copy: (text) => platform.writeClipboardText?.(text) ?? navigator.clipboard.writeText(text),
async copy(text) {
if (platform.writeClipboardText) return platform.writeClipboardText(text)
if (!(await writeClipboard(text))) throw new Error(language.t("common.requestFailed"))
},
async save(file) {
if (platform.saveFile) return platform.saveFile({ defaultPath: file.name }, file.content)
const url = URL.createObjectURL(new Blob([file.content], { type: "application/octet-stream" }))
@@ -0,0 +1,106 @@
import { Show } from "solid-js"
import { Portal } from "solid-js/web"
import { Menu } from "@opencode/ui/menu"
import { writeClipboard } from "@opencode/session-ui/copy"
import { useLanguage } from "@/runtime/i18n/language"
import { usePlatform } from "@/runtime/platform/platform"
import { useData } from "@/runtime/server/current"
import { showToast } from "@/shell/notifications/toast"
export type SessionReferenceMenuTarget = { sessionID: string; x: number; y: number }
export function SessionReferenceMenu(props: {
target: SessionReferenceMenuTarget | undefined
currentSessionID: string | undefined
onOpenSession: (sessionID: string) => void
onClose: () => void
}) {
const language = useLanguage()
const platform = usePlatform()
const data = useData()
const title = () => {
const session = props.target ? data.session.get(props.target.sessionID) : undefined
return session && !session.time.archived ? session.title || undefined : undefined
}
const copy = async (text: string, failure: { title: string; description: string }) => {
try {
const written = platform.writeClipboardText
? await platform.writeClipboardText(text).then(() => true)
: await writeClipboard(text)
if (!written) throw new Error(failure.description)
showToast({ variant: "success", icon: "circle-check", title: language.t("common.copied"), description: text })
} catch (err) {
showToast({
variant: "error",
title: failure.title,
description: err instanceof Error ? err.message : failure.description,
})
}
}
return (
<Menu
modal={false}
placement="bottom-start"
gutter={2}
open={!!props.target}
onOpenChange={(open) => {
if (!open) props.onClose()
}}
>
{/* Portaled so a transformed ancestor never offsets the fixed trigger. */}
<Portal>
<Menu.Trigger
as="span"
aria-hidden="true"
disabled
class="pointer-events-none fixed size-px"
style={{ left: `${props.target?.x ?? 0}px`, top: `${props.target?.y ?? 0}px` }}
/>
</Portal>
<Menu.Portal>
<Menu.Content onCloseAutoFocus={(event) => event.preventDefault()}>
<Show when={props.target?.sessionID}>
{(sessionID) => (
<>
<Show when={sessionID() !== props.currentSessionID}>
<Menu.Item onSelect={() => props.onOpenSession(sessionID())}>
{language.t("session.reference.open")}
</Menu.Item>
</Show>
<Menu.Item
onSelect={() =>
void copy(sessionID(), {
title: language.t("toast.session.copyID.failed.title"),
description: language.t("toast.session.copyID.failed.description"),
})
}
>
{language.t("command.session.copyID")}
</Menu.Item>
<Show when={title()}>
{(value) => (
<Menu.Item
onSelect={() =>
void copy(value(), {
title: language.t("session.reference.copyTitle.failed"),
description: language.t("common.requestFailed"),
})
}
>
{language.t("session.reference.copyTitle")}
</Menu.Item>
)}
</Show>
</>
)}
</Show>
</Menu.Content>
</Menu.Portal>
</Menu>
)
}
@@ -81,6 +81,7 @@ export function createTimelineCache(
const readImage = select(() => markdown?.readImage)
const openSession = select(() => markdown?.openSession)
const sessionTitle = select(() => markdown?.sessionTitle)
const sessionMenu = select(() => markdown?.sessionMenu)
const turnDiff = select(() => data.turnDiff)
// The Location's config is a query: read it in the reader and only while selected, so a pending config
@@ -163,6 +164,9 @@ export function createTimelineCache(
get sessionTitle() {
return sessionTitle()
},
get sessionMenu() {
return sessionMenu()
},
},
view,
),
@@ -0,0 +1,111 @@
import type { SessionInfo } from "@opencode/client/promise"
import { describe, expect, test } from "bun:test"
import {
createSessionReferenceLookupState,
transitionSessionReferenceLookup,
type SessionReferenceLookupEvent,
type SessionReferenceLookupState,
} from "./session-reference-lookup-machine"
const ID = "ses_0123456789abcdefghijklmnop"
function info(archived?: number): SessionInfo {
return {
id: ID,
projectID: "proj",
cost: 0,
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
location: { directory: "/project" },
title: "Linked",
time: { created: 1, updated: 1, archived },
}
}
function replay(events: readonly SessionReferenceLookupEvent[], state = createSessionReferenceLookupState()) {
return events.reduce<SessionReferenceLookupState>(
(current, event) => transitionSessionReferenceLookup(current, event).state,
state,
)
}
describe("transitionSessionReferenceLookup", () => {
test("looks an unknown ID up once and remembers the session it finds", () => {
const requested = transitionSessionReferenceLookup(createSessionReferenceLookupState(), {
type: "requested",
sessionID: ID,
})
expect(requested.effects).toEqual([{ type: "fetch", sessionID: ID, attempt: 1 }])
// Markdown asks again on every render while the request runs, and after it settles.
const repeated = transitionSessionReferenceLookup(requested.state, { type: "requested", sessionID: ID })
expect(repeated.state).toBe(requested.state)
expect(repeated.effects).toEqual([])
const session = info()
const resolved = transitionSessionReferenceLookup(requested.state, {
type: "resolved",
sessionID: ID,
attempt: 1,
session,
})
expect(resolved.effects).toEqual([{ type: "remember", session }])
expect(transitionSessionReferenceLookup(resolved.state, { type: "requested", sessionID: ID }).effects).toEqual([])
})
test("a missing, failed or archived session is not asked for again and is not remembered", () => {
const missing = transitionSessionReferenceLookup(replay([{ type: "requested", sessionID: ID }]), {
type: "unavailable",
sessionID: ID,
attempt: 1,
})
expect(missing.effects).toEqual([])
expect(transitionSessionReferenceLookup(missing.state, { type: "requested", sessionID: ID }).effects).toEqual([])
const archived = transitionSessionReferenceLookup(replay([{ type: "requested", sessionID: ID }]), {
type: "resolved",
sessionID: ID,
attempt: 1,
session: info(5),
})
expect(archived.effects).toEqual([])
})
test("a server change aborts earlier lookups, ignores their answers and asks again", () => {
const changed = transitionSessionReferenceLookup(replay([{ type: "requested", sessionID: ID }]), {
type: "server.changed",
})
expect(changed.effects).toEqual([{ type: "abort-all" }])
const stale = transitionSessionReferenceLookup(changed.state, {
type: "resolved",
sessionID: ID,
attempt: 1,
session: info(),
})
expect(stale.state).toBe(changed.state)
expect(stale.effects).toEqual([])
expect(transitionSessionReferenceLookup(changed.state, { type: "requested", sessionID: ID }).effects).toEqual([
{ type: "fetch", sessionID: ID, attempt: 2 },
])
})
test("disposing aborts lookups and ignores later answers", () => {
const disposed = transitionSessionReferenceLookup(replay([{ type: "requested", sessionID: ID }]), {
type: "disposed",
})
expect(disposed.effects).toEqual([{ type: "abort-all" }])
expect(
transitionSessionReferenceLookup(disposed.state, { type: "resolved", sessionID: ID, attempt: 1, session: info() })
.effects,
).toEqual([])
})
})
@@ -0,0 +1,86 @@
import type { SessionInfo } from "@opencode/client/promise"
/**
* Lookups of sessions the transcript references but this window has not loaded. Each ID is looked up once per
* provider: `pending` while the request runs, `settled` after it, whether the session was found, missing, archived or
* the request failed. A found session goes into the session cache, which is what renders the reference's title.
*/
export type SessionReferenceLookupState =
| {
readonly status: "active"
readonly attempt: number
readonly entries: ReadonlyMap<string, { readonly status: "pending"; readonly attempt: number } | SettledEntry>
}
| { readonly status: "disposed" }
type SettledEntry = { readonly status: "settled" }
export type SessionReferenceLookupEvent =
| { readonly type: "requested"; readonly sessionID: string }
| { readonly type: "resolved"; readonly sessionID: string; readonly attempt: number; readonly session: SessionInfo }
/** Not found, archived, or the request failed: the reference stays its raw ID. */
| { readonly type: "unavailable"; readonly sessionID: string; readonly attempt: number }
/** The provider moved to another server, so every earlier answer is for the wrong one. */
| { readonly type: "server.changed" }
| { readonly type: "disposed" }
export type SessionReferenceLookupEffect =
| { readonly type: "fetch"; readonly sessionID: string; readonly attempt: number }
| { readonly type: "remember"; readonly session: SessionInfo }
| { readonly type: "abort-all" }
export type SessionReferenceLookupTransition = {
readonly state: SessionReferenceLookupState
readonly effects: readonly SessionReferenceLookupEffect[]
}
const NONE: readonly SessionReferenceLookupEffect[] = []
const SETTLED: SettledEntry = Object.freeze({ status: "settled" })
export function createSessionReferenceLookupState(): SessionReferenceLookupState {
return { status: "active", attempt: 0, entries: new Map() }
}
export function transitionSessionReferenceLookup(
state: SessionReferenceLookupState,
event: SessionReferenceLookupEvent,
): SessionReferenceLookupTransition {
if (state.status === "disposed") return { state, effects: NONE }
if (event.type === "disposed") return { state: { status: "disposed" }, effects: [{ type: "abort-all" }] }
if (event.type === "server.changed") {
if (state.entries.size === 0) return { state, effects: NONE }
return { state: { status: "active", attempt: state.attempt, entries: new Map() }, effects: [{ type: "abort-all" }] }
}
if (event.type === "requested") {
if (state.entries.has(event.sessionID)) return { state, effects: NONE }
const attempt = state.attempt + 1
return {
state: {
status: "active",
attempt,
entries: new Map(state.entries).set(event.sessionID, { status: "pending", attempt }),
},
effects: [{ type: "fetch", sessionID: event.sessionID, attempt }],
}
}
const entry = state.entries.get(event.sessionID)
if (entry?.status !== "pending" || entry.attempt !== event.attempt) return { state, effects: NONE }
const next: SessionReferenceLookupState = {
status: "active",
attempt: state.attempt,
entries: new Map(state.entries).set(event.sessionID, SETTLED),
}
if (event.type === "unavailable" || event.session.time.archived) return { state: next, effects: NONE }
return { state: next, effects: [{ type: "remember", session: event.session }] }
}
@@ -16,6 +16,7 @@ import { useLanguage } from "@/runtime/i18n/language"
import { showToast } from "@/shell/notifications/toast"
import { SessionExportProvider } from "@/session/commands/export-session"
import { createTurnDiffCache } from "@/session/timeline/turn-diffs"
import { SessionReferenceMenu, type SessionReferenceMenuTarget } from "@/session/session-reference-menu"
import { useSettings } from "@/settings/model"
import {
INITIAL_SESSION_UI_NAVIGATE_STATE,
@@ -24,6 +25,12 @@ import {
type SessionUINavigateEffect,
type SessionUINavigateEvent,
} from "./session-ui-navigate-machine"
import {
createSessionReferenceLookupState,
transitionSessionReferenceLookup,
type SessionReferenceLookupEffect,
type SessionReferenceLookupEvent,
} from "./session-reference-lookup-machine"
export function SessionUIProvider(
props: ParentProps<{
@@ -139,12 +146,55 @@ export function SessionUIProvider(
const openReferencedSession = (sessionID: string) =>
dispatchNavigation({ type: "referenced.requested", origin: untrack(origin), targetSessionID: sessionID })
let referenceLookup = createSessionReferenceLookupState()
const referenceLookups = new Map<number, AbortController>()
const dispatchReferenceLookup = (event: SessionReferenceLookupEvent) => {
const next = transitionSessionReferenceLookup(referenceLookup, event)
referenceLookup = next.state
next.effects.forEach((effect) =>
Promise.try(() => runReferenceLookup(effect)).catch((cause: unknown) =>
console.error("[session.reference]", cause),
),
)
}
function runReferenceLookup(effect: SessionReferenceLookupEffect) {
if (effect.type === "abort-all") {
referenceLookups.forEach((controller) => controller.abort())
referenceLookups.clear()
return
}
if (effect.type === "remember") return data.session.remember(effect.session)
const controller = new AbortController()
referenceLookups.set(effect.attempt, controller)
void Promise.try(() => serverSDK.api.session.get({ sessionID: effect.sessionID }, { signal: controller.signal }))
.finally(() => referenceLookups.delete(effect.attempt))
.then(
(session) =>
dispatchReferenceLookup({ type: "resolved", sessionID: effect.sessionID, attempt: effect.attempt, session }),
() => dispatchReferenceLookup({ type: "unavailable", sessionID: effect.sessionID, attempt: effect.attempt }),
)
}
createEffect(on(() => props.server, () => dispatchReferenceLookup({ type: "server.changed" }), { defer: true }))
onCleanup(() => dispatchReferenceLookup({ type: "disposed" }))
const sessionTitle = (id: string) => {
if (id === params.id) return
const session = data.session.get(id)
// Markdown calls this inside its render effect.
if (!session) untrack(() => dispatchReferenceLookup({ type: "requested", sessionID: id }))
return session && !session.time.archived ? session.title || language.t("command.session.new") : undefined
}
const [referenceMenu, setReferenceMenu] = createSignal<SessionReferenceMenuTarget>()
const providers = useProviders(directory)
const config = useQuery(() => ({
@@ -220,8 +270,19 @@ export function SessionUIProvider(
onSessionHref={href}
backgroundCompaction={backgroundCompaction()}
>
<MarkdownProvider readImage={readImage()} openSession={openReferencedSession} sessionTitle={sessionTitle}>
<MarkdownProvider
readImage={readImage()}
openSession={openReferencedSession}
sessionTitle={sessionTitle}
sessionMenu={(target) => setReferenceMenu({ ...target })}
>
<SessionExportProvider>{props.children}</SessionExportProvider>
<SessionReferenceMenu
target={referenceMenu()}
currentSessionID={params.id}
onOpenSession={openReferencedSession}
onClose={() => setReferenceMenu(undefined)}
/>
</MarkdownProvider>
</DataProvider>
</LocalProvider>
+79
View File
@@ -113,6 +113,49 @@ function ToggleCell(props: {
)
}
function CopyCell(props: { inline?: boolean; label: string; onClick?: () => void; tip: string; value: string }) {
const content = () => (
<button
type="button"
disabled={!props.onClick}
aria-label={`${props.label}: ${props.value}`}
classList={{
"flex min-w-0 items-center font-mono enabled:hover:bg-surface-raised-base focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-[-2px] focus-visible:outline-v2-border-border-focus": true,
"min-h-[20px] w-fit justify-start rounded px-1.5 py-0.5 text-left": !!props.inline,
"min-h-[42px] w-full flex-col justify-center rounded-[8px] px-0.5 py-1 text-center": !props.inline,
}}
onClick={() => props.onClick?.()}
>
<span
classList={{
flex: true,
"-translate-y-px items-baseline gap-1.5": !!props.inline,
"flex-col items-center": !props.inline,
}}
>
<span dir="ltr" class="text-[10px] leading-none font-black tracking-[0.04em] opacity-70">
{props.label}
</span>
<span
dir="ltr"
classList={{
"text-[11px] leading-none font-bold tabular-nums": true,
"uppercase opacity-70": !props.onClick,
}}
>
{props.value}
</span>
</span>
</button>
)
return (
<Tooltip appearance={props.inline ? "compact" : "standard"} value={props.tip} placement="top">
{content()}
</Tooltip>
)
}
export default function DebugBar(props: {
/** The dev server's layout tools: the direction and focus toggles. */
devTools?: boolean
@@ -195,6 +238,29 @@ export default function DebugBar(props: {
onCleanup(() => dispatchFocus({ type: "disposed" }))
const sessionID = () => target()?.id
const sessionTip = () => {
const id = sessionID()
return id ? ctx.t("session.tip", { id }) : ctx.t("session.none")
}
const copySessionID = () => {
const id = sessionID()
if (!id) return
void ctx.system.copy(id).then(
() => showToast({ variant: "success", title: ctx.t("common.copied"), description: id }),
(cause) =>
showToast({
variant: "error",
title: ctx.t("session.copyFailed"),
description: cause instanceof Error ? cause.message : String(cause),
}),
)
}
return (
<aside
aria-label={ctx.t("providerAriaLabel")}
@@ -226,6 +292,13 @@ export default function DebugBar(props: {
/>
</Tooltip>
</Show>
<CopyCell
label={ctx.t("session.label")}
tip={sessionTip()}
value={shortSessionID(sessionID()) ?? na()}
inline={props.inline}
onClick={sessionID() ? copySessionID : undefined}
/>
<Cell
label={ctx.t("duration.label")}
tip={ctx.t("duration.tip")}
@@ -324,6 +397,12 @@ export default function DebugBar(props: {
)
}
function shortSessionID(id: string | undefined) {
if (!id) return
return `${id.slice(0, 8)}…${id.slice(-4)}`
}
// The bar's speed cell steps through the common slow-downs, then back to full speed.
function nextSpeed(speed: number) {
return [0.5, 0.25, 1].find((step) => step < speed) ?? 1
@@ -15,6 +15,10 @@ export default {
"duration.tip": "Time from the prompt that started the latest turn until its response completed.",
"tps.label": "TPS",
"tps.tip": "Output and reasoning tokens per second across the latest turn's model requests, excluding tool time.",
"session.label": "SESSION",
"session.tip": "{{id}}. Click to copy.",
"session.none": "No session open",
"session.copyFailed": "Failed to copy session ID",
"memory.label": "MEMLOG",
"memory.tip":
"Memory diagnostics: log app memory to the desktop logs every 30 seconds. Stays on across restarts until turned off; the bar stays open while it runs.",
@@ -83,6 +83,21 @@ test("wraps a partial selection in its semantic ancestors", () => {
expect(markdownClipboardHtml(root, codeRange)).toBe("<pre><code>let</code></pre>")
})
test("writes session references as the IDs they stand for", () => {
const root = markdownRoot(
[
'<p>See <button type="button" class="markdown-session-link" data-session-id="ses_a"',
' data-session-reference="ses_a">@Auth middleware</button></p>',
].join(""),
)
expect(markdownClipboardHtml(root, rangeOver(root))).toBe("<p>See <code>ses_a</code></p>")
const range = document.createRange()
range.selectNodeContents(root.querySelector("button")!)
expect(markdownClipboardHtml(root, range)).toBe("<p><code>ses_a</code></p>")
})
test("keeps web links and drops local paths, scripts, and decorative icons", () => {
const root = markdownRoot(
[
@@ -1,3 +1,5 @@
import { sessionReferenceRange } from "./markdown-session-links"
// Chromium's default copy inlines computed styles, so text copied from a dark theme pastes as light text on the
// destination's white page. Copied HTML keeps only semantic markup and lets the destination style it.
@@ -68,8 +70,10 @@ function hasProtocol(value: string, protocols: Set<string>) {
}
export function markdownClipboardHtml(root: Element, range: Range) {
const ancestor = range.commonAncestorContainer
let content: Node = range.cloneContents()
const selection = sessionReferenceRange(range)
const ancestor = selection.commonAncestorContainer
let content: Node = selection.cloneContents()
for (
let element = ancestor instanceof Element ? ancestor : ancestor.parentElement;
@@ -84,6 +88,11 @@ export function markdownClipboardHtml(root: Element, range: Range) {
const container = document.createElement("div")
container.appendChild(content)
container.querySelectorAll<HTMLElement>("[data-session-reference]").forEach((reference) => {
const code = document.createElement("code")
code.textContent = reference.dataset.sessionReference ?? ""
reference.replaceWith(code)
})
container.querySelectorAll(removedSelector).forEach((element) => element.remove())
container.querySelectorAll("*").forEach(sanitizeAttributes)
@@ -1,6 +1,6 @@
import { GlobalRegistrator } from "@happy-dom/global-registrator"
import { afterAll, beforeAll, expect, test } from "bun:test"
import { markSessionLinks, setupSessionLinks } from "./markdown-session-links"
import { markSessionLinks, sessionReferenceClipboardText, setupSessionLinks } from "./markdown-session-links"
const first = "ses_0123456789abcdefghijklmnop"
@@ -19,11 +19,11 @@ test("links complete IDs in prose and inline code without changing fenced code o
const links = root.querySelectorAll<HTMLButtonElement>("button[data-session-id]")
expect([...links].map((button) => button.dataset.sessionId)).toEqual([first, second])
expect(links[0]?.textContent).toBe("Auth middleware")
expect(links[1]?.textContent).toBe("Release notes")
expect(links[0]?.textContent).toBe("@Auth middleware")
expect(links[1]?.textContent).toBe("@Release notes")
expect(root.querySelector("pre button")).toBeNull()
expect(root.querySelector("a button")).toBeNull()
expect(root.textContent).toBe(`Open Auth middleware, then Release notes. See ${first}.${first}`)
expect(root.textContent).toBe(`Open @Auth middleware, then @Release notes. See ${first}.${first}`)
})
test("ignores incomplete IDs, identifiers, code snippets and IDs in URLs", () => {
@@ -61,16 +61,70 @@ test("unknown IDs stay mono; tokens and bare IDs follow current titles and delet
const root = document.createElement("div")
root.innerHTML = `<p>@session:${first} and ${second} and ses_short</p>`
markSessionLinks(root, (id) => (id === first ? "Original" : undefined))
expect(root.querySelector("button")?.textContent).toBe("Original")
expect(root.querySelector("button")?.textContent).toBe("@Original")
expect(root.querySelector("code")?.textContent).toBe(second)
expect(root.querySelectorAll("button").length).toBe(1)
markSessionLinks(root, () => "Renamed <session>")
expect([...root.querySelectorAll("button")].map((link) => link.textContent)).toEqual([
"Renamed <session>",
"Renamed <session>",
"@Renamed <session>",
"@Renamed <session>",
])
expect(root.querySelector("session")).toBeNull()
markSessionLinks(root, () => undefined)
expect(root.querySelector("button")).toBeNull()
expect([...root.querySelectorAll("code")].map((code) => code.textContent)).toEqual([`@session:${first}`, second])
})
test("right-clicking a linked or plain reference opens its menu at the pointer", () => {
const root = document.createElement("div")
const menus: { sessionID: string; x: number; y: number }[] = []
const dispose = setupSessionLinks(
root,
() => undefined,
() => (input) => menus.push(input),
)
root.innerHTML = `<p>${first} and ${second}</p>`
markSessionLinks(root, (id) => (id === first ? "Auth middleware" : undefined))
const link = new MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX: 12, clientY: 34 })
root.querySelector("button")?.dispatchEvent(link)
const plain = new MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX: 5, clientY: 6 })
root.querySelector("code")?.dispatchEvent(plain)
const prose = new MouseEvent("contextmenu", { bubbles: true, cancelable: true })
root.querySelector("p")?.dispatchEvent(prose)
expect(menus).toEqual([
{ sessionID: first, x: 12, y: 34 },
{ sessionID: second, x: 5, y: 6 },
])
expect([link.defaultPrevented, plain.defaultPrevented, prose.defaultPrevented]).toEqual([true, true, false])
dispose()
})
test("a reference keeps the native menu when the host has none", () => {
const root = document.createElement("div")
const dispose = setupSessionLinks(root, () => undefined)
root.innerHTML = `<p>${first}</p>`
markSessionLinks(root, title)
const event = new MouseEvent("contextmenu", { bubbles: true, cancelable: true })
root.querySelector("button")?.dispatchEvent(event)
expect(event.defaultPrevented).toBe(false)
dispose()
})
test("copied text writes each selected reference as its source instead of its title", () => {
const root = document.createElement("div")
document.body.append(root)
root.innerHTML = `<p>Open @session:${first}, then <code>${second}</code>.</p><p>Plain</p>`
markSessionLinks(root, title)
const range = document.createRange()
range.selectNodeContents(root.querySelector("p")!)
expect(sessionReferenceClipboardText(root, [range])).toBe(`Open @session:${first}, then ${second}.`)
expect(root.childElementCount).toBe(2)
range.selectNodeContents(root.querySelector("button")!)
expect(sessionReferenceClipboardText(root, [range])).toBe(`@session:${first}`)
const plain = document.createRange()
plain.selectNodeContents(root.querySelectorAll("p")[1]!)
expect(sessionReferenceClipboardText(root, [plain])).toBeUndefined()
root.remove()
})
@@ -11,7 +11,11 @@ export function markSessionLinks(root: HTMLElement, title: SessionTitle) {
if (!mention) return
const label = title(mention.id)
if (element.textContent === (label ?? source) && (element.tagName === "BUTTON") === (label !== undefined)) return
if (
element.textContent === (label === undefined ? source : `@${label}`) &&
(element.tagName === "BUTTON") === (label !== undefined)
)
return
element.replaceWith(sessionReference(mention, source, label))
})
@@ -63,6 +67,7 @@ function sessionReference(mention: SessionMention, source: string, title: string
if (title === undefined) {
const code = document.createElement("code")
code.className = "markdown-session-id"
code.dataset.sessionId = mention.id
code.dataset.sessionReference = source
code.textContent = source
@@ -75,12 +80,18 @@ function sessionReference(mention: SessionMention, source: string, title: string
button.dataset.sessionId = mention.id
button.dataset.sessionReference = source
button.title = mention.id
button.textContent = title
button.textContent = `@${title}`
return button
}
export function setupSessionLinks(root: HTMLElement, open: () => ((id: string) => void) | undefined) {
export type SessionReferenceMenu = (input: { sessionID: string; x: number; y: number }) => void
export function setupSessionLinks(
root: HTMLElement,
open: () => ((id: string) => void) | undefined,
menu?: () => SessionReferenceMenu | undefined,
) {
const click = (event: MouseEvent) => {
if (event.defaultPrevented || !(event.target instanceof Element)) return
const button = event.target.closest("button[data-session-id]")
@@ -93,7 +104,80 @@ export function setupSessionLinks(root: HTMLElement, open: () => ((id: string) =
handler(button.dataset.sessionId!)
}
root.addEventListener("click", click)
const contextMenu = (event: MouseEvent) => {
const reference = sessionReferenceTarget(root, event.target)
const handler = menu?.()
return () => root.removeEventListener("click", click)
if (event.defaultPrevented || !reference || !handler) return
event.preventDefault()
event.stopPropagation()
handler({ sessionID: reference.dataset.sessionId!, x: event.clientX, y: event.clientY })
}
const keyDown = (event: KeyboardEvent) => {
if (event.key !== "ContextMenu" && (event.key !== "F10" || !event.shiftKey)) return
const reference = sessionReferenceTarget(root, event.target)
const handler = menu?.()
if (event.defaultPrevented || !reference || !handler) return
const bounds = reference.getBoundingClientRect()
event.preventDefault()
handler({ sessionID: reference.dataset.sessionId!, x: bounds.left, y: bounds.bottom })
}
root.addEventListener("click", click)
root.addEventListener("contextmenu", contextMenu)
root.addEventListener("keydown", keyDown)
return () => {
root.removeEventListener("click", click)
root.removeEventListener("contextmenu", contextMenu)
root.removeEventListener("keydown", keyDown)
}
}
function sessionReferenceTarget(root: HTMLElement, target: EventTarget | null) {
if (!(target instanceof Element)) return
const reference = target.closest<HTMLElement>("[data-session-reference][data-session-id]")
return reference && root.contains(reference) ? reference : undefined
}
/** Undefined when the selection holds no session reference, so the caller keeps its usual copy. */
export function sessionReferenceClipboardText(root: HTMLElement, ranges: readonly Range[]) {
const references = Array.from(root.querySelectorAll("[data-session-reference]"))
if (!ranges.some((range) => references.some((reference) => range.intersectsNode(reference)))) return
const container = document.createElement("div")
container.style.cssText = "position:fixed;top:0;left:-100000px"
ranges.forEach((range) => container.append(sessionReferenceRange(range).cloneContents()))
container.querySelectorAll<HTMLElement>("[data-session-reference]").forEach((reference) => {
reference.replaceWith(reference.dataset.sessionReference ?? "")
})
// `innerText` needs layout to keep line breaks.
root.append(container)
const text = container.innerText
container.remove()
return text
}
/** References copy atomically even when the selection starts or ends inside their displayed title. */
export function sessionReferenceRange(range: Range) {
const start = range.startContainer instanceof Element ? range.startContainer : range.startContainer.parentElement
const end = range.endContainer instanceof Element ? range.endContainer : range.endContainer.parentElement
const first = start?.closest("[data-session-reference]")
const last = end?.closest("[data-session-reference]")
if (!first && !last) return range
const selection = range.cloneRange()
if (first) selection.setStartBefore(first)
if (last) selection.setEndAfter(last)
return selection
}
@@ -1,19 +1,18 @@
/* Matches the composer's session mention (packages/app/src/composer/editor/editor.css). */
.markdown-session-link {
display: inline;
padding: 1px 5px;
padding: 0;
border: 0;
border-radius: 4px;
background: var(--v2-background-bg-layer-02);
box-shadow: inset 0 0 0 1px var(--v2-border-border-base);
color: var(--v2-text-text-accent);
border-radius: 2px;
background: none;
color: var(--v2-text-text-muted);
font: inherit;
font-weight: var(--font-weight-medium);
text-align: start;
cursor: pointer;
box-decoration-break: clone;
-webkit-box-decoration-break: clone;
}
.markdown-session-link:hover {
color: var(--v2-text-text-accent-hover);
text-decoration: underline;
text-underline-offset: 2px;
}
@@ -70,7 +70,7 @@ import {
import { createMarkdownImages } from "./markdown-image"
import { createImagePreview } from "./image-preview"
import { setupFragmentLinks } from "./markdown-fragment-links"
import { markSessionLinks, setupSessionLinks } from "./markdown-session-links"
import { markSessionLinks, sessionReferenceClipboardText, setupSessionLinks } from "./markdown-session-links"
import { markdownClipboardHtml } from "./markdown-clipboard"
import { createCopyFeedback } from "./copy"
@@ -663,7 +663,10 @@ function copySelection(event: ClipboardEvent & { currentTarget: HTMLDivElement }
if (!ranges.every((range) => event.currentTarget.contains(range.commonAncestorContainer))) return
event.preventDefault()
event.clipboardData.setData("text/plain", selection.toString())
event.clipboardData.setData(
"text/plain",
sessionReferenceClipboardText(event.currentTarget, ranges) ?? selection.toString(),
)
event.clipboardData.setData(
"text/html",
`<meta charset="utf-8">${ranges.map((range) => markdownClipboardHtml(event.currentTarget, range)).join("")}`,
@@ -1100,7 +1103,12 @@ export function Markdown(
if (!linkCleanup) linkCleanup = setupLocalLinks(container, () => markdown?.openLocalFile)
if (!sessionLinkCleanup) sessionLinkCleanup = setupSessionLinks(container, () => markdown?.openSession)
if (!sessionLinkCleanup)
sessionLinkCleanup = setupSessionLinks(
container,
() => markdown?.openSession,
() => markdown?.sessionMenu,
)
if (!fragmentLinkCleanup) fragmentLinkCleanup = setupFragmentLinks(container)
@@ -1926,22 +1926,6 @@
[data-slot="user-message-text"] {
background: var(--v2-background-bg-layer-02);
color: var(--v2-text-text-base);
.markdown-session-link {
padding: 0;
text-align: start;
background: none;
box-shadow: none;
color: inherit;
text-decoration: underline;
text-decoration-color: color-mix(in oklch, currentColor 40%, transparent);
text-underline-offset: 2px;
&:hover {
color: inherit;
text-decoration-color: currentColor;
}
}
}
[data-slot="user-message-comments"] {
@@ -1,5 +1,6 @@
import type { IconName } from "@opencode/ui/icons/catalog"
import { createContext, useContext, type ParentProps } from "solid-js"
import type { SessionReferenceMenu } from "../components/markdown-session-links"
export type ReadMarkdownImage = (path: string, signal: AbortSignal) => Promise<Blob | undefined>
@@ -60,6 +61,7 @@ const context = createContext<{
readonly localFileExists?: MarkdownLocalFileExists
readonly openSession?: (sessionID: string) => void
readonly sessionTitle?: (sessionID: string) => string | undefined
readonly sessionMenu?: SessionReferenceMenu
readonly codeBlocks?: MarkdownCodeBlocks
}>()
@@ -70,6 +72,7 @@ export function MarkdownProvider(
localFileExists?: MarkdownLocalFileExists
openSession?: (id: string) => void
sessionTitle?: (id: string) => string | undefined
sessionMenu?: SessionReferenceMenu
/** Content for code blocks; inherited when omitted. `false` turns it off below, e.g. inside such content. */
codeBlocks?: MarkdownCodeBlocks | false
}>,
@@ -94,6 +97,9 @@ export function MarkdownProvider(
get sessionTitle() {
return props.sessionTitle ?? parent?.sessionTitle
},
get sessionMenu() {
return props.sessionMenu ?? parent?.sessionMenu
},
get codeBlocks() {
if (props.codeBlocks === false) return undefined
@@ -22,7 +22,11 @@ import { useI18n } from "@opencode/ui/context/i18n"
import { Markdown } from "../components/markdown"
import { linkSegments } from "../components/link-segments"
import { LinkedText } from "../components/linked-text"
import { sessionReferenceText, setupSessionLinks } from "../components/markdown-session-links"
import {
sessionReferenceClipboardText,
sessionReferenceText,
setupSessionLinks,
} from "../components/markdown-session-links"
import { useMarkdown } from "../context/markdown"
import { useSources } from "../context/sources"
import { SourcesChip } from "../sources/sources-chip"
@@ -680,7 +684,12 @@ export function CurrentUserMessageDisplay(props: {
</Tooltip>
</div>
</Show>
<div data-slot="user-message-text" dir="auto" data-comments={comments().length > 0 ? "true" : undefined}>
<div
data-slot="user-message-text"
dir="auto"
data-comments={comments().length > 0 ? "true" : undefined}
onCopy={copySessionReferences}
>
<Show
when={props.fold}
fallback={<CurrentHighlightedText text={props.text} files={inlineFiles()} agents={agents()} />}
@@ -886,11 +895,31 @@ function CurrentHighlightedText(props: { text: string; files: PromptAttachment[]
type HighlightSegment = { text: string; type?: "file" | "agent" | "link" }
function copySessionReferences(event: ClipboardEvent & { currentTarget: HTMLDivElement }) {
const selection = window.getSelection()
if (event.defaultPrevented || !event.clipboardData || !selection || selection.isCollapsed) return
const ranges = Array.from({ length: selection.rangeCount }, (_, index) => selection.getRangeAt(index))
if (!ranges.every((range) => event.currentTarget.contains(range.commonAncestorContainer))) return
const text = sessionReferenceClipboardText(event.currentTarget, ranges)
if (text === undefined) return
event.preventDefault()
event.clipboardData.setData("text/plain", text)
}
function SessionReferenceText(props: { text: string }) {
const markdown = useMarkdown()
const root = document.createElement("span")
createEffect(() => root.replaceChildren(sessionReferenceText(props.text, (id) => markdown?.sessionTitle?.(id))))
onCleanup(setupSessionLinks(root, () => markdown?.openSession))
onCleanup(
setupSessionLinks(
root,
() => markdown?.openSession,
() => markdown?.sessionMenu,
),
)
return root
}