Skip to content

The agent that grows with you

feat(desktop): render agent-written @session links as chips

Brooklyn Nicholson92439be3516b
diff --git a/apps/desktop/src/app/chat/composer/rich-editor.ts b/apps/desktop/src/app/chat/composer/rich-editor.ts
index e3ebe3dffdf..21f0286c9f8 100644
--- a/apps/desktop/src/app/chat/composer/rich-editor.ts
+++ b/apps/desktop/src/app/chat/composer/rich-editor.ts
@@ -15,7 +15,7 @@ import {
type SlashChipKind,
slashIconElement
} from '@/components/assistant-ui/directive-text'
-import { sessionRefFallbackLabel } from '@/lib/session-link-title'
+import { sessionRefFallbackLabel } from '@/lib/session-refs'
export const RICH_INPUT_SLOT = 'composer-rich-input'
diff --git a/apps/desktop/src/components/assistant-ui/directive-text.tsx b/apps/desktop/src/components/assistant-ui/directive-text.tsx
index e1a83f1c4c0..6788365da15 100644
--- a/apps/desktop/src/components/assistant-ui/directive-text.tsx
+++ b/apps/desktop/src/components/assistant-ui/directive-text.tsx
@@ -8,7 +8,8 @@ import { Fragment, useEffect, useMemo, useState } from 'react'
import { ZoomableImage } from '@/components/chat/zoomable-image'
import { extractEmbeddedImages } from '@/lib/embedded-images'
import { gatewayMediaDataUrl, isRemoteGateway } from '@/lib/media'
-import { sessionRefFallbackLabel, useSessionLinkTitle } from '@/lib/session-link-title'
+import { useSessionLinkTitle } from '@/lib/session-link-title'
+import { sessionRefFallbackLabel } from '@/lib/session-refs'
const HERMES_REF_TYPES = ['file', 'folder', 'url', 'image', 'tool', 'line', 'terminal', 'session'] as const
type HermesRefType = (typeof HERMES_REF_TYPES)[number]
@@ -362,7 +363,7 @@ export function DirectiveContent({ text }: { text: string }) {
segment.kind === 'text' ? (
<Fragment key={`t-${index}`}>{segment.text}</Fragment>
) : segment.type === 'image' ? null : segment.type === 'session' ? (
- <SessionDirectiveChip id={segment.id} key={`m-${index}-${segment.id}`} label={segment.label} />
+ <SessionRefChip key={`m-${index}-${segment.id}`} label={segment.label} value={segment.id} />
) : (
<DirectiveChip id={segment.id} key={`m-${index}-${segment.id}`} label={segment.label} type={segment.type} />
)
@@ -446,13 +447,16 @@ const DirectiveImage: FC<{ id: string; label: string }> = ({ id, label }) => {
)
}
-const SessionDirectiveChip: FC<{
- label: string
- id: string
-}> = ({ label, id }) => {
- const resolved = useSessionLinkTitle(id, label)
+/** A `@session:<profile>/<id>` reference, rendered as the session's title once
+ * resolved. Shared by the user transcript (directive segments) and assistant
+ * markdown (`#session/` links rewritten in `preprocessMarkdown`). */
+export const SessionRefChip: FC<{
+ label?: string
+ value: string
+}> = ({ label, value }) => {
+ const resolved = useSessionLinkTitle(value, label)
- return <DirectiveChip id={id} label={resolved} type="session" />
+ return <DirectiveChip id={value} label={resolved} type="session" />
}
const DirectiveChip: FC<{
diff --git a/apps/desktop/src/components/assistant-ui/markdown-text.session.test.tsx b/apps/desktop/src/components/assistant-ui/markdown-text.session.test.tsx
new file mode 100644
index 00000000000..e96ecc1acb6
--- /dev/null
+++ b/apps/desktop/src/components/assistant-ui/markdown-text.session.test.tsx
@@ -0,0 +1,66 @@
+import { cleanup, render, screen } from '@testing-library/react'
+import { afterEach, describe, expect, it } from 'vitest'
+
+import { __resetSessionLinkTitleCache } from '@/lib/session-link-title'
+import { $sessions } from '@/store/session'
+import type { SessionInfo } from '@/types/hermes'
+
+import { MarkdownTextContent } from './markdown-text'
+
+function makeSession(overrides: Partial<SessionInfo> = {}): SessionInfo {
+ return {
+ ended_at: null,
+ id: '20260101_abc123',
+ input_tokens: 0,
+ is_active: false,
+ last_active: 1_000,
+ message_count: 1,
+ model: null,
+ output_tokens: 0,
+ preview: null,
+ profile: 'work',
+ source: 'cli',
+ started_at: 1_000,
+ title: 'Branch plan',
+ tool_call_count: 0,
+ ...overrides
+ }
+}
+
+afterEach(() => {
+ cleanup()
+ $sessions.set([])
+ __resetSessionLinkTitleCache()
+})
+
+// End-to-end for the agent-authored path: a bare ref in assistant markdown has
+// to survive preprocessMarkdown -> Streamdown -> MarkdownLink and come out as
+// the session chip, not as literal text or a dead anchor.
+describe('MarkdownTextContent session refs', () => {
+ it('renders an agent-written @session ref as a chip showing the session title', async () => {
+ $sessions.set([makeSession()])
+
+ render(<MarkdownTextContent isRunning={false} text="Context lives in @session:work/20260101_abc123 today." />)
+
+ const chip = await screen.findByTitle('work/20260101_abc123')
+
+ expect(chip.dataset.directiveType).toBe('session')
+ expect(chip.textContent).toBe('Branch plan')
+ expect(screen.queryByText(/@session:/)).toBeNull()
+ })
+
+ it('falls back to a short id when the session is unknown', async () => {
+ render(<MarkdownTextContent isRunning={false} text="See @session:work/20260101_abc123 for context." />)
+
+ const chip = await screen.findByTitle('work/20260101_abc123')
+
+ expect(chip.textContent).toBe('20260101…')
+ })
+
+ it('leaves a ref inside inline code as literal text', () => {
+ render(<MarkdownTextContent isRunning={false} text="Write `@session:work/20260101_abc123` to link a chat." />)
+
+ expect(screen.getByText('@session:work/20260101_abc123')).toBeTruthy()
+ expect(screen.queryByTitle('work/20260101_abc123')).toBeNull()
+ })
+})
diff --git a/apps/desktop/src/components/assistant-ui/markdown-text.tsx b/apps/desktop/src/components/assistant-ui/markdown-text.tsx
index f5d78f53133..61983dd4c8f 100644
--- a/apps/desktop/src/components/assistant-ui/markdown-text.tsx
+++ b/apps/desktop/src/components/assistant-ui/markdown-text.tsx
@@ -30,8 +30,10 @@ import {
resolveMediaDisplaySrc
} from '@/lib/media'
import { previewTargetFromMarkdownHref } from '@/lib/preview-targets'
+import { sessionRefFromMarkdownHref } from '@/lib/session-refs'
import { cn } from '@/lib/utils'
+import { SessionRefChip } from './directive-text'
import { detectEmbed, extractAlert, MarkdownAlert, RichCodeBlock, UrlEmbed } from './embeds'
// Math rendering plugin (KaTeX). Configured once at module scope — the
@@ -233,6 +235,12 @@ function MarkdownLink({ children, className, href, ...props }: ComponentProps<'a
return <PreviewAttachment source="explicit-link" target={previewTarget} />
}
+ const sessionRef = sessionRefFromMarkdownHref(href)
+
+ if (sessionRef) {
+ return <SessionRefChip value={sessionRef} />
+ }
+
const target = href ? normalizeExternalUrl(href) : href
if (!target || !/^https?:\/\//i.test(target)) {
diff --git a/apps/desktop/src/lib/markdown-preprocess.ts b/apps/desktop/src/lib/markdown-preprocess.ts
index 25213e7ab30..c4a8731f478 100644
--- a/apps/desktop/src/lib/markdown-preprocess.ts
+++ b/apps/desktop/src/lib/markdown-preprocess.ts
@@ -2,6 +2,7 @@ import { normalizeMathDelimiters } from '@assistant-ui/react-streamdown'
import { isLikelyProseFence, sanitizeLanguageTag } from '@/lib/markdown-code'
import { stripPreviewTargets } from '@/lib/preview-targets'
+import { linkifySessionRefs } from '@/lib/session-refs'
const REASONING_BLOCK_RE = /<(think|thinking|reasoning|scratchpad|analysis)>[\s\S]*?<\/\1>\s*/gi
const PREVIEW_MARKER_RE = /\[Preview:[^\]]+\]\(#preview[:/][^)]+\)/gi
@@ -149,8 +150,10 @@ function normalizeVisibleProse(text: string): string {
.map(part =>
part.startsWith('`')
? part
- : autoLinkRawUrls(
- part.replace(/`{3,}/g, '').replace(LOCAL_PREVIEW_URL_RE, '$1').replace(CITATION_MARKER_RE, '')
+ : linkifySessionRefs(
+ autoLinkRawUrls(
+ part.replace(/`{3,}/g, '').replace(LOCAL_PREVIEW_URL_RE, '$1').replace(CITATION_MARKER_RE, '')
+ )
)
)
.join('')
diff --git a/apps/desktop/src/lib/session-link-title.test.ts b/apps/desktop/src/lib/session-link-title.test.ts
index b6fe39cf8f9..f04daeca330 100644
--- a/apps/desktop/src/lib/session-link-title.test.ts
+++ b/apps/desktop/src/lib/session-link-title.test.ts
@@ -7,11 +7,9 @@ import type { SessionInfo } from '@/types/hermes'
import {
__resetSessionLinkTitleCache,
fetchSessionLinkTitle,
- lookupLocalSessionTitle,
- parseSessionRefValue,
- sessionRefCacheKey,
- sessionRefFallbackLabel
+ lookupLocalSessionTitle
} from './session-link-title'
+import { sessionRefCacheKey } from './session-refs'
vi.mock('@/hermes', () => ({
getSession: vi.fn()
@@ -43,29 +41,6 @@ afterEach(() => {
vi.mocked(getSession).mockReset()
})
-describe('parseSessionRefValue', () => {
- it('splits profile and session id', () => {
- expect(parseSessionRefValue('work/20260101_abc123')).toEqual({
- profile: 'work',
- sessionId: '20260101_abc123'
- })
- })
-
- it('treats bare values as session ids', () => {
- expect(parseSessionRefValue('20260101_abc123')).toEqual({ sessionId: '20260101_abc123' })
- })
-})
-
-describe('sessionRefFallbackLabel', () => {
- it('truncates long ids', () => {
- expect(sessionRefFallbackLabel('default/20260610_120000_abcdef')).toBe('20260610…')
- })
-
- it('leaves short ids alone', () => {
- expect(sessionRefFallbackLabel('work/abc123')).toBe('abc123')
- })
-})
-
describe('lookupLocalSessionTitle', () => {
it('reads from the in-memory session list', () => {
$sessions.set([makeSession({ profile: 'work', title: 'Branch plan' })])
diff --git a/apps/desktop/src/lib/session-link-title.ts b/apps/desktop/src/lib/session-link-title.ts
index fc86a112f2e..27aff91002f 100644
--- a/apps/desktop/src/lib/session-link-title.ts
+++ b/apps/desktop/src/lib/session-link-title.ts
@@ -9,6 +9,7 @@
import { useEffect, useMemo, useState } from 'react'
import { getSession } from '@/hermes'
+import { parseSessionRefValue, sessionRefCacheKey, sessionRefFallbackLabel } from '@/lib/session-refs'
import { $sessions, sessionMatchesStoredId } from '@/store/session'
import type { SessionInfo } from '@/types/hermes'
@@ -16,39 +17,6 @@ const titleCache = new Map<string, string>()
const titleInflight = new Map<string, Promise<string>>()
const titleSubs = new Map<string, Set<(value: string) => void>>()
-/** Session ids never contain a slash, so a slash unambiguously means
- * `<profile>/<id>` — mirrors the same split in `tools/session_search_tool.py`. */
-export function parseSessionRefValue(value: string): { profile?: string; sessionId: string } {
- const trimmed = value.trim()
- const slash = trimmed.indexOf('/')
-
- if (slash === -1) {
- return { sessionId: trimmed }
- }
-
- const profile = trimmed.slice(0, slash).trim()
- const sessionId = trimmed.slice(slash + 1).trim()
-
- return sessionId ? { profile: profile || undefined, sessionId } : { sessionId: trimmed }
-}
-
-export function sessionRefCacheKey(value: string): string {
- const { profile, sessionId } = parseSessionRefValue(value)
-
- return sessionId ? `${profile ?? ''}/${sessionId}` : ''
-}
-
-/** Chip label before (or without) a resolved title — a short, still-identifying id. */
-export function sessionRefFallbackLabel(value: string): string {
- const { sessionId } = parseSessionRefValue(value)
-
- if (!sessionId) {
- return value
- }
-
- return sessionId.length > 10 ? `${sessionId.slice(0, 8)}…` : sessionId
-}
-
/** Deliberately not `sessionTitle()` from chat-runtime: its "Untitled session"
* fallback is a worse chip label than the short id, so an untitled row
* resolves to empty and the caller's fallback wins. */
diff --git a/apps/desktop/src/lib/session-refs.test.ts b/apps/desktop/src/lib/session-refs.test.ts
new file mode 100644
index 00000000000..0028150ef3a
--- /dev/null
+++ b/apps/desktop/src/lib/session-refs.test.ts
@@ -0,0 +1,118 @@
+import { describe, expect, it } from 'vitest'
+
+import { preprocessMarkdown } from './markdown-preprocess'
+import {
+ linkifySessionRefs,
+ parseSessionRefValue,
+ sessionMarkdownHref,
+ sessionRefCacheKey,
+ sessionRefFallbackLabel,
+ sessionRefFromMarkdownHref,
+ splitSessionRefValue
+} from './session-refs'
+
+describe('parseSessionRefValue', () => {
+ it('splits profile and session id', () => {
+ expect(parseSessionRefValue('work/20260101_abc123')).toEqual({
+ profile: 'work',
+ sessionId: '20260101_abc123'
+ })
+ })
+
+ it('treats bare values as session ids', () => {
+ expect(parseSessionRefValue('20260101_abc123')).toEqual({ sessionId: '20260101_abc123' })
+ })
+})
+
+describe('sessionRefFallbackLabel', () => {
+ it('truncates long ids', () => {
+ expect(sessionRefFallbackLabel('default/20260610_120000_abcdef')).toBe('20260610…')
+ })
+
+ it('leaves short ids alone', () => {
+ expect(sessionRefFallbackLabel('work/abc123')).toBe('abc123')
+ })
+})
+
+describe('sessionRefCacheKey', () => {
+ it('separates the same id across profiles', () => {
+ expect(sessionRefCacheKey('work/abc')).not.toBe(sessionRefCacheKey('home/abc'))
+ })
+
+ it('is empty for a valueless ref', () => {
+ expect(sessionRefCacheKey(' ')).toBe('')
+ })
+})
+
+describe('splitSessionRefValue', () => {
+ it('peels prose punctuation off a bare value', () => {
+ expect(splitSessionRefValue('default/abc123.')).toEqual({ trailing: '.', value: 'default/abc123' })
+ })
+
+ it('leaves a quoted value fenced', () => {
+ expect(splitSessionRefValue('`my session`')).toEqual({ trailing: '', value: 'my session' })
+ })
+})
+
+describe('session markdown hrefs', () => {
+ it('round-trips a value through the fragment href', () => {
+ const href = sessionMarkdownHref('work/20260101_abc123')
+
+ expect(href).toBe('#session/work%2F20260101_abc123')
+ expect(sessionRefFromMarkdownHref(href)).toBe('work/20260101_abc123')
+ })
+
+ it('ignores hrefs that are not session fragments', () => {
+ expect(sessionRefFromMarkdownHref('#preview/foo')).toBeNull()
+ expect(sessionRefFromMarkdownHref('https://example.com')).toBeNull()
+ expect(sessionRefFromMarkdownHref(undefined)).toBeNull()
+ })
+})
+
+describe('linkifySessionRefs', () => {
+ it('rewrites a bare ref into a session link', () => {
+ expect(linkifySessionRefs('see @session:work/20260101_abc123 next')).toBe(
+ 'see [20260101…](#session/work%2F20260101_abc123) next'
+ )
+ })
+
+ it('keeps trailing prose punctuation outside the link', () => {
+ expect(linkifySessionRefs('see @session:default/abc123.')).toBe('see [abc123](#session/default%2Fabc123).')
+ })
+
+ it('leaves text without a ref untouched', () => {
+ const text = 'no references here'
+
+ expect(linkifySessionRefs(text)).toBe(text)
+ })
+
+ it('does not match an email-like or path-embedded @session', () => {
+ expect(linkifySessionRefs('me@session:abc')).toBe('me@session:abc')
+ expect(linkifySessionRefs('a/@session:abc')).toBe('a/@session:abc')
+ })
+})
+
+// The agent-authored path: assistant markdown runs through preprocessMarkdown
+// before Streamdown, so a bare ref must survive as a link — and must NOT be
+// rewritten inside code, where it is being discussed rather than referenced.
+describe('preprocessMarkdown session refs', () => {
+ it('linkifies a ref in prose', () => {
+ expect(preprocessMarkdown('Context is in @session:work/20260101_abc123 there.')).toContain(
+ '[20260101…](#session/work%2F20260101_abc123)'
+ )
+ })
+
+ it('leaves refs inside inline code alone', () => {
+ const out = preprocessMarkdown('Type `@session:work/20260101_abc123` to link a chat.')
+
+ expect(out).toContain('`@session:work/20260101_abc123`')
+ expect(out).not.toContain('#session/')
+ })
+
+ it('leaves refs inside a fenced block alone', () => {
+ const out = preprocessMarkdown(['```text', '@session:work/20260101_abc123', '```'].join('\n'))
+
+ expect(out).toContain('@session:work/20260101_abc123')
+ expect(out).not.toContain('#session/')
+ })
+})
diff --git a/apps/desktop/src/lib/session-refs.ts b/apps/desktop/src/lib/session-refs.ts
new file mode 100644
index 00000000000..e672c1b6f05
--- /dev/null
+++ b/apps/desktop/src/lib/session-refs.ts
@@ -0,0 +1,117 @@
+/**
+ * Pure helpers for `@session:<profile>/<id>` references.
+ *
+ * Kept free of React/store/API imports so the markdown preprocessor (a hot
+ * per-flush path) can use them without pulling in the resolver; the stateful
+ * title lookup lives in `session-link-title.ts`.
+ */
+
+/** Mirrors the composer/transcript form in `directive-text.tsx`: a bare value,
+ * or one fenced in backticks/quotes so a value with spaces survives. The
+ * lookbehind keeps `foo@session:` and URL paths from matching. */
+export const SESSION_REF_RE = /(?<![\w/])@session:(`[^`\n]+`|"[^"\n]+"|'[^'\n]+'|\S+)/g
+
+const TRAILING_PUNCTUATION_RE = /[,.;:!?)\]}]+$/
+
+function unwrapQuotes(raw: string): null | string {
+ if (raw.length < 2) {
+ return null
+ }
+
+ const head = raw[0]
+ const tail = raw[raw.length - 1]
+
+ if ((head === '`' && tail === '`') || (head === '"' && tail === '"') || (head === "'" && tail === "'")) {
+ return raw.slice(1, -1)
+ }
+
+ return null
+}
+
+/** Splits a matched value into the reference itself and any prose punctuation
+ * that the greedy `\S+` branch swallowed. Quoted values are already fenced. */
+export function splitSessionRefValue(raw: string): { trailing: string; value: string } {
+ const quoted = unwrapQuotes(raw)
+
+ if (quoted !== null) {
+ return { trailing: '', value: quoted }
+ }
+
+ const value = raw.replace(TRAILING_PUNCTUATION_RE, '')
+
+ return { trailing: raw.slice(value.length), value }
+}
+
+/** Session ids never contain a slash, so a slash unambiguously means
+ * `<profile>/<id>` — same split as `tools/session_search_tool.py`. */
+export function parseSessionRefValue(value: string): { profile?: string; sessionId: string } {
+ const trimmed = value.trim()
+ const slash = trimmed.indexOf('/')
+
+ if (slash === -1) {
+ return { sessionId: trimmed }
+ }
+
+ const profile = trimmed.slice(0, slash).trim()
+ const sessionId = trimmed.slice(slash + 1).trim()
+
+ return sessionId ? { profile: profile || undefined, sessionId } : { sessionId: trimmed }
+}
+
+export function sessionRefCacheKey(value: string): string {
+ const { profile, sessionId } = parseSessionRefValue(value)
+
+ return sessionId ? `${profile ?? ''}/${sessionId}` : ''
+}
+
+/** Chip label before (or without) a resolved title — a short, still-identifying id. */
+export function sessionRefFallbackLabel(value: string): string {
+ const { sessionId } = parseSessionRefValue(value)
+
+ if (!sessionId) {
+ return value
+ }
+
+ return sessionId.length > 10 ? `${sessionId.slice(0, 8)}…` : sessionId
+}
+
+/** A fragment href, matching the `#preview/` convention in `preview-targets.ts`
+ * — no custom URL scheme to survive markdown sanitization. */
+export function sessionMarkdownHref(value: string): string {
+ return `#session/${encodeURIComponent(value)}`
+}
+
+export function sessionRefFromMarkdownHref(href?: string): null | string {
+ if (!href?.startsWith('#session/')) {
+ return null
+ }
+
+ try {
+ return decodeURIComponent(href.slice('#session/'.length)) || null
+ } catch {
+ return null
+ }
+}
+
+/**
+ * Rewrites bare `@session:<profile>/<id>` tokens into markdown links so an
+ * agent-authored reference reaches `MarkdownLink` and renders as a chip.
+ * Callers must exclude code spans/fences — `preprocessMarkdown` already does.
+ */
+export function linkifySessionRefs(text: string): string {
+ if (!text.includes('@session:')) {
+ return text
+ }
+
+ return text.replace(SESSION_REF_RE, (match, raw: string) => {
+ const { trailing, value } = splitSessionRefValue(raw)
+
+ if (!parseSessionRefValue(value).sessionId) {
+ return match
+ }
+
+ const label = sessionRefFallbackLabel(value).replace(/[[\]\\]/g, '\\$&')
+
+ return `[${label}](${sessionMarkdownHref(value)})${trailing}`
+ })
+}