Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
feat(session-links): render conversation references as chips everywhere
vastsa52a1cc988773
diff --git a/apps/desktop/src/components/Markdown.tsx b/apps/desktop/src/components/Markdown.tsxindex 1f83e87e4..7d913439e 100644--- a/apps/desktop/src/components/Markdown.tsx+++ b/apps/desktop/src/components/Markdown.tsx@@ -532,11 +532,17 @@ function InlineCode({type="button"className="chat-code-link"title={target.kind === "file" ? fileTitle : urlTitle}- onClick={() =>- target.kind === "file"- ? openFileRef(text ?? target.path, baseDir)- : openHttpUrl(target.url)- }+ onClick={() => {+ if (target.kind === "file") {+ openFileRef(text ?? target.path, baseDir);+ return;+ }+ if (target.kind === "session") {+ void useAppStore.getState().selectSession(target.sessionId).catch(() => undefined);+ return;+ }+ openHttpUrl(target.url);+ }}onContextMenu={target.kind === "file" && openFileMenu? (event) =>diff --git a/apps/desktop/src/features/chat/composer/editor.ts b/apps/desktop/src/features/chat/composer/editor.tsindex 1f6f9fec7..584747a20 100644--- a/apps/desktop/src/features/chat/composer/editor.ts+++ b/apps/desktop/src/features/chat/composer/editor.ts@@ -39,7 +39,7 @@ export function createFileReference(preferredName?: string,sessionId = "",metadata?: {- kind?: "image" | "file";+ kind?: "image" | "file" | "session";mimeType?: string;token?: string;plugin?: ComposerPluginPart;@@ -51,7 +51,12 @@ export function createFileReference(sessionId,path,// A plugin mark's label is shown as given; it is no path.- name: isPluginMark(metadata) ? (preferredName ?? "") : fileReferenceLabel(path, preferredName),+ // A plugin mark's label is shown as given, and a session reference is+ // named by its conversation; neither is a path.+ name:+ isPluginMark(metadata) || metadata?.kind === "session"+ ? (preferredName ?? "")+ : fileReferenceLabel(path, preferredName),kind: metadata?.kind ?? (isImageFilePath(path) ? "image" : "file"),...(metadata?.mimeType ? { mimeType: metadata.mimeType } : {}),...(metadata?.token ? { token: metadata.token } : {}),@@ -244,6 +249,7 @@ const CHIP_ICON_SVG: Record<string, string> = {video:'<path d="m16 13 5.223 3.482a.5.5 0 0 0 .777-.416V7.87a.5.5 0 0 0-.752-.432L16 10.5"/><rect x="2" y="6" width="14" height="12" rx="2"/>',file: '<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/>',+ session: '<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>',x: '<path d="M18 6 6 18"/><path d="m6 6 12 12"/>',plugin:'<path d="M15.39 4.39a1 1 0 0 0 1.68-.474 2.5 2.5 0 1 1 3.014 3.015 1 1 0 0 0-.474 1.68l1.683 1.682a2.414 2.414 0 0 1 0 3.414L19.61 15.39a1 1 0 0 1-1.68-.474 2.5 2.5 0 1 0-3.014 3.015 1 1 0 0 1 .474 1.68l-1.683 1.682a2.414 2.414 0 0 1-3.414 0L8.61 19.61a1 1 0 0 0-1.68.474 2.5 2.5 0 1 1-3.014-3.015 1 1 0 0 0 .474-1.68l-1.683-1.682a2.414 2.414 0 0 1 0-3.414L4.39 8.61a1 1 0 0 1 1.68.474 2.5 2.5 0 1 0 3.014-3.015 1 1 0 0 1-.474-1.68l1.683-1.682a2.414 2.414 0 0 1 3.414 0z"/>',@@ -253,6 +259,7 @@ const CHIP_ICON_SVG: Record<string, string> = {function chipIconKey(reference: ComposerFileReference): string {if (reference.plugin?.kind === "mark") return "plugin";if (reference.plugin?.kind === "fold") return "fold";+ if (reference.kind === "session") return "session";const mime = reference.mimeType ?? "";if (reference.kind === "image" || mime.startsWith("image/")) return "image";const name = reference.name;@@ -283,6 +290,7 @@ function buildChipElement(onRemove: (token: string) => void,onExpandText: (token: string) => void,onOpenImage: (token: string) => void,+ onOpenSession: (token: string) => void,): HTMLElement {const chip = document.createElement("span");chip.className = "composer-chip";@@ -292,19 +300,31 @@ function buildChipElement(const origin = isPluginMark(reference) ? (reference.plugin?.pluginId ?? "") : reference.path;if (isPluginMark(reference)) chip.dataset.pluginMark = reference.plugin?.kind;chip.title = origin;- // An image keeps the compact chip and opens its preview; only plain text- // references expand into editable draft text.+ // An image keeps the compact chip and opens its preview, a session chip opens+ // that conversation, and only plain text expands into editable draft text.const image = chipIconKey(reference) === "image";if (image) chip.dataset.image = "";- const editableText = !image && isEditableTextReference(reference);- const activate = editableText ? () => onExpandText(token) : image ? () => onOpenImage(token) : undefined;+ const session = reference.kind === "session";+ if (session) chip.dataset.sessionId = reference.path;+ const editableText = !image && !session && isEditableTextReference(reference);+ const activate = editableText+ ? () => onExpandText(token)+ : image+ ? () => onOpenImage(token)+ : session+ ? () => onOpenSession(token)+ : undefined;chip.setAttribute("role", activate ? "button" : "listitem");chip.setAttribute("aria-label", `${reference.name} — ${origin}`);if (activate) {chip.tabIndex = 0;// Only a text reference expands into editable text; an image chip opens- // its preview instead.- chip.dataset.action = editableText ? "expand-text-reference" : "open-image-preview";+ // its preview and a session chip opens that conversation instead.+ chip.dataset.action = editableText+ ? "expand-text-reference"+ : image+ ? "open-image-preview"+ : "open-session-reference";chip.addEventListener("click", activate);chip.addEventListener("keydown", (event) => {if (event.target !== chip) return;@@ -353,6 +373,7 @@ export function paintEditorValue(onRemove: (token: string) => void,onExpandText: (token: string) => void,onOpenImage: (token: string) => void,+ onOpenSession: (token: string) => void,): void {el.replaceChildren();let textBuffer = "";@@ -375,6 +396,7 @@ export function paintEditorValue(onRemove,onExpandText,onOpenImage,+ onOpenSession,),);continue;diff --git a/apps/desktop/src/features/chat/composer/hooks/useComposerAttachments.ts b/apps/desktop/src/features/chat/composer/hooks/useComposerAttachments.tsindex 792b22876..7e3229230 100644--- a/apps/desktop/src/features/chat/composer/hooks/useComposerAttachments.ts+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerAttachments.ts@@ -5,6 +5,7 @@ import {type DragEvent as ReactDragEvent,} from "react";import type { TFunction } from "i18next";+import { parseSessionLinks, sessionLinkSpans } from "@pi-desktop/shared";import { materializeDraftSession, useAppStore } from "../../../../stores/app-store";import { api } from "../../../../lib/api";import {@@ -158,6 +159,56 @@ export function useComposerAttachments({}};+ /** The chip label for one referenced conversation. */+ const sessionChipName = (id: string) => {+ const title = (+ useAppStore.getState().sessions.find((session) => session.id === id)?.title ?? ""+ ).trim();+ return `${t("chat.sessionReference")} · ${title || id.slice(0, 8)}`;+ };++ /**+ * A pasted `pi-desktop://session/<id>` link becomes the same inline chip as+ * any other attachment; the prompt still carries the link text.+ */+ const pasteSessionLinks = (text: string) => {+ const editor = draft.ref.current;+ const sourceValue = editor ? readEditorValue(editor) : draft.valueRef.current;+ const { start: selectionStart, end: selectionEnd } = editor+ ? editorSelectionRange(editor)+ : { start: sourceValue.length, end: sourceValue.length };+ const ownerSessionId = activeSessionId ?? "";+ const previousReferences = snapshotReferences(ownerSessionId);+ const sessionReferences: ComposerFileReference[] = [];+ let pasted = text;+ for (const span of [...sessionLinkSpans(text)].reverse()) {+ const token = nextChipToken();+ pasted = pasted.slice(0, span.start) + token + pasted.slice(span.end);+ sessionReferences.unshift(+ createFileReference(span.id, sessionChipName(span.id), ownerSessionId, {+ kind: "session",+ token,+ }),+ );+ }+ if (!sessionReferences.length) return;+ const nextText = sourceValue.slice(0, selectionStart) + pasted + sourceValue.slice(selectionEnd);+ const nextReferences = [+ ...previousReferences.map((reference) =>+ createFileReference(reference.path, reference.name, ownerSessionId, reference),+ ),+ ...sessionReferences,+ ];+ writeComposerDraft(ownerSessionId || draftKey, {+ text: nextText,+ fileReferences: [+ ...previousReferences,+ ...sessionReferences.map((reference) => draftFileReference(reference)),+ ],+ });+ draft.applyEditorDraft(nextText, nextReferences, selectionStart + pasted.length);+ };+const pasteClipboardFiles = async (event: ClipboardEvent<HTMLDivElement>) => {if (isInputBlocked) return;const text = event.clipboardData.getData("text/plain");@@ -255,6 +306,14 @@ export function useComposerAttachments({return;}+ const sessionIds = parseSessionLinks(text);+ if (sessionIds.length) {+ event.preventDefault();+ void api.recordClipboardPaste(text).catch(() => undefined);+ pasteSessionLinks(text);+ return;+ }+// Small text paste is kept plain so rich HTML never enters the draft.event.preventDefault();if (!text) return;diff --git a/apps/desktop/src/features/chat/composer/hooks/useComposerDraft.ts b/apps/desktop/src/features/chat/composer/hooks/useComposerDraft.tsindex 026578491..ea12f9ce0 100644--- a/apps/desktop/src/features/chat/composer/hooks/useComposerDraft.ts+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerDraft.ts@@ -248,6 +248,12 @@ export function useComposerDraft({const reference = referenceByTokenRef.current.get(token);if (reference) imagePreview.open(reference);};+ const openSessionReferenceRef = useRef<(token: string) => void>(() => {});+ openSessionReferenceRef.current = (token) => {+ const reference = referenceByTokenRef.current.get(token);+ if (!reference || reference.kind !== "session") return;+ void useAppStore.getState().selectSession(reference.path).catch(() => undefined);+ };const pendingEditorCaretRef = useRef<number | null>(initialDraft?.text ? initialDraft.text.length : null,);@@ -278,6 +284,7 @@ export function useComposerDraft({(token) => removeChipByTokenRef.current(token),(token) => expandTextReferenceRef.current(token),(token) => openImageReferenceRef.current(token),+ (token) => openSessionReferenceRef.current(token),);editorValueRef.current = nextValue;};@@ -466,9 +473,12 @@ export function useComposerDraft({if (previousWorkspacePathRef.current === workspacePath) return;previousWorkspacePathRef.current = workspacePath;const current = fileReferencesRef.current;- // Plugin marks carry their text, not a workspace path.+ // Plugin marks carry their text, not a workspace path, and a session+ // reference names a conversation rather than a file in this project.const survives = (fileReference: ComposerFileReference) =>- Boolean(fileReference.plugin) || isPersistedScratchReference(fileReference.path);+ Boolean(fileReference.plugin) ||+ fileReference.kind === "session" ||+ isPersistedScratchReference(fileReference.path);const kept = current.filter(survives);if (kept.length === current.length) return;markComposerDraftEdited(draftKeyRef.current);diff --git a/apps/desktop/src/features/chat/composer/model.ts b/apps/desktop/src/features/chat/composer/model.tsindex d5891a884..a8331002f 100644--- a/apps/desktop/src/features/chat/composer/model.ts+++ b/apps/desktop/src/features/chat/composer/model.ts@@ -61,7 +61,7 @@ export type ComposerFileReference = {sessionId: string;path: string;name: string;- kind: "image" | "file";+ kind: "image" | "file" | "session";mimeType?: string;token?: string;plugin?: ComposerPluginPart;diff --git a/apps/desktop/src/features/chat/transcript/shared.tsx b/apps/desktop/src/features/chat/transcript/shared.tsxindex d1f879925..4861b3ccb 100644--- a/apps/desktop/src/features/chat/transcript/shared.tsx+++ b/apps/desktop/src/features/chat/transcript/shared.tsx@@ -467,11 +467,14 @@ export function FileRefChip({}/**- * A referenced conversation on a user message (issue #1324). The draft carried- * a `pi-desktop://session/<id>` link; main attached a bounded excerpt for the- * model and this chip is how the reader sees and reopens it.+ * A referenced conversation as a chip. The draft carried a+ * `pi-desktop://session/<id>` link; main attached a bounded excerpt for the+ * model, and this chip is how the reader sees and reopens it.*/-export function SessionRefChip({ attachment }: { attachment: MessageAttachment }) {+function SessionChip({ sessionId, fallbackName, ...position }: {+ sessionId: string;+ fallbackName: string;+} & SourcePositionProps) {const { t } = useTranslation();const selectSession = useAppStore((state) => state.selectSession);// The chip names a conversation, not the name that conversation carried when@@ -480,19 +483,20 @@ export function SessionRefChip({ attachment }: { attachment: MessageAttachment }// model block quotes, and it stays the fallback for a conversation this// viewer no longer lists.const liveTitle = useAppStore(- (state) => state.sessions.find((session) => session.id === attachment.ref)?.title,+ (state) => state.sessions.find((session) => session.id === sessionId)?.title,);- const name = (liveTitle ?? "").trim() || attachment.name;+ const name = (liveTitle ?? "").trim() || fallbackName;const label = `${t("chat.sessionReference")} · ${name}`;return (<buttontype="button"className="composer-chip chat-file-chip"+ {...position}data-action="open-session-reference"- data-session-id={attachment.ref}+ data-session-id={sessionId}title={t("chat.sessionReferenceOpen", { title: name })}aria-label={label}- onClick={() => void selectSession(attachment.ref).catch(() => undefined)}+ onClick={() => void selectSession(sessionId).catch(() => undefined)}><span className="composer-chip-icon" aria-hidden><IconChat size={13} />@@ -502,6 +506,18 @@ export function SessionRefChip({ attachment }: { attachment: MessageAttachment });}+/** A structured session attachment on a user message (issue #1324). */+export function SessionRefChip({ attachment }: { attachment: MessageAttachment }) {+ return <SessionChip sessionId={attachment.ref} fallbackName={attachment.name} />;+}++/** A bare `pi-desktop://session/<id>` link in prose, rendered as that chip. */+export function SessionLinkChip({ sessionId, ...position }: { sessionId: string } & SourcePositionProps) {+ return (+ <SessionChip sessionId={sessionId} fallbackName={sessionId.slice(0, 8)} {...position} />+ );+}+/*** User-message image attachment as the same compact chip as any other file* reference. The host resolves the ref into a bounded data URL that the hover@@ -574,6 +590,8 @@ export function LinkifiedText({ text, attachments }: { text: string; attachmentsonOpen={openFileRef}{...position}/>+ ) : segment.target.kind === "session" ? (+ <SessionLinkChip key={index} sessionId={segment.target.sessionId} {...position} />) : (<TooltipButtonkey={index}diff --git a/apps/desktop/src/hooks/use-preview-target.ts b/apps/desktop/src/hooks/use-preview-target.tsindex 633a2e62f..639c93d98 100644--- a/apps/desktop/src/hooks/use-preview-target.ts+++ b/apps/desktop/src/hooks/use-preview-target.ts@@ -26,13 +26,19 @@ import {export function useOpenPreviewTarget() {const openFileRef = useOpenChatFileRef();return useCallback(- (target: ChatPreviewTarget) =>- target.kind === "file"- ? openFileRef(target.path, undefined, undefined, {- line: target.line,- column: target.column,- })- : openHttpUrl(target.url),+ (target: ChatPreviewTarget) => {+ if (target.kind === "file") {+ return openFileRef(target.path, undefined, undefined, {+ line: target.line,+ column: target.column,+ });+ }+ if (target.kind === "session") {+ void useAppStore.getState().selectSession(target.sessionId).catch(() => undefined);+ return;+ }+ openHttpUrl(target.url);+ },[openFileRef],);}diff --git a/apps/desktop/src/lib/chat-links.ts b/apps/desktop/src/lib/chat-links.tsindex 02a39b9df..8922fe8ce 100644--- a/apps/desktop/src/lib/chat-links.ts+++ b/apps/desktop/src/lib/chat-links.ts@@ -17,6 +17,8 @@* still cannot escape the workspace (D322).*/+import { formatSessionLink, parseSessionLinkToken } from "@pi-desktop/shared";+const KNOWN_EXTS = new Set(["ts", "tsx", "js", "jsx", "mjs", "cjs", "json", "css", "scss", "less","html", "htm", "md", "mdx", "txt", "rs", "py", "go", "rb", "sh", "zsh",@@ -204,7 +206,8 @@ export function toWorkspaceRel(export type ChatPreviewTarget =| { kind: "file"; path: string; line?: number; column?: number }- | { kind: "url"; url: string };+ | { kind: "url"; url: string }+ | { kind: "session"; sessionId: string };/** Resolve one raw chat token into a previewable target, or null. */export function resolvePreviewTarget(@@ -213,6 +216,8 @@ export function resolvePreviewTarget(baseDir?: string | null,): ChatPreviewTarget | null {const trimmed = text.trim();+ const sessionId = parseSessionLinkToken(trimmed);+ if (sessionId) return { kind: "session", sessionId };if (isHttpUrl(trimmed)) return { kind: "url", url: trimmed };const position = parseFileRefPosition(trimmed);const pathText = position@@ -294,6 +299,7 @@ const SCAN_RE = new RegExp([String.raw`@"[^"\n]+"`,String.raw`@[^\s]+`,String.raw`https?:\/\/(?=[^\s<>"'()[\]{}])`,+ String.raw`pi-desktop:\/\/session\/[A-Za-z0-9_-]{1,64}`,String.raw`(?:[A-Za-z]:[\\/]|${UNC_PREFIX}|\/)(?:${PATH_SEGMENT}[\\/])*?${FILE_NAME}`,String.raw`${SPACED_START}[\\/](?:${PATH_SEGMENT}[\\/])*?${FILE_NAME}`,String.raw`${SPACED_START}(?:\.[A-Za-z0-9_-]+)*${FILE_END}`,@@ -421,9 +427,11 @@ export function linkifyMdastTree(const url =target.kind === "url"? target.url- : /^[A-Za-z]:[\\/]/.test(target.path) || target.path.startsWith("\\\\")- ? encodeURIComponent(target.path)- : target.path;+ : target.kind === "session"+ ? formatSessionLink(target.sessionId)+ : /^[A-Za-z]:[\\/]/.test(target.path) || target.path.startsWith("\\\\")+ ? encodeURIComponent(target.path)+ : target.path;next.push({type: "link",url,@@ -446,9 +454,11 @@ export function linkifyMdastTree(const url =segment.target.kind === "url"? segment.target.url- : (/^[A-Za-z]:[\\/]/.test(segment.target.path) || segment.target.path.startsWith("\\\\"))- ? encodeURIComponent(segment.target.path)- : segment.target.path;+ : segment.target.kind === "session"+ ? formatSessionLink(segment.target.sessionId)+ : (/^[A-Za-z]:[\\/]/.test(segment.target.path) || segment.target.path.startsWith("\\\\"))+ ? encodeURIComponent(segment.target.path)+ : segment.target.path;next.push({type: "link",url,diff --git a/apps/desktop/src/lib/composer-draft-cache.ts b/apps/desktop/src/lib/composer-draft-cache.tsindex f496c17be..69a0d09f9 100644--- a/apps/desktop/src/lib/composer-draft-cache.ts+++ b/apps/desktop/src/lib/composer-draft-cache.ts@@ -24,7 +24,7 @@ export type ComposerDraftFileInput = {sessionId?: string;path: string;name: string;- kind?: "image" | "file";+ kind?: "image" | "file" | "session";mimeType?: string;token?: string;plugin?: ComposerPluginPart;diff --git a/apps/desktop/src/lib/composer-smart-stop.ts b/apps/desktop/src/lib/composer-smart-stop.tsindex 01d525b73..f984205d4 100644--- a/apps/desktop/src/lib/composer-smart-stop.ts+++ b/apps/desktop/src/lib/composer-smart-stop.ts@@ -25,7 +25,7 @@ export type ComposerPluginPart =export type ComposerDraftFileReference = {path: string;name: string;- kind?: "image" | "file";+ kind?: "image" | "file" | "session";mimeType?: string;/** Visible inline token for a generated large-text paste reference. */token?: string;diff --git a/apps/desktop/src/lib/session-transcript.ts b/apps/desktop/src/lib/session-transcript.tsindex 426a86674..682c4f160 100644--- a/apps/desktop/src/lib/session-transcript.ts+++ b/apps/desktop/src/lib/session-transcript.ts@@ -9,7 +9,7 @@ import {type OptimisticFileReference = {path: string;name: string;- kind?: "image" | "file";+ kind?: "image" | "file" | "session";mimeType?: string;/** Large-text paste tokens travel inline in the text, not as attachments. */token?: string;diff --git a/apps/desktop/src/stores/helpers/store-helpers.ts b/apps/desktop/src/stores/helpers/store-helpers.tsindex c8585cbf8..957139296 100644--- a/apps/desktop/src/stores/helpers/store-helpers.ts+++ b/apps/desktop/src/stores/helpers/store-helpers.ts@@ -25,6 +25,9 @@ export function promptAttachmentsFromDraft(references: ComposerDraftSnapshot["fileReferences"],): AgentPromptAttachment[] {return references.flatMap((reference) => {+ // A session link is prompt text: main resolves it into a conversation+ // reference, and it never travels as a structured attachment.+ if (reference.kind === "session") return [];const kind =reference.kind ??(/\.(avif|bmp|gif|heic|jpe?g|png|tiff?|webp)$/i.test(reference.path)diff --git a/apps/desktop/test/chat-file-reveal-menu.test.mjs b/apps/desktop/test/chat-file-reveal-menu.test.mjsindex 294263a32..00deae6e6 100644--- a/apps/desktop/test/chat-file-reveal-menu.test.mjs+++ b/apps/desktop/test/chat-file-reveal-menu.test.mjs@@ -108,7 +108,9 @@ const previewTarget = loadModule("../src/hooks/use-preview-target.ts", {},},},- "../lib/chat-links": loadModule("../src/lib/chat-links.ts", {}),+ "../lib/chat-links": loadModule("../src/lib/chat-links.ts", {+ "@pi-desktop/shared": await import("@pi-desktop/shared"),+ }),"../lib/open-http-url": { openHttpUrl: (...args) => calls.urls.push(args) },"../lib/work-panel-tabs": loadModule("../src/lib/work-panel-tabs.ts", {}),});diff --git a/apps/desktop/test/chat-links.test.mjs b/apps/desktop/test/chat-links.test.mjsindex ad23dd4df..5c9989974 100644--- a/apps/desktop/test/chat-links.test.mjs+++ b/apps/desktop/test/chat-links.test.mjs@@ -766,3 +766,20 @@ test("resolvePreviewTarget carries line/col on file chips (#681)", () => {column: 7,});});++test("session links segment as their own target", () => {+ const link = "pi-desktop://session/6f1d2c3b-4a59-4e7f-8a90-b1c2d3e4f506";+ const segments = splitChatText(`analyze ${link} please`, ROOT);+ assert.deepEqual(+ segments.map((segment) => segment.text),+ ["analyze ", link, " please"],+ );+ const target = segments.find((segment) => segment.kind === "target");+ assert.deepEqual(target.target, {+ kind: "session",+ sessionId: "6f1d2c3b-4a59-4e7f-8a90-b1c2d3e4f506",+ });+ // A remote id and a bare scheme are not local conversations.+ assert.equal(resolvePreviewTarget("pi-desktop://session/remote:abc", ROOT), null);+ assert.equal(resolvePreviewTarget("pi-desktop://session/", ROOT), null);+});diff --git a/apps/desktop/test/composer-file-reference-display.test.mjs b/apps/desktop/test/composer-file-reference-display.test.mjsindex 442c63f7c..fd18f449d 100644--- a/apps/desktop/test/composer-file-reference-display.test.mjs+++ b/apps/desktop/test/composer-file-reference-display.test.mjs@@ -52,12 +52,12 @@ test("accepted files become compact references while directories keep completion);assert.match(composer, /applyEditorDraft\(\s*nextText,/);// Workspace switches still drop relative `@` chips, not every token-backed- // chip — paste/scratch paths are absolute and plugin marks carry no path,- // so both must survive.+ // chip — paste/scratch paths are absolute, plugin marks carry no path, and a+ // session reference names a conversation, so all three must survive.assert.match(composer, /function isPersistedScratchReference\(path: string\)/);assert.match(composer,- /Boolean\(fileReference\.plugin\) \|\| isPersistedScratchReference\(fileReference\.path\)/,+ /Boolean\(fileReference\.plugin\) \|\|[\s\S]*?fileReference\.kind === "session" \|\|[\s\S]*?isPersistedScratchReference\(fileReference\.path\)/,);assert.match(composer, /kept = current\.filter\(survives\)/);assert.doesNotMatch(diff --git a/apps/desktop/test/composer-inline-image-chips.test.mjs b/apps/desktop/test/composer-inline-image-chips.test.mjsindex ee558b670..23101a0d5 100644--- a/apps/desktop/test/composer-inline-image-chips.test.mjs+++ b/apps/desktop/test/composer-inline-image-chips.test.mjs@@ -19,10 +19,10 @@ const [composer, editor, hoverCard, hoverHook, card, cardStyles, styles, submitHtest("pasted images stay inline chips like every other attachment", () => {assert.match(editor, /const image = chipIconKey\(reference\) === "image";/);assert.match(editor, /if \(image\) chip\.dataset\.image = "";/);- assert.match(editor, /const editableText = !image && isEditableTextReference\(reference\);/);+ assert.match(editor, /const editableText = !image && !session && isEditableTextReference\(reference\);/);// Activating an image chip opens the preview; it never expands draft text.- assert.match(editor, /image \? \(\) => onOpenImage\(token\)/);- assert.match(editor, /chip\.dataset\.action = editableText \? "expand-text-reference" : "open-image-preview";/);+ assert.match(editor, /image\s*\?\s*\(\) => onOpenImage\(token\)/);+ assert.match(editor, /chip\.dataset\.action = editableText/);assert.match(composer, /openImageReferenceRef\.current = \(token\) => \{[\s\S]*?imagePreview\.open\(reference\)/);// The detached attachment row above the input shell is gone.assert.doesNotMatch(composer, /ComposerImageAttachments/);diff --git a/apps/desktop/test/composer-paste-files.test.mjs b/apps/desktop/test/composer-paste-files.test.mjsindex cbaa01e0c..ff3146b9f 100644--- a/apps/desktop/test/composer-paste-files.test.mjs+++ b/apps/desktop/test/composer-paste-files.test.mjs@@ -334,3 +334,20 @@ test("large pasted text is preserved byte-for-byte in session scratch", async ()await rm(root, { recursive: true, force: true });}});++test("a pasted session link becomes an inline chip with the link as its text", () => {+ // The paste path turns each link into a token-backed chip, and the draft+ // keeps the conversation link as the text the model receives.+ assert.match(composer, /const sessionIds = parseSessionLinks\(text\);/);+ assert.match(composer, /pasteSessionLinks\(text\);/);+ assert.match(composer, /for \(const span of \[\.\.\.sessionLinkSpans\(text\)\]\.reverse\(\)\)/);+ assert.match(+ composer,+ /createFileReference\(span\.id, sessionChipName\(span\.id\), ownerSessionId, \{\s*kind: "session",\s*token,/,+ );+ assert.match(composer, /return `\$\{t\("chat\.sessionReference"\)\} · \$\{title \|\| id\.slice\(0, 8\)\}`;/);+ // The chip opens its conversation, and its token serializes back to the link.+ assert.match(composer, /if \(reference\.kind === "session"\) return "session";/);+ assert.match(composer, /chip\.dataset\.action = editableText[\s\S]*?"open-session-reference"/);+ assert.match(composer, /selectSession\(reference\.path\)/);+});diff --git a/apps/desktop/test/open-http-url.test.mjs b/apps/desktop/test/open-http-url.test.mjsindex 92f5475f3..4dc271408 100644--- a/apps/desktop/test/open-http-url.test.mjs+++ b/apps/desktop/test/open-http-url.test.mjs@@ -164,7 +164,7 @@ test("previewable transcript URLs follow the link-open setting", () => {assert.match(previewSource, /import \{ openHttpUrl \} from "\.\.\/lib\/open-http-url"/);assert.match(previewSource,- /target\.kind === "file"\s*\?\s*openFileRef\(target\.path,[\s\S]*?\)\s*:\s*openHttpUrl\(target\.url\)/,+ /if \(target\.kind === "file"\) \{[\s\S]*?openFileRef\(target\.path,[\s\S]*?\}[\s\S]*?openHttpUrl\(target\.url\)/,);});diff --git a/apps/desktop/test/session-reference-ui.test.mjs b/apps/desktop/test/session-reference-ui.test.mjsindex 7fcc92c2a..94ceb6cb6 100644--- a/apps/desktop/test/session-reference-ui.test.mjs+++ b/apps/desktop/test/session-reference-ui.test.mjs@@ -153,7 +153,7 @@ test("a referenced conversation renders as a chip naming its own target", () =>assert.match(html, /data-session-id="session-a"/);assert.match(read("../src/features/chat/transcript/shared.tsx"),- /onClick=\{\(\) => void selectSession\(attachment\.ref\)\.catch\(\(\) => undefined\)\}/,+ /onClick=\{\(\) => void selectSession\(sessionId\)\.catch\(\(\) => undefined\)\}/,"activating the chip opens the referenced conversation",);assert.ok(@@ -288,3 +288,17 @@ test("the reference keys exist in every shipped locale", () => {assert.equal(catalogs["zh-CN"].nav.copySessionLink, "复制会话链接");assert.equal(catalogs["zh-CN"].chat.sessionReference, "会话引用");});++test("a session link in the message body renders as that chip", () => {+ // A bare link in prose segments as a session target and renders through the+ // same chip the structured attachment uses, named by the live conversation.+ const source = read("../src/features/chat/transcript/shared.tsx");+ assert.match(source, /export function SessionLinkChip\(/);+ assert.match(source, /\) : segment\.target\.kind === "session" \? \(/);+ assert.match(+ source,+ /<SessionLinkChip key=\{index\} sessionId=\{segment\.target\.sessionId\} \{\.\.\.position\} \/>/,+ );+ assert.match(source, /data-action="open-session-reference"/);+ assert.match(source, /session\.id === sessionId/);+});diff --git a/apps/desktop/test/tool-row-file-refs.test.mjs b/apps/desktop/test/tool-row-file-refs.test.mjsindex be3b235de..fe3cd0ea3 100644--- a/apps/desktop/test/tool-row-file-refs.test.mjs+++ b/apps/desktop/test/tool-row-file-refs.test.mjs@@ -73,7 +73,9 @@ const { useOpenPreviewTarget } = loadModule("../src/hooks/use-preview-target.ts"},},},- "../lib/chat-links": loadModule("../src/lib/chat-links.ts", {}),+ "../lib/chat-links": loadModule("../src/lib/chat-links.ts", {+ "@pi-desktop/shared": await import("@pi-desktop/shared"),+ }),"../lib/open-http-url": { openHttpUrl: (...args) => calls.urls.push(args) },"../lib/work-panel-tabs": workPanelTabs,});diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex 6efad36d7..30dc45758 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -4187,13 +4187,12 @@ from the conversation overflow menu and pastes it into a Composer draft (issueConversation overflow Composer draft (unsent)┌─────────────────────────────┐ ┌──────────────────────────────────┐│ Pin conversation │ │ continue from │-│ Create branch │ │ pi-desktop://session/ab12cd34 │+│ Create branch │ │ [💬 Conversation · ab12cd34] ││ Copy conversation link │ └──────────────────────────────────┘│ Delete conversation │└─────────────────────────────┘ Sent user message┌──────────────────────────────────┐│ continue from │- │ pi-desktop://session/ab12cd34 ││ [💬 Conversation · Nightly check]│└──────────────────────────────────┘```@@ -4203,7 +4202,7 @@ Conversation overflow Composer draft (unsent)| State | Appearance ||---|---|| Reference attached | Chat-icon chip on the user message, named with the catalog's reference label and the referenced conversation's current title |-| Reference skipped | Nothing is attached; the link stays plaintext in the message |+| Reference skipped | Nothing is attached; the body link still renders as that chip || Another project | Skipped the same way: that transcript is not this turn's context || Self-reference | Dropped before any read, so the conversation itself is never a reference || Empty referenced conversation | The resolver attaches nothing and the message keeps the link |@@ -4229,8 +4228,9 @@ Conversation overflow Composer draft (unsent)it. The name recorded when the reference was made stays the fallback for aconversation this viewer no longer lists, and is the name the quoted blockkeeps for the model.-- The visible text is never rewritten: the link a reader typed stays in the- message, and only the attached excerpt is additive.+- The draft shows a pasted link as that chip, and the submitted text still+ carries the link: prose is never rewritten on the wire, and the attached+ excerpt is additive.- Boundary: only conversations of the same project are read, the currentconversation is dropped before any read, and a link to another project, anunknown id, or a `remote:` identifier stays plaintext rather than becoming adiff --git a/docs/zh-CN/spec/04-ux/08-component-spec.md b/docs/zh-CN/spec/04-ux/08-component-spec.mdindex 86d56593b..873a52b0a 100644--- a/docs/zh-CN/spec/04-ux/08-component-spec.md+++ b/docs/zh-CN/spec/04-ux/08-component-spec.md@@ -2905,13 +2905,12 @@ Sidebar footer Popover (360px max)对话溢出菜单 输入框草稿(未发送)┌─────────────────────────────┐ ┌──────────────────────────────────┐│ 固定对话 │ │ 接着做 │-│ 创建分支 │ │ pi-desktop://session/ab12cd34 │+│ 创建分支 │ │ [💬 会话引用 · ab12cd34] ││ 复制会话链接 │ └──────────────────────────────────┘│ 删除对话 │└─────────────────────────────┘ 已发送的用户消息┌──────────────────────────────────┐│ 接着做 │- │ pi-desktop://session/ab12cd34 ││ [💬 会话引用 · 夜间依赖检查] │└──────────────────────────────────┘```@@ -2921,7 +2920,7 @@ Sidebar footer Popover (360px max)| 状态 | 外观 ||---|---|| 已附带引用 | 用户消息上的聊天图标芯片,标签为语言目录里的引用标签加被引用对话的当前标题 |-| 引用被跳过 | 不附带任何东西;链接在消息里保持纯文本 |+| 引用被跳过 | 不附带任何东西;正文里的链接仍渲染为该芯片 || 另一个项目 | 同样跳过:那段转写不是本轮的上下文 || 自引用 | 在任何读取之前就被丢弃,当前对话永远不会成为引用 || 被引用对话为空 | 解析器不附带任何东西,消息保留链接 |@@ -2940,7 +2939,7 @@ Sidebar footer Popover (360px max)- 激活芯片会打开被引用的对话;引用是链接,不是那段转写的副本。- 芯片按被引用对话的当前标题命名:手动改名或首轮自动摘要改名,都会跟随出现在每一处引用上。粘贴链接时记录的名称,则作为这位读者已无法列出该对话时的回退,它也是引用块留给模型的名字。-- 可见文本从不被改写:读者输入的链接留在消息里,只有附带的摘录是新增的。+- 草稿把粘贴的链接显示为芯片,提交的文本仍带链接:正文从不在传输时被改写,只有附带的摘录是新增的。- 边界:只读取同一项目的对话,当前对话在任何读取之前就被丢弃,指向其他项目、不存在的 id 或 `remote:` 标识的链接保持纯文本,不会变成引用。粘贴无法让应用读取读者本来打不开的转写。diff --git a/packages/shared/src/composer-trigger.test.ts b/packages/shared/src/composer-trigger.test.tsindex 36fdff222..51ec8142f 100644--- a/packages/shared/src/composer-trigger.test.ts+++ b/packages/shared/src/composer-trigger.test.ts@@ -286,4 +286,18 @@ describe("compact file references", () => {expect(normalizeLargePasteThreshold(1_000_001)).toBe(600);expect(normalizeLargePasteThreshold(601)).toBe(601);});++ it("sends a session reference as its link, never as an @path", () => {+ const id = "6f1d2c3b-4a59-4e7f-8a90-b1c2d3e4f506";+ const reference = { path: id, kind: "session", token: "\uE001" };+ expect(serializeInlineComposerFileReferences(`look \uE001 now`, [reference])).toBe(+ `look pi-desktop://session/${id} now`,+ );+ expect(serializeComposerFileReferences(`look \uE001 now`, [reference])).toBe(+ `look pi-desktop://session/${id} now`,+ );+ // Token or not, a session reference never becomes an appended @path.+ expect(serializeComposerFileReferences("", [reference])).toBe("");+ expect(serializeComposerFileReferences("", [{ path: id, kind: "session" }])).toBe("");+ });});diff --git a/packages/shared/src/composer-trigger.ts b/packages/shared/src/composer-trigger.tsindex d11a25e60..fe64c579b 100644--- a/packages/shared/src/composer-trigger.ts+++ b/packages/shared/src/composer-trigger.ts@@ -1,3 +1,5 @@+import { formatSessionLink } from "./session-link.js";+/*** Trigger detection and completion insertion for the composer autocomplete* (D123–D125). Pure string/cursor math so the exact "/"+"@" grammar is unit@@ -180,11 +182,11 @@ type ComposerReferencePluginPart = { readonly kind?: string; readonly send?: str*/export function serializeComposerFileReferences(draft: string,- references: ReadonlyArray<{ path: string; token?: string; plugin?: ComposerReferencePluginPart }>,+ references: ReadonlyArray<{ path: string; kind?: string; token?: string; plugin?: ComposerReferencePluginPart }>,): string {const content = serializeInlineComposerFileReferences(draft, references);const paths = references- .filter((reference) => !reference.token)+ .filter((reference) => !reference.token && reference.kind !== "session").map((reference) => formatFileInsert(reference.path, "file")).join("").trim();@@ -198,18 +200,22 @@ export function serializeComposerFileReferences(* sentinel characters backing atomic chips). Each resolved token keeps one* separating space so adjacent chips never fuse their @paths together. A* plugin mark's token resolves to the text it sends (`plugin.send`) instead- * of a path.+ * of a path, and a session reference resolves to its `pi-desktop://` link.*/export function serializeInlineComposerFileReferences(draft: string,- references: ReadonlyArray<{ path: string; token?: string; plugin?: ComposerReferencePluginPart }>,+ references: ReadonlyArray<{ path: string; kind?: string; token?: string; plugin?: ComposerReferencePluginPart }>,): string {let content = draft;for (const reference of references) {const token = reference.token?.trim();if (!token || !content.includes(token)) continue;const send = reference.plugin?.send;- const insert = typeof send === "string" ? send : formatFileInsert(reference.path, "file").trim();+ const insert = typeof send === "string"+ ? send+ : reference.kind === "session"+ ? formatSessionLink(reference.path)+ : formatFileInsert(reference.path, "file").trim();let index = content.indexOf(token);while (index !== -1) {const nextChar = content[index + token.length];diff --git a/packages/shared/src/session-link.test.ts b/packages/shared/src/session-link.test.tsindex 848da9708..6a173add4 100644--- a/packages/shared/src/session-link.test.ts+++ b/packages/shared/src/session-link.test.ts@@ -4,6 +4,8 @@ import {isSessionLinkToken,MAX_SESSION_LINKS_PER_MESSAGE,parseSessionLinks,+ parseSessionLinkToken,+ sessionLinkSpans,} from "./session-link.js";describe("session links", () => {@@ -43,4 +45,20 @@ describe("session links", () => {expect(isSessionLinkToken(formatSessionLink("abc"))).toBe(true);expect(isSessionLinkToken("@src/index.ts")).toBe(false);});+ it("names the id only when the whole token is one link", () => {+ expect(parseSessionLinkToken(formatSessionLink("abc"))).toBe("abc");+ expect(parseSessionLinkToken(` ${formatSessionLink("abc")} `)).toBe("abc");+ expect(parseSessionLinkToken(`see ${formatSessionLink("abc")}`)).toBeNull();+ expect(parseSessionLinkToken("pi-desktop://session/")).toBeNull();+ expect(parseSessionLinkToken("@src/index.ts")).toBeNull();+ });++ it("reports every link span in text order", () => {+ const text = `first ${formatSessionLink("aaa")} then ${formatSessionLink("bbb")}`;+ const spans = sessionLinkSpans(text);+ expect(spans.map((span) => span.id)).toEqual(["aaa", "bbb"]);+ expect(text.slice(spans[0].start, spans[0].end)).toBe(formatSessionLink("aaa"));+ expect(text.slice(spans[1].start, spans[1].end)).toBe(formatSessionLink("bbb"));+ expect(sessionLinkSpans("nothing here")).toEqual([]);+ });});diff --git a/packages/shared/src/session-link.ts b/packages/shared/src/session-link.tsindex 48f8c361b..e38847523 100644--- a/packages/shared/src/session-link.ts+++ b/packages/shared/src/session-link.ts@@ -52,3 +52,25 @@ export function parseSessionLinks(text: string): string[] {export function isSessionLinkToken(token: string): boolean {return parseSessionLinks(token).length > 0;}++/** The session id when the whole token is one session link, otherwise null. */+export function parseSessionLinkToken(text: string): string | null {+ const trimmed = text.trim();+ if (!trimmed.startsWith(`${SESSION_LINK_SCHEME}://${SESSION_LINK_HOST}/`)) return null;+ const ids = parseSessionLinks(trimmed);+ return ids.length === 1 && trimmed.endsWith(ids[0]) ? ids[0] : null;+}++/** Every session link in `text` with the span it occupies, in text order. */+export function sessionLinkSpans(+ text: string,+): Array<{ id: string; start: number; end: number }> {+ if (!text?.includes(`${SESSION_LINK_SCHEME}://`)) return [];+ const spans: Array<{ id: string; start: number; end: number }> = [];+ for (const match of text.matchAll(SESSION_LINK_PATTERN)) {+ const id = match[1];+ if (!SESSION_LINK_ID.test(id) || match.index === undefined) continue;+ spans.push({ id, start: match.index, end: match.index + match[0].length });+ }+ return spans;+}diff --git a/scripts/e2e/composer-paste.tsx b/scripts/e2e/composer-paste.tsxindex 4b76a5fca..bf6e678a3 100644--- a/scripts/e2e/composer-paste.tsx+++ b/scripts/e2e/composer-paste.tsx@@ -1,4 +1,4 @@-import { serializeInlineComposerFileReferences, type MessageAttachment } from "@pi-desktop/shared";+import { formatSessionLink, serializeInlineComposerFileReferences, type MessageAttachment } from "@pi-desktop/shared";import { useComposerInputHistory } from "../../apps/desktop/src/features/chat/composer/hooks/useComposerInputHistory";import type { AppState } from "../../apps/desktop/src/stores/app-state";import { createQueueSlice } from "../../apps/desktop/src/stores/slices/queue-slice";@@ -829,6 +829,28 @@ globalThis.composerPasteProbe = async () => {controller.ref.current!.querySelector(".composer-chip[data-image]"),"image-only draft did not survive session switching");+ // A pasted conversation link is an inline chip, and the submitted text+ // carries that link again.+ const linkedSession = "session-link-fixture";+ editor = await paste(`continue from ${formatSessionLink(linkedSession)}`, []);+ const linkChip = editor.querySelector<HTMLElement>(+ `.composer-chip[data-session-id="${linkedSession}"]`,+ );+ assert(linkChip, "a pasted conversation link must render as an inline chip");+ assert(+ !readEditorValue(editor).includes(formatSessionLink(linkedSession)),+ "the chip replaces the raw link in the draft text",+ );+ assert(+ serializeInlineComposerFileReferences(readEditorValue(editor), controller.fileReferences)+ .includes(formatSessionLink(linkedSession)),+ "the submitted text carries the conversation link",+ );+ assert(+ linkChip!.querySelector(".composer-chip-name")?.textContent?.includes(linkedSession.slice(0, 8)),+ "the chip names the conversation it opens",+ );+await paste("file names", nativeFiles);assert(controller.fileReferences.length === 2,