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(chat): reference another conversation by pasting its link
Hanawa888e29a30fdb
diff --git a/apps/desktop/electron/main/ipc/agent-ipc.ts b/apps/desktop/electron/main/ipc/agent-ipc.tsindex 1b9d1befc..98396665d 100644--- a/apps/desktop/electron/main/ipc/agent-ipc.ts+++ b/apps/desktop/electron/main/ipc/agent-ipc.ts@@ -3,6 +3,7 @@ import type { FinishTurn } from "../runtime/plans";import { expandSlashInvocation, enhancePromptDraft, summarizeSessionTitle, visionFromModelConfig, type ComposerTemplate, type RuntimeProviderConfig } from "@pi-desktop/agent-runtime";import { OAUTH_AUTH_KIND, type VendorOAuth } from "../oauth";import { appendPromptFallbackPaths, durableUserMessageId, preparePromptAttachments, type PreparedPromptAttachment } from "../prompt-attachments";+import { resolveSessionReferences } from "../session-references";import { executionFromResponse, resolveSessionMessageInput } from "@pi-desktop/host-runtime";import type { AgentExtensionBridge } from "../agent-extensions";import type { AgentHostBridge } from "../agent-host-bridge";@@ -542,6 +543,19 @@ export function registerAgentIpc({});throw error;}+ // A `pi-desktop://session/<id>` link in the draft becomes a bounded excerpt+ // that travels with this message from now on (issue #1324). A skipped link+ // stays plain text; nothing else about the prompt changes.+ const sessionReferences = await resolveSessionReferences({+ host,+ logger,+ sessionId: req.sessionId,+ projectPath:+ typeof session.projectPath === "string" && session.projectPath.trim()+ ? session.projectPath.trim()+ : undefined,+ content: req.content,+ });const modelContent = appendPromptFallbackPaths(promptContent,preparedAttachments,@@ -568,8 +582,13 @@ export function registerAgentIpc({...(sessionMessage ? { sessionMessage: sessionMessage.origin } : {}),createdAt: new Date().toISOString(),status: "complete" as const,- ...(preparedAttachments.length- ? { attachments: preparedAttachments.map((attachment) => attachment.message) }+ ...(preparedAttachments.length || sessionReferences.length+ ? {+ attachments: [+ ...preparedAttachments.map((attachment) => attachment.message),+ ...sessionReferences,+ ],+ }: {}),...(voiceOrigin ? { voiceOrigin } : {}),...(slashCommand ? { command: slashCommand } : {}),@@ -623,16 +642,26 @@ export function registerAgentIpc({turnId: durableTurnId,content: modelContent,...(sessionMessage ? { sessionMessage: sessionMessage.origin } : {}),- attachments: preparedAttachments- .filter((attachment) => attachment.inlineData)- .map((attachment) => ({- path: attachment.message.ref,- name: attachment.message.name,- kind: attachment.message.kind,- mimeType: attachment.message.mimeType,- size: attachment.message.size,- data: attachment.inlineData,+ attachments: [+ ...preparedAttachments+ .filter((attachment) => attachment.inlineData)+ .map((attachment) => ({+ path: attachment.message.ref,+ name: attachment.message.name,+ kind: attachment.message.kind,+ mimeType: attachment.message.mimeType,+ size: attachment.message.size,+ data: attachment.inlineData,+ })),+ // A referenced conversation crosses the sidecar as quoted text for+ // this turn; the durable record above keeps it for later turns.+ ...sessionReferences.map((attachment) => ({+ path: attachment.ref,+ name: attachment.name,+ kind: attachment.kind,+ text: attachment.text,})),+ ],userMessageId: userMessage.id,// Per-turn permission ceiling override (R1 leftover; spec §7.3). The// sidecar records it on the turn context; enforcement of a NARROWERdiff --git a/apps/desktop/electron/main/session-references.ts b/apps/desktop/electron/main/session-references.tsnew file mode 100644index 000000000..e4b756387--- /dev/null+++ b/apps/desktop/electron/main/session-references.ts@@ -0,0 +1,134 @@+/**+ * Session references: `pi-desktop://session/<id>` links a Composer draft carries.+ *+ * The link is the whole interaction — no new Composer trigger symbol — and the+ * transcript shows it as a card next to the user's words. Electron main is the+ * only writer: it reads the referenced conversation through the host, refuses+ * what this conversation may not pull, and attaches a bounded excerpt that+ * travels with the message from then on.+ */+import { parseSessionLinks, type MessageAttachment } from "@pi-desktop/shared";+import type { HostProcess } from "./host-process";+import type { Logger } from "./logger";++/** Newest messages read from the referenced conversation. */+export const SESSION_REFERENCE_MESSAGE_LIMIT = 40;+/** Per-field cap for one referenced message. */+export const SESSION_REFERENCE_CONTENT_LIMIT = 8 * 1024;+/** Whole excerpt cap; the model gets a bounded quotation, never a whole session. */+export const SESSION_REFERENCE_TOTAL_LIMIT = 16 * 1024;++type ReferencedMessage = {+ role?: string;+ content?: string;+ toolName?: string;+ isError?: boolean;+};++type ReferencedSession = {+ id?: string;+ title?: string;+ projectPath?: string;+ messages?: ReferencedMessage[];+};++/** The words the model sees for one referenced conversation. */+export function formatSessionExcerpt(+ session: ReferencedSession,+ limit = SESSION_REFERENCE_TOTAL_LIMIT,+): string {+ const title = (session.title || session.id || "").trim();+ const lines: string[] = [];+ const messages = [...(session.messages ?? [])].reverse();+ let used = 0;+ let omitted = 0;+ for (const message of messages) {+ const text = (message.content ?? "").trim();+ if (!text) continue;+ const role = message.toolName+ ? `tool ${message.toolName}`+ : message.role === "assistant"+ ? "assistant"+ : "user";+ const line = `${role}: ${text}`;+ if (used + line.length > limit) {+ omitted += 1;+ continue;+ }+ used += line.length;+ lines.unshift(line);+ }+ if (!lines.length) return "";+ const head = [+ `Referenced conversation "${title}" (${session.id ?? "unknown"}).`,+ `${lines.length} message${lines.length === 1 ? "" : "s"} shown in order, newest last` ++ (omitted ? `, ${omitted} earlier message${omitted === 1 ? "" : "s"} omitted for length.` : "."),+ ].join(" ");+ return [head, "", ...lines].join("\n");+}++/** The project a path belongs to, as the host compares it. */+function canonicalProject(path: string | undefined): string {+ return (path ?? "").replace(/[\\/]+$/, "");+}++/**+ * Resolves every session link in one prompt into an attachment record. Skipped+ * references stay plain text in the message: the current conversation is never+ * referenced, and another project's transcript is not this turn's context.+ */+export async function resolveSessionReferences({+ host,+ logger,+ sessionId,+ projectPath,+ content,+}: {+ host: HostProcess;+ logger: Pick<Logger, "app">;+ sessionId: string;+ projectPath?: string;+ content: string;+}): Promise<MessageAttachment[]> {+ const ids = parseSessionLinks(content).filter((id) => id !== sessionId);+ if (!ids.length) return [];+ const attachments: MessageAttachment[] = [];+ for (const id of ids) {+ try {+ const result = await host.call<{ session?: ReferencedSession }>("session.get", {+ id,+ messageLimit: SESSION_REFERENCE_MESSAGE_LIMIT,+ contentLimit: SESSION_REFERENCE_CONTENT_LIMIT,+ });+ const referenced = result.session;+ if (!referenced) {+ logger.app("session", "warn", "session reference not found", {+ sessionId,+ data: id,+ });+ continue;+ }+ if (canonicalProject(referenced.projectPath) !== canonicalProject(projectPath)) {+ logger.app("session", "warn", "session reference outside this project was skipped", {+ sessionId,+ data: id,+ });+ continue;+ }+ const text = formatSessionExcerpt(referenced);+ if (!text) continue;+ attachments.push({+ kind: "session",+ name: (referenced.title || id).trim(),+ ref: id,+ text,+ });+ } catch (error) {+ logger.app("session", "warn", "session reference read failed", {+ sessionId,+ data: `${id}: ${String(error)}`,+ });+ }+ }+ return attachments;+}diff --git a/apps/desktop/src/components/Sidebar.tsx b/apps/desktop/src/components/Sidebar.tsxindex 1e5cfb1a9..8dbd6543e 100644--- a/apps/desktop/src/components/Sidebar.tsx+++ b/apps/desktop/src/components/Sidebar.tsx@@ -43,7 +43,7 @@ import {sidebarSessionStatus,type SidebarSessionStatus,} from "../lib/sidebar-session-status";-import { ErrorCodes } from "@pi-desktop/shared";+import { ErrorCodes, formatSessionLink } from "@pi-desktop/shared";import type { SessionSummary } from "@pi-desktop/shared";import type {ProjectMeta,@@ -1439,6 +1439,20 @@ export function Sidebar({closeMenus();};+ /**+ * The link another conversation references: pasting it into a Composer draft+ * carries a bounded excerpt of this conversation into that turn (issue #1324).+ */+ const copySessionLink = async (session: SessionSummary) => {+ try {+ await navigator.clipboard.writeText(formatSessionLink(session.id));+ showToast(t("chat.copied"));+ } catch (error) {+ reportError(error);+ }+ closeMenus();+ };+const openSessionPath = async (session: SessionSummary) => {closeMenus(false);try {@@ -2178,6 +2192,15 @@ export function Sidebar({{t("nav.createBranch")}</button>) : null}+ <button+ type="button"+ role="menuitem"+ data-action="copy-session-link"+ onClick={() => void copySessionLink(session)}+ >+ <IconCopy size={14} />+ {t("nav.copySessionLink")}+ </button>{settings?.developerMode === true ? (<><buttondiff --git a/apps/desktop/src/features/chat/transcript/MessageRow.tsx b/apps/desktop/src/features/chat/transcript/MessageRow.tsxindex 145c3f16a..33314111b 100644--- a/apps/desktop/src/features/chat/transcript/MessageRow.tsx+++ b/apps/desktop/src/features/chat/transcript/MessageRow.tsx@@ -30,6 +30,7 @@ import {LinkifiedText,MessageAttachmentImage,MessageTimestamp,+ SessionRefChip,} from "./shared";import {useChatTextActions,@@ -264,6 +265,10 @@ export const MessageRow = memo(function MessageRow({attachment={attachment}onOpenFile={openFileRef}/>+ ) : attachment.kind === "session" ? (+ <span key={`${attachment.ref}:${attachment.name}`} role="listitem">+ <SessionRefChip attachment={attachment} />+ </span>) : (<spankey={`${attachment.ref}:${attachment.name}`}diff --git a/apps/desktop/src/features/chat/transcript/shared.tsx b/apps/desktop/src/features/chat/transcript/shared.tsxindex 019dd4974..6154ea551 100644--- a/apps/desktop/src/features/chat/transcript/shared.tsx+++ b/apps/desktop/src/features/chat/transcript/shared.tsx@@ -38,6 +38,7 @@ import {IconAudio,IconBot,IconBranch,+ IconChat,IconCheck,IconChevronRight,IconCircleAlert,@@ -455,6 +456,33 @@ 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.+ */+export function SessionRefChip({ attachment }: { attachment: MessageAttachment }) {+ const { t } = useTranslation();+ const selectSession = useAppStore((state) => state.selectSession);+ const label = `${t("chat.sessionReference")} · ${attachment.name}`;+ return (+ <button+ type="button"+ className="composer-chip chat-file-chip"+ data-action="open-session-reference"+ data-session-id={attachment.ref}+ title={t("chat.sessionReferenceOpen", { title: attachment.name })}+ aria-label={label}+ onClick={() => void selectSession(attachment.ref).catch(() => undefined)}+ >+ <span className="composer-chip-icon" aria-hidden>+ <IconChat size={13} />+ </span>+ <span className="composer-chip-name">{label}</span>+ </button>+ );+}+/*** User-message image attachment as a thumbnail. The host resolves the ref* into a bounded data URL; an unresolvable load falls back to the file chip.diff --git a/apps/desktop/src/stores/helpers/store-helpers.ts b/apps/desktop/src/stores/helpers/store-helpers.tsindex 63757e545..c8585cbf8 100644--- a/apps/desktop/src/stores/helpers/store-helpers.ts+++ b/apps/desktop/src/stores/helpers/store-helpers.ts@@ -9,7 +9,7 @@ import type {SessionSummary,UiMessage,} from "@pi-desktop/shared";-import { modeForProposalKind } from "@pi-desktop/shared";+import { isRenderableAttachment, modeForProposalKind } from "@pi-desktop/shared";import type { ComposerDraftSnapshot } from "../../lib/composer-smart-stop";import { normalizeProjectPath } from "../../lib/sidebar-session-groups";import {@@ -48,13 +48,17 @@ export function promptAttachmentsFromDraft(export function promptAttachmentsFromMessage(attachments: UiMessage["attachments"],): AgentPromptAttachment[] {- return (attachments ?? []).map((attachment) => ({- path: attachment.ref,- name: attachment.name,- kind: attachment.kind,- ...(attachment.mimeType ? { mimeType: attachment.mimeType } : {}),- ...(attachment.size !== undefined ? { size: attachment.size } : {}),- }));+ // A session reference is not a renderer-resolvable attachment: its link text+ // is still in the message, so main re-resolves it on the next send.+ return (attachments ?? [])+ .filter(isRenderableAttachment)+ .map((attachment) => ({+ path: attachment.ref,+ name: attachment.name,+ kind: attachment.kind,+ ...(attachment.mimeType ? { mimeType: attachment.mimeType } : {}),+ ...(attachment.size !== undefined ? { size: attachment.size } : {}),+ }));}export function withoutRecordKey<T>(record: Record<string, T>, key: string): Record<string, T> {diff --git a/apps/desktop/src/stores/slices/transcript-slice.ts b/apps/desktop/src/stores/slices/transcript-slice.tsindex 7379b2bbe..0987ee1b1 100644--- a/apps/desktop/src/stores/slices/transcript-slice.ts+++ b/apps/desktop/src/stores/slices/transcript-slice.ts@@ -2,6 +2,7 @@ import i18n from "i18next";import type {UiMessage,} from "@pi-desktop/shared";+import { isRenderableAttachment } from "@pi-desktop/shared";import { api } from "../../lib/api";import { resolveComposerSmartStop } from "../../lib/composer-smart-stop";import {@@ -143,14 +144,16 @@ export function createTranscriptSlice({const optimisticMessage = optimisticUserMessage(crypto.randomUUID(),prompt,- (attachments ?? state.messages[userIndex].attachments ?? []).map(- (attachment) => ({+ (attachments ?? state.messages[userIndex].attachments ?? [])+ // A session reference re-resolves from its link text on send; it is+ // not an optimistic file reference.+ .filter(isRenderableAttachment)+ .map((attachment) => ({path: attachment.ref,name: attachment.name,kind: attachment.kind,mimeType: attachment.mimeType,- }),- ),+ })),);set((current) => ({diff --git a/apps/desktop/test/session-reference-ui.test.mjs b/apps/desktop/test/session-reference-ui.test.mjsnew file mode 100644index 000000000..e61849ab5--- /dev/null+++ b/apps/desktop/test/session-reference-ui.test.mjs@@ -0,0 +1,260 @@+/**+ * Session references in the transcript (issue #1324): the chip a user message+ * shows for `pi-desktop://session/<id>`, and the two prompt paths that must not+ * hand a referenced conversation to the file-attachment resolver.+ */+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import { register } from "node:module";+import { dirname, join } from "node:path";+import test from "node:test";+import { fileURLToPath, pathToFileURL } from "node:url";+import * as React from "react";+import * as jsxRuntime from "react/jsx-runtime";+import { renderToStaticMarkup } from "react-dom/server";+import ts from "typescript";+import { catalogs } from "@pi-desktop/i18n";+import { formatSessionLink, isRenderableAttachment } from "@pi-desktop/shared";++const here = dirname(fileURLToPath(import.meta.url));+register(pathToFileURL(join(here, "helpers/ts-import-hooks.mjs")));++const read = (path) => readFileSync(new URL(path, import.meta.url), "utf8");++/** The shipped catalogs answer `t`, so the assertions read real wording. */+let locale = "en";+const t = (key, values) => {+ const raw = key+ .split(".")+ .reduce(+ (node, part) => (node && typeof node === "object" ? node[part] : undefined),+ catalogs[locale],+ );+ if (typeof raw !== "string") return key;+ return values+ ? raw.replace(/\{\{(\w+)\}\}/g, (_, name) => String(values[name] ?? ""))+ : raw;+};++const useAppStore = (selector) => selector({ selectSession: async () => {} });++const Icon = () => React.createElement("svg", { "aria-hidden": true });++/**+ * The modules below render through the repository's own transpile-and-stub+ * pattern: the real component source, with its surroundings replaced.+ */+function load(file, imports) {+ const source = readFileSync(file, "utf8");+ const { outputText } = ts.transpileModule(source, {+ compilerOptions: { module: ts.ModuleKind.CommonJS, jsx: ts.JsxEmit.ReactJSX },+ fileName: file.pathname,+ });+ const module = { exports: {} };+ new Function("require", "exports", "module", outputText)(+ (id) => {+ assert.ok(Object.hasOwn(imports, id), `unmocked dependency ${id} of ${file.pathname}`);+ return imports[id];+ },+ module.exports,+ module,+ );+ return module.exports;+}++const shared = load(new URL("../src/features/chat/transcript/shared.tsx", import.meta.url), {+ react: React,+ "react/jsx-runtime": jsxRuntime,+ "react-i18next": { useTranslation: () => ({ t, i18n: { language: locale } }) },+ "@pi-desktop/shared": await import("@pi-desktop/shared"),+ "./disclosure": {},+ "../../../hooks/use-preview-target": {+ useOpenChatFileRef: () => () => {},+ useOpenPreviewTarget: () => undefined,+ },+ "../../../hooks/use-chat-file-menu": { useChatFileMenu: () => ({}) },+ "../../../hooks/use-verified-chat-text": {+ useVerifiedChatText: (text) => [{ kind: "text", text: String(text ?? "") }],+ },+ "../../../components/ContextMenu": { ContextMenu: () => null },+ "../../../components/Markdown": {+ Markdown: ({ source }) => source,+ useCopy: () => ({ copied: false, copy: () => {} }),+ },+ "../../../components/icons": new Proxy({}, { get: () => Icon }),+ "../../../components/ui": {+ TooltipButton: ({ ariaLabel, tooltip, ...props }) =>+ React.createElement("button", { ...props, "aria-label": ariaLabel ?? tooltip }),+ },+ "../../../lib/disclosure-anchor-context": { useDisclosureAnchorNotifier: () => {} },+ "../../../lib/turn-process": { isThinkingActive: () => false, resolveThinkingDisplayMode: () => "none" },+ "../../../lib/transcript-search-context": { TranscriptSearchContext: React.createContext(null) },+ "../../../lib/assistant-turns": { messageThinking: () => "" },+ "../../../lib/use-referenced-image-data-url": { useReferencedImageDataUrl: () => undefined },+ "../../../lib/chat-links": { isHtmlFilePath: () => false },+ "../../../lib/context-usage": { calculateTokenRate: () => 0 },+ "../../../stores/app-store": { useAppStore },+});++const { MessageRow } = load(new URL("../src/features/chat/transcript/MessageRow.tsx", import.meta.url), {+ react: React,+ "react/jsx-runtime": jsxRuntime,+ "react-i18next": { useTranslation: () => ({ t, i18n: { language: locale } }) },+ "@pi-desktop/shared": await import("@pi-desktop/shared"),+ "../../../hooks/use-preview-target": { useOpenChatFileRef: () => () => {} },+ "../../../lib/chat-links": { splitChatText: () => [] },+ "../../../components/Markdown": { Markdown: ({ source }) => source },+ "../../../components/icons": new Proxy({}, { get: () => Icon }),+ "../../../components/ui": {+ TooltipButton: ({ ariaLabel, tooltip, ...props }) =>+ React.createElement("button", { ...props, "aria-label": ariaLabel ?? tooltip }),+ },+ "../../../stores/app-store": { useAppStore },+ "../../../plugins/renderer-slots/slot-message": { slotMessage: () => undefined },+ "./menu-items": { userMessageMenuItems: () => [] },+ "./ActionBarSlots": { ActionSlotSide: () => null },+ "./SessionMessageOrigin": { SessionMessageOrigin: () => null },+ "./TranscriptMenu": {+ useTranscriptMenu: () => () => {},+ useChatTextActions: () => ({ copyText: () => {}, selectText: () => {} }),+ },+ "./shared": shared,+});++const referenced = {+ kind: "session",+ name: "Nightly review",+ ref: "session-a",+ text: 'Referenced conversation "Nightly review" (session-a).\n\nuser: ship it',+};++const userMessage = {+ id: "user-row",+ role: "user",+ content: `continue from ${formatSessionLink("session-a")}`,+ status: "complete",+ createdAt: "2026-09-26T10:00:00.000Z",+ attachments: [referenced],+};++const renderChip = () =>+ renderToStaticMarkup(React.createElement(shared.SessionRefChip, { attachment: referenced }));+const renderRow = (message) =>+ renderToStaticMarkup(React.createElement(MessageRow, { message, isRunning: false }));++test("a referenced conversation renders as a chip naming its own target", () => {+ locale = "en";+ const html = renderChip();+ assert.match(html, /data-action="open-session-reference"/);+ assert.match(html, /data-session-id="session-a"/);+ assert.match(+ read("../src/features/chat/transcript/shared.tsx"),+ /onClick=\{\(\) => void selectSession\(attachment\.ref\)\.catch\(\(\) => undefined\)\}/,+ "activating the chip opens the referenced conversation",+ );+ assert.ok(+ html.includes(`${catalogs.en.chat.sessionReference} · Nightly review`),+ "the chip names the reference from the catalog",+ );+ assert.ok(+ html.includes(`title="${catalogs.en.chat.sessionReferenceOpen.replace("{{title}}", "Nightly review")}"`),+ "the tooltip says what opening it does",+ );+ assert.doesNotMatch(html, /pi-desktop:\/\/session\//, "the raw link is the message's, not the chip's");+});++test("the chip speaks the reader's language", () => {+ locale = "zh-CN";+ const html = renderChip();+ assert.match(html, /会话引用 · Nightly review/);+ assert.match(html, /title="打开会话 Nightly review"/);+ assert.match(html, /aria-label="会话引用 · Nightly review"/);+});++test("a user message shows the reference next to its own words", () => {+ locale = "en";+ const html = renderRow(userMessage);+ assert.match(html, /class="message-attachments"/);+ assert.match(html, /data-action="open-session-reference"/);+ assert.match(html, /data-session-id="session-a"/);+ assert.ok(+ html.includes(formatSessionLink("session-a")),+ "the link text stays in the message: it is what main re-resolves",+ );+});++test("a referenced conversation is not rendered as a file chip", () => {+ locale = "en";+ const withFile = {+ ...userMessage,+ attachments: [referenced, { kind: "file", name: "notes.md", ref: "/p/notes.md" }],+ };+ const html = renderRow(withFile);+ assert.match(html, /data-action="open-session-reference"/, "the reference keeps its own chip");+ assert.match(html, /aria-label="notes\.md — \/p\/notes\.md"/, "an ordinary file attachment is untouched");+ assert.equal(html.match(/chat-file-chip/g).length, 2, "two attachments, two chips");+});++test("a referenced conversation never reaches the file-attachment resolver", async () => {+ const { promptAttachmentsFromMessage } = await import(+ "../src/stores/helpers/store-helpers.ts"+ );+ const prompt = promptAttachmentsFromMessage(userMessage.attachments);+ assert.deepEqual(prompt, [], "a session reference is not a prompt attachment");++ const mixed = promptAttachmentsFromMessage([+ { kind: "image", name: "shot.png", ref: "/p/shot.png", mimeType: "image/png" },+ referenced,+ { kind: "file", name: "notes.md", ref: "/p/notes.md", size: 12 },+ ]);+ assert.deepEqual(mixed, [+ { path: "/p/shot.png", name: "shot.png", kind: "image", mimeType: "image/png" },+ { path: "/p/notes.md", name: "notes.md", kind: "file", size: 12 },+ ]);+ assert.equal(isRenderableAttachment(referenced), false);+ assert.match(+ read("../src/stores/slices/transcript-slice.ts"),+ /\.filter\(isRenderableAttachment\)/,+ "the optimistic edit path uses the same narrowing as the prompt path",+ );+});++test("the conversation overflow menu copies the link for every reader", () => {+ const sidebar = read("../src/components/Sidebar.tsx");+ assert.match(sidebar, /data-action="copy-session-link"/);+ assert.match(sidebar, /t\("nav\.copySessionLink"\)/);+ assert.match(sidebar, /navigator\.clipboard\.writeText\(formatSessionLink\(session\.id\)\)/);+ assert.doesNotMatch(sidebar, /pi-desktop:\/\/session\//, "the scheme stays in shared");++ const link = sidebar.indexOf('data-action="copy-session-link"');+ const fork = sidebar.indexOf('data-action="fork-session"');+ const developer = sidebar.indexOf('data-action="copy-conversation-id"');+ assert.ok(+ link > 0 && link > fork && link < developer,+ "an ordinary reader sees it; the developer-only actions stay behind their gate",+ );+});++test("the reference keys exist in every shipped locale", () => {+ const locales = Object.keys(catalogs);+ assert.equal(locales.length, 9, "nine locales ship");+ for (const code of locales) {+ const catalog = catalogs[code];+ for (const [group, key] of [+ ["nav", "copySessionLink"],+ ["chat", "sessionReference"],+ ["chat", "sessionReferenceOpen"],+ ]) {+ const value = catalog[group]?.[key];+ assert.equal(typeof value, "string", `${code} is missing ${group}.${key}`);+ assert.ok(value.trim().length > 0, `${code} has an empty ${group}.${key}`);+ }+ assert.match(+ catalog.chat.sessionReferenceOpen,+ /\{\{title\}\}/,+ `${code} names the conversation it opens`,+ );+ }+ assert.equal(catalogs["zh-CN"].nav.copySessionLink, "复制会话链接");+ assert.equal(catalogs["zh-CN"].chat.sessionReference, "会话引用");+});diff --git a/apps/desktop/test/session-references.test.mjs b/apps/desktop/test/session-references.test.mjsnew file mode 100644index 000000000..b810bd160--- /dev/null+++ b/apps/desktop/test/session-references.test.mjs@@ -0,0 +1,139 @@+import assert from "node:assert/strict";+import test from "node:test";+import { register } from "node:module";+import { dirname, join } from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";++const here = dirname(fileURLToPath(import.meta.url));+register(pathToFileURL(join(here, "helpers/ts-import-hooks.mjs")));++const { formatSessionLink, parseSessionLinks } = await import("@pi-desktop/shared");+const { formatSessionExcerpt, resolveSessionReferences } = await import(+ "../electron/main/session-references.ts"+);++const PROJECT = "/Users/dev/project";++/** Only the host surface the resolver uses: `session.get`. */+function fakeHost(sessions) {+ const calls = [];+ return {+ calls,+ async call(method, params) {+ calls.push([method, params]);+ return { session: sessions[params?.id] };+ },+ };+}++const silentLogger = { app() {} };++test("a session excerpt is bounded, ordered, and states what it left out", () => {+ const messages = Array.from({ length: 6 }, (_, index) => ({+ role: index % 2 === 0 ? "user" : "assistant",+ content: `message ${index}`,+ }));+ const text = formatSessionExcerpt(+ { id: "session-a", title: "Nightly review", messages },+ 64,+ );+ assert.match(text, /Referenced conversation "Nightly review" \(session-a\)/);+ assert.match(text, /\(session-a\)\. \d+ messages? shown in order, newest last, \d+ earlier messages?/);+ assert.match(text, /omitted for length/);+ const lines = text.split("\n").filter((line) => /^[a-z][a-z ]*: /.test(line));+ assert.ok(lines.length > 0 && lines.length < messages.length, "the tail stays, the head is cut");+ assert.equal(lines.at(-1), "assistant: message 5", "newest message last");+ assert.ok(text.length <= 200, "the whole excerpt stays near the requested bound");+});++test("an empty reference never produces an excerpt", () => {+ assert.equal(formatSessionExcerpt({ id: "session-a", messages: [] }), "");+ assert.equal(+ formatSessionExcerpt({ id: "session-a", messages: [{ role: "user", content: " " }] }),+ "",+ );+});++test("session links resolve against their own project only", async () => {+ const host = fakeHost({+ "same-project": {+ id: "same-project",+ title: "Dependency sweep",+ projectPath: PROJECT,+ messages: [+ { role: "user", content: "check the lockfile" },+ { role: "assistant", content: "two advisories" },+ ],+ },+ "other-project": {+ id: "other-project",+ title: "Elsewhere",+ projectPath: "/Users/dev/other",+ messages: [{ role: "user", content: "secret" }],+ },+ });++ const content = `please continue from ${formatSessionLink("same-project")} and ${formatSessionLink(+ "other-project",+ )}`;+ const attachments = await resolveSessionReferences({+ host,+ logger: silentLogger,+ sessionId: "current",+ projectPath: PROJECT,+ content,+ });++ assert.equal(attachments.length, 1, "only the same-project reference is attached");+ assert.deepEqual(+ { kind: attachments[0].kind, name: attachments[0].name, ref: attachments[0].ref },+ { kind: "session", name: "Dependency sweep", ref: "same-project" },+ );+ assert.match(attachments[0].text, /user: check the lockfile/);+ assert.match(attachments[0].text, /assistant: two advisories/);+ assert.deepEqual(+ host.calls.map(([, params]) => params.id),+ ["same-project", "other-project"],+ "each link is read through the host with a bounded window",+ );+ assert.equal(host.calls[0][1].id, "same-project");+ assert.ok(host.calls[0][1].messageLimit > 0 && host.calls[0][1].contentLimit > 0);+ assert.deepEqual(parseSessionLinks(content), ["same-project", "other-project"]);+});++test("the current session is never referenced and a missing one is skipped", async () => {+ const host = fakeHost({});+ const attachments = await resolveSessionReferences({+ host,+ logger: silentLogger,+ sessionId: "current",+ projectPath: PROJECT,+ content: `${formatSessionLink("current")} ${formatSessionLink("missing")}`,+ });+ assert.deepEqual(attachments, []);+ assert.deepEqual(+ host.calls.map(([, params]) => params.id),+ ["missing"],+ "a self-reference is dropped before any read",+ );+});++test("a resolved reference keeps the message text untouched", async () => {+ const host = fakeHost({+ "session-a": {+ id: "session-a",+ title: "A",+ projectPath: PROJECT,+ messages: [{ role: "user", content: "hi" }],+ },+ });+ const content = `see ${formatSessionLink("session-a")}`;+ await resolveSessionReferences({+ host,+ logger: silentLogger,+ sessionId: "current",+ projectPath: PROJECT,+ content,+ });+ assert.equal(content, `see ${formatSessionLink("session-a")}`);+});diff --git a/crates/host-core/src/sessions.rs b/crates/host-core/src/sessions.rsindex 0b2478225..2280766ed 100644--- a/crates/host-core/src/sessions.rs+++ b/crates/host-core/src/sessions.rs@@ -153,6 +153,11 @@ pub struct MessageAttachment {pub mime_type: Option<String>,#[serde(skip_serializing_if = "Option::is_none")]pub size: Option<i64>,+ /// Bounded excerpt of a referenced conversation (`kind: "session"`), written+ /// by Electron main when the prompt carried a `pi-desktop://session/<id>`+ /// link. Travels with the user message so the model keeps reading it.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub text: Option<String>,}#[derive(Debug, Clone, Serialize, Deserialize)]@@ -439,6 +444,9 @@ pub(crate) fn ui_to_record(message: &UiMessage) -> (MessageRecord, Option<Stringif let Some(size) = attachment.size {block.insert("size".into(), json!(size));}+ if let Some(text) = &attachment.text {+ block.insert("text".into(), json!(text));+ }blocks.push(Value::Object(block));}}@@ -575,6 +583,10 @@ pub(crate) fn record_to_ui(record: MessageRecord) -> UiMessage {.and_then(|v| v.as_str()).map(str::to_string),size: block.get("size").and_then(|v| v.as_i64()),+ text: block+ .get("text")+ .and_then(|v| v.as_str())+ .map(str::to_string),})}).collect::<Vec<_>>();@@ -4785,6 +4797,7 @@ mod tests {reference: "attachments/abc123".into(),mime_type: Some("image/png".into()),size: Some(42),+ text: None,}]);append_message(&db, &session.id, &user, None).unwrap();diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.mdindex 0262e800a..e4fea71f2 100644--- a/docs/spec/03-runtime/02-agent-runtime.md+++ b/docs/spec/03-runtime/02-agent-runtime.md@@ -119,6 +119,11 @@ No host RPC or storage schema change is required.the durable user message. Only an image that is within the 10 MB inlinebound for a vision model is read into memory; larger images use streamedhashing/copying and the existing safe path fallback+ A `pi-desktop://session/<id>` link in the draft is resolved in the same step+ into a bounded excerpt attachment: the same project only, the current+ conversation dropped before any read, and the runtime quotes it to the model+ as one `<session_reference name="…" session="…">` block ahead of the user's+ own words7. snapshot the effective shell ID and dialect for the turn8. start pi turn with the resolved session configuration and effectivethinking level; HTTP 429 setup and stream failures use the runtime-owneddiff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.mdindex d43eee94c..f99dd2b43 100644--- a/docs/spec/03-runtime/04-data-storage.md+++ b/docs/spec/03-runtime/04-data-storage.md@@ -893,9 +893,10 @@ type Block =status: "ok" | "error" | "denied"; result?: unknown;completedAt?: string; durationMs?: number;toolUsage?: ToolTokenUsage }- | { type: "attachment"; kind: "image" | "file"; name: string;- ref: string /* attachments/<sha256> or absolute path */;- mimeType?: string; size?: number }+ | { type: "attachment"; kind: "image" | "file" | "session"; name: string;+ ref: string /* attachments/<sha256>, absolute path, or session id */;+ mimeType?: string; size?: number;+ text?: string /* bounded referenced-conversation excerpt */ }| { type: "hostedSearch"; status: "searching" | "completed" | "failed";rounds: Array<{ id: string;status: "searching" | "completed" | "failed";@@ -918,6 +919,13 @@ type Block =`scratch/<sessionId>/replayed/` when a path fallback is required. Imagesabove the inline bound are hashed and copied with streaming file operations;startup and history hydration must not load the whole image into memory.+- A `kind: "session"` block is a conversation reference: it stores the session+ id it names, the display title, and the bounded excerpt quoted to the model,+ so a later turn reads the same reference instead of re-reading the referenced+ conversation. The excerpt bound, the same-project rule, and the+ `<session_reference>` prompt block belong to the reference contract+ (`04-ux/08-component-spec.md` §20B); the host stores exactly what it is given+ and never reads the referenced session to build one.- Assistant thinking is stored only in `thinking` blocks inside the file. Thederived `text` column contains final answer text, so transcript search andanswer previews do not expose or mix reasoning.diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex e4c04e776..22aef527b 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -576,9 +576,10 @@ visually distinct from list content.in its overflow menu. Rename edits the local display name only; open folderreveals the project directory in the system file manager for the selectedproject row.-- Conversation overflow: pin/unpin, archive/restore, Create branch, delete.- Create branch is disabled while that conversation is running; success- activates the independent child session and focuses the composer. When+- Conversation overflow: pin/unpin, archive/restore, Create branch, Copy+ conversation link, delete. Create branch is disabled while that conversation+ is running; success activates the independent child session and focuses the+ composer. Copy conversation link is offered to every reader (§20B). Whendeveloper mode is on, the menu also offers Copy conversation ID (clipboard)and Open session path (the session scratch directory in the system filemanager).@@ -1424,6 +1425,10 @@ near-zero duration. A folded group keeps its rows mounted, `aria-hidden`, andsession path opens `<data_dir>/scratch/<sessionId>/` in the system filemanager, creating the directory if it does not exist yet. Both actionsappear only while developer mode is on.+- Copy conversation link writes the `pi-desktop://session/<id>` reference to+ the clipboard without developer mode. Pasting it into another conversation's+ Composer draft sends a bounded excerpt of that conversation with the turn,+ and the user message then shows it as a chip (§20B).- Selecting a conversation with a different project first activates thatproject's workspace. A running turn in the previously selected session isnot aborted.@@ -1728,8 +1733,12 @@ Single message render — either user (plaintext) or assistant (markdown streamichips matching the composer node (icon + ellipsized name; canonical path inthe tooltip and accessible name). Image attachments that are not alreadyinlined as `@path` chips render as bounded thumbnails (data URL from- `fs/readImageDataUrl`); unresolved loads keep the chip. Bare path tokens in- message text recognize Unicode letters and digits. In user-message prose,+ `fs/readImageDataUrl`); unresolved loads keep the chip. A referenced+ conversation (`kind: "session"`) renders as a chat-icon chip labeled with the+ shared reference label and the referenced title; the tooltip and accessible+ name come from the catalog, and activating it opens that conversation+ (§20B). Bare path tokens in message text recognize Unicode letters and+ digits. In user-message prose,these are candidates only: show a chip after the existing `fs/resolveRef`lookup confirms a real file. Pending, missing, or failed lookups preservethe exact original text, including `使用llama.cpp`. Explicit `@path` refs@@ -3309,6 +3318,12 @@ Anatomy:main selects image blocks or path fallbacks from the exact model capability.Reference-only drafts are sendable. Builtin/plugin dispatch still bypassesthe model-ready gate when no prompt text or file reference is sent.+- A `pi-desktop://session/<id>` link in the draft is the reference itself: no+ new trigger symbol joins `@` files and `/` commands, and the link stays+ visible plaintext while the draft is unsent. Immediately before dispatch,+ main resolves each link to another conversation in the same project into a+ bounded excerpt attachment (§20B). An unknown id, a self-reference, and a+ conversation in another project stay plaintext.- The Agent/Plan/Goal mode aliases can prefix a prompt in the same draft:`/agent-mode <prompt>`, `/plan-mode <prompt>`, and `/goal-mode <prompt>` applythe mode first, then send `<prompt>` plus any serialized references through@@ -4171,6 +4186,71 @@ TASKS (2) │ Nightly dependency check [Enabled] [Run now]`prefers-reduced-motion`, including the running dot's pulse.+## 20B. Conversation references++### 20B.1 Purpose++Carry another conversation into a turn without retyping it. The+`pi-desktop://session/<id>` link is the whole interaction: a reader copies it+from the conversation overflow menu and pastes it into a Composer draft (issue+#1324, option B). Copy conversation ID stays the developer-mode identifier.++### 20B.2 Anatomy++```text+Conversation overflow Composer draft (unsent)+┌─────────────────────────────┐ ┌──────────────────────────────────┐+│ Pin conversation │ │ continue from │+│ Create branch │ │ pi-desktop://session/ab12cd34 │+│ Copy conversation link │ └──────────────────────────────────┘+│ Delete conversation │+└─────────────────────────────┘ Sent user message+ ┌──────────────────────────────────┐+ │ continue from │+ │ pi-desktop://session/ab12cd34 │+ │ [💬 Conversation · Nightly check]│+ └──────────────────────────────────┘+```++### 20B.3 States++| State | Appearance |+|---|---|+| Reference attached | Chat-icon chip on the user message, named with the catalog's reference label and the referenced conversation's title |+| Reference skipped | Nothing is attached; the link stays plaintext in the message |+| 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 |+| Chip activated | The referenced conversation becomes the active session |++### 20B.4 Interaction++- Copy conversation link writes `pi-desktop://session/<sessionId>` from the+ conversation overflow menu. The durable id is the reference; Copy+ conversation ID still exposes the bare id in developer mode.+- Sending a turn whose draft holds the link attaches a bounded excerpt of the+ referenced conversation: the 40 newest messages, 8 KB per field, 16 KB for+ the whole excerpt, newest last, and the count of earlier messages the bound+ cut. At most four links per message are resolved.+- The excerpt is stored on the message's attachment and quoted to the model as+ one `<session_reference name="…" session="…">` block, so later turns read the+ same reference and re-sending a message that still contains the link+ re-resolves it from that conversation's current content.+- Activating the chip opens the referenced conversation; the reference is a+ link, not a copy of that transcript.+- The visible text is never rewritten: the link a reader typed stays in the+ message, and only the attached excerpt is additive.+- Boundary: only conversations of the same project are read, the current+ conversation is dropped before any read, and a link to another project, an+ unknown id, or a `remote:` identifier stays plaintext rather than becoming a+ reference. A paste cannot make the app read a transcript its reader could not+ open.+- The chip is a button with a catalog-built accessible name and a tooltip+ naming the conversation it opens; it is keyboard-activatable and leaves the+ surrounding selectable message text intact.+- `pi-desktop://` is not yet an operating-system protocol handler; opening a+ link from outside the app is a separate change (issue #1324, option A). This+ section covers the in-app reference.## 21. Acceptance criteria (all components)1. All components use semantic color tokens from [07-ui-design-system.md](07-ui-design-system.md) — no raw hexdiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 00272e30d..9531d61dc 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -1840,6 +1840,32 @@ identify the platform validation still needed.`pnpm test:e2e:composer-paste`; real desktop recording uses isolated data anda local model with a controlled response delay.+#### E2E-SESSION-reference-conversation-link: A pasted conversation link carries that conversation into the turn++- **Preconditions**: Isolated desktop profile; one project with conversations A+ and B, and a second project with conversation C; a configured model that+ answers from the context it is given.+- **Steps**: 1) In A's conversation overflow menu choose Copy conversation+ link and read the clipboard. 2) Open B, paste the link into the Composer+ draft, send it, and inspect the user message. 3) Ask a follow-up in B without+ repeating the link. 4) Paste C's link into B and send. 5) In A, send A's own+ link.+- **Expected**: The clipboard holds `pi-desktop://session/<A's id>`. B's user+ message keeps the link text visible and shows a chat-icon chip labelled with+ the catalog's reference label and A's title; activating the chip opens A. The+ answer uses A's content, and the follow-up still reads the same reference+ without the link being written again. C's link and A's own link attach+ nothing: the message keeps its plaintext and the model receives no excerpt+ from them, because the resolver drops a self-reference before any read and+ discards an excerpt whose conversation belongs to another project.+- **Specs linked**: `04-ux/08-component-spec.md` §20B,+ `03-runtime/04-data-storage.md`, `03-runtime/02-agent-runtime.md`+- **Acceptance criterion**: C — Conversation & stream+- **Milestone**: M2+- **Status**: Draft — the resolver and the chip are covered at source level by+ `apps/desktop/test/session-references.test.mjs` and+ `apps/desktop/test/session-reference-ui.test.mjs`+#### E2E-COMPOSER-input-history-recall- **Preconditions**: Isolated Electron test profile and the production Composerdiff --git a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md b/docs/zh-CN/spec/03-runtime/02-agent-runtime.mdindex e98492af2..9949c2b99 100644--- a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md+++ b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md@@ -96,6 +96,9 @@ pi 消费排队输入时保留渲染器提供的消息 id;即使补充输入6. 在 Electron main 的会话绑定路径边界上校验结构化附件,按 SHA-256 持久化图片字节,持久用户消息中只保留附件引用。只有处于视觉模型 10 MB 内联上限之内的图片才会被读进内存;更大的图片走流式哈希/复制以及既有的安全路径回退+ 草稿里的 `pi-desktop://session/<id>` 链接在同一步骤里解析成有界摘录附件:只限+ 同一项目,当前对话在任何读取之前就被跳过;运行时随后把它作为一个+ `<session_reference name="…" session="…">` 块排在用户自己的话之前引用给模型7. 为本回合快照有效的 shell ID 与方言8. 用解析出的会话配置和有效思考级别启动 pi 回合;HTTP 429 的建连与流式失败使用运行时自有的静默 10 次重试预算,其他瞬时的 transport/provider 失败则在diff --git a/docs/zh-CN/spec/03-runtime/04-data-storage.md b/docs/zh-CN/spec/03-runtime/04-data-storage.mdindex 80ae42971..109808c45 100644--- a/docs/zh-CN/spec/03-runtime/04-data-storage.md+++ b/docs/zh-CN/spec/03-runtime/04-data-storage.md@@ -709,8 +709,10 @@ type Block =status: "ok" | "error" | "denied"; result?: unknown;completedAt?: string; durationMs?: number;toolUsage?: ToolTokenUsage }- | { type: "attachment"; kind: "image" | "file"; name: string;- ref: string /* attachments/<sha256> or absolute path */ }+ | { type: "attachment"; kind: "image" | "file" | "session"; name: string;+ ref: string /* attachments/<sha256>、绝对路径或会话 id */;+ mimeType?: string; size?: number;+ text?: string /* 被引用对话的有界摘录 */ }| { type: "hostedSearch"; status: "searching" | "completed" | "failed";rounds: Array<{ id: string;status: "searching" | "completed" | "failed";@@ -724,6 +726,11 @@ type Block =- 工具结果存储**截断后**(16 个工具结果限制);满原始输出不是存储问题。+- `kind: "session"` 块是会话引用:它存储被引用的会话 id、显示标题,以及引用给模型的+ 有界摘录,因此后续轮次读到的是同一份引用,而不必重新读取被引用的对话。摘录边界、+ 同项目规则与 `<session_reference>` 提示块属于引用契约+ (`04-ux/08-component-spec.md` §20B);宿主只存它拿到的东西,不会为了拼出一条引用+ 去读被引用的会话。- 辅助思维仅存储在文件内的 `thinking` 块中。的派生的 `text` 列包含最终答案文本,因此转录搜索和答案预览不会暴露或混合推理。diff --git a/docs/zh-CN/spec/04-ux/08-component-spec.md b/docs/zh-CN/spec/04-ux/08-component-spec.mdindex 01e1cd469..ec1f3a3d5 100644--- a/docs/zh-CN/spec/04-ux/08-component-spec.md+++ b/docs/zh-CN/spec/04-ux/08-component-spec.md@@ -431,9 +431,11 @@ Collapsed (48px):- 项目溢出:切换、打开文件夹、重命名、pin/unpin、archive/restore、关闭保留选项卡。重命名只修改本地显示名称;打开文件夹在系统文件管理器中显示所选项目行的项目目录。-- 对话溢出:pin/unpin、archive/restore、创建分支、删除。+- 对话溢出:pin/unpin、archive/restore、创建分支、复制会话链接、删除。当该对话运行时,创建分支被禁用;成功- 激活独立的子会话并集中输入框。+ 激活独立的子会话并集中输入框。「复制会话链接」对所有读者可见(§20B);+ 开发者模式打开时,菜单还提供复制对话 ID(剪贴板)与打开会话路径+ (在系统文件管理器中打开会话临时目录)。- `Sessions` 工具栏将排序按钮放置在消息加新聊天之前控制。排序菜单和所有其他主体级侧边栏菜单仍然保留内容大小并在触发器或指针右侧打开 4px。他们的@@ -1003,6 +1005,9 @@ SESSIONS [msg+][↕]进入独立会话。子会话留在同一个项目或独立会话部分并变为活动状态;后来 transcript/configuration 发生了变化不影响来源。对于正在运行的源,该操作被禁用。+- 「复制会话链接」把 `pi-desktop://session/<id>` 引用写入剪贴板,不需要开发者模式。+ 把它粘贴进另一段对话的输入框草稿,该轮就会带上这段对话的有界摘录,用户消息随后+ 以芯片显示它(§20B)。- 首先选择与不同项目的对话会激活该对话项目的工作区。先前选择的会话中的运行回合是没有中止。@@ -1238,6 +1243,8 @@ row 而不是在转录本中添加树镶边。保留硬换行符(`white-space: pre-wrap`);仅应用 trailing/leading 输入框修剪,从不应用内部换行符崩溃。序列化的 `@path` 文件引用画成与输入框一致的叶子名芯片(图标 + 省略号文件名;规范路径放在工具提示和无障碍名称里)。未内联成 `@path` 芯片的图片附件渲染为有界缩略图(`fs/readImageDataUrl` 的 data URL);无法解析时保留芯片。消息正文里的裸路径 token 识别 Unicode 字母与数字。在用户消息正文中,它们只是候选:现有的 `fs/resolveRef` 查找确认是真实文件后才显示芯片。等待、未找到或失败的查找保留原文,包括 `使用llama.cpp`。显式 `@path` 引用和结构化附件保留现有芯片,不做猜测查询。每条消息最多检查 32 个唯一候选,可见行之间最多 4 个并发查找;其余候选保持纯文本。确认结果绑定到当前消息文本、工作区路径和会话;任一变化都会丢弃旧结果并取消排队的工作。之后新建的文件在消息重新挂载或作用域变化时再考虑,不轮询。非 ASCII 文件名仍受支持。绝对路径与 `~/` 整体匹配,工作区之外(以及一切家目录路径)保持纯文本,而不是渲染一个永远打不开的芯片——包含边界不变(D322)。点击芯片先经 `pi-desktop/fs/resolveRef` 补全引用——该通道搜索整个打开的项目,按项目组文件夹顺序、主文件夹优先(ADR 0263)——再按解析结果打开:项目文件在随应用打包的 `pi.file-manager` 工作面板视图中打开(该视图不可用时退回宿主 `file:` 选项卡),会话临时目录或附件文件在宿主 `file:` 选项卡中打开,主文件夹中的 `.html`/`.htm` 仍由侧边浏览器打开。交给该视图的地址跟随应答的文件夹:主文件夹中的文件用项目内相对路径传递,同一项目的同级文件夹中的文件用绝对路径传递,与会话临时目录和附件文件一致。已解析的图片缩略图按同样规则打开。什么都没匹配到的芯片不打开任何东西,而是自己报告出来;系统默认应用不再由这次点击触发。HTTP(S) URL 仍是内联文本链接;裸 URL 保留路径、查询和片段中成对的圆括号,正文包裹网址时多出的右括号不属于链接;紧跟 URL 右括号的句末标点也不属于链接,但 `(draft).html` 这样的后缀仍保留,在侧边浏览器打开;长 URL 在板内换行并保持逻辑开始对齐,而不是继承浏览器的居中按钮文本。+- 被引用的对话(`kind: "session"`)画成聊天图标芯片,标签是共享的引用标签加被引用+ 标题;工具提示与无障碍名称来自语言目录,激活它会打开那段对话(§20B)。- Assistant:透明表面,左对齐,Markdown 完全渲染内容宽度。该 Markdown 里的工作区文件路径可预览:行内代码、Markdown 链接与裸路径token(带已知扩展名)都像芯片一样,在打开项目的每个文件夹里先补全再打开(ADR 0263)——@@ -2290,6 +2297,10 @@ Live Voice 受现有开发者模式和开发构建门控约束,包含四种展按原始参考顺序恢复该快照而不是复制序列化的消息路径返回到文本区域。回复开始后停止不得恢复或复制已提交的草稿。+- 草稿里的 `pi-desktop://session/<id>` 链接本身就是引用:不在 `@` 文件和 `/` 命令+ 之外新增触发符号,草稿未发送时链接保持可见纯文本。派发之前,main 会把每个指向同一+ 项目内其他对话的链接解析成有界摘录附件(§20B)。不存在的 id、自引用与其他项目中的+ 对话保持纯文本。- 按 §11.7 选择表示后,文件粘贴需要至少一个 `File`。渲染器传输有界文件字节、名称和 MIME元数据到 Electron main 以及持久会话 ID。主要验证@@ -2911,6 +2922,61 @@ Sidebar footer Popover (360px max)- 动画仅使用颜色与箭头过渡,并在 `prefers-reduced-motion` 下关闭,包括运行中圆点的脉冲。+## 20B. 会话引用++### 20B.1 目的++把另一段对话带进本轮,而不必重新抄一遍。`pi-desktop://session/<id>` 链接本身就是+整个交互:读者从对话溢出菜单复制它,再粘贴进输入框草稿(issue #1324 的 B 方案)。+「复制对话 ID」仍是开发者模式下的身份标识。++### 20B.2 解剖++```text+对话溢出菜单 输入框草稿(未发送)+┌─────────────────────────────┐ ┌──────────────────────────────────┐+│ 固定对话 │ │ 接着做 │+│ 创建分支 │ │ pi-desktop://session/ab12cd34 │+│ 复制会话链接 │ └──────────────────────────────────┘+│ 删除对话 │+└─────────────────────────────┘ 已发送的用户消息+ ┌──────────────────────────────────┐+ │ 接着做 │+ │ pi-desktop://session/ab12cd34 │+ │ [💬 会话引用 · 夜间依赖检查] │+ └──────────────────────────────────┘+```++### 20B.3 状态++| 状态 | 外观 |+|---|---|+| 已附带引用 | 用户消息上的聊天图标芯片,标签为语言目录里的引用标签加被引用对话的标题 |+| 引用被跳过 | 不附带任何东西;链接在消息里保持纯文本 |+| 另一个项目 | 同样跳过:那段转写不是本轮的上下文 |+| 自引用 | 在任何读取之前就被丢弃,当前对话永远不会成为引用 |+| 被引用对话为空 | 解析器不附带任何东西,消息保留链接 |+| 激活芯片 | 被引用的对话成为活动会话 |++### 20B.4 交互++- 「复制会话链接」从对话溢出菜单写入 `pi-desktop://session/<sessionId>`。持久 id+ 就是引用本身;「复制对话 ID」在开发者模式下仍暴露裸 id。+- 发送带有该链接的草稿时,会附带被引用对话的有界摘录:最近 40 条消息、每个字段+ 8 KB、整段摘录 16 KB,最新在后,并说明被边界截掉的更早消息条数。每条消息最多+ 解析四个链接。+- 摘录存放在消息的附件上,并以一个 `<session_reference name="…" session="…">`+ 块引用给模型,因此后续轮次读到的仍是同一份引用,而重发仍含链接的消息会按该对话+ 当前内容重新解析。+- 激活芯片会打开被引用的对话;引用是链接,不是那段转写的副本。+- 可见文本从不被改写:读者输入的链接留在消息里,只有附带的摘录是新增的。+- 边界:只读取同一项目的对话,当前对话在任何读取之前就被丢弃,指向其他项目、不存+ 在的 id 或 `remote:` 标识的链接保持纯文本,不会变成引用。粘贴无法让应用读取读者+ 本来打不开的转写。+- 芯片是按钮,无障碍名称由语言目录生成,工具提示说明它会打开哪段对话;可键盘激活,+ 并保持周围可选中的消息文本不变。+- `pi-desktop://` 目前还不是操作系统协议处理器;从应用外打开链接是另一项改动+ (issue #1324 的 A 方案)。本节只覆盖应用内的引用。## 21. 验收标准(所有组件)1. 所有组件均使用 [07-ui-design-system.md](/zh-CN/spec/04-ux/07-ui-design-system) 中的语义颜色标记 — 无原始十六进制diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.mdindex 64fe26caa..7d5306cbf 100644--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md@@ -768,6 +768,27 @@ task-candidate E2E 从请求工作树运行,但使用主工作区已经准备- **覆盖**:`scripts/e2e/composer-submission.tsx`,由`pnpm test:e2e:composer-paste` 执行;真实桌面录屏使用隔离数据,以及响应时间受控的本地模型。+#### E2E-SESSION-reference-conversation-link:粘贴的会话链接把那段对话带进本轮++- **先决条件**:隔离的桌面配置;一个项目内有会话 A 与 B,另一个项目内有会话 C;+ 已配置一个会依据给定上下文作答的模型。+- **步骤**: 1) 在 A 的对话溢出菜单选「复制会话链接」,读取剪贴板。+ 2) 打开 B,把链接粘贴进输入框草稿并发送,检查用户消息。+ 3) 在 B 里追问一次,不再重复链接。 4) 把 C 的链接粘贴进 B 并发送。+ 5) 在 A 里发送 A 自己的链接。+- **预期**:剪贴板内容是 `pi-desktop://session/<A 的 id>`。B 的用户消息保留可见的链接+ 文本,并显示聊天图标芯片,标签为语言目录里的引用标签加 A 的标题;激活芯片会打开 A。+ 回答使用 A 的内容,追问仍然读到同一份引用,而无需再次写入链接。C 的链接与 A 自己的+ 链接什么都不附带:消息保持纯文本,模型收不到它们的任何摘录——解析器在任何读取之前+ 丢掉自引用,并丢弃属于其他项目的对话摘录。+- **关联规范**:`04-ux/08-component-spec.md` §20B、`03-runtime/04-data-storage.md`、+ `03-runtime/02-agent-runtime.md`+- **验收标准**:C — 对话与流+- **里程碑**:M2+- **状态**:Draft — 解析器与芯片已由源码级测试覆盖:+ `apps/desktop/test/session-references.test.mjs`、+ `apps/desktop/test/session-reference-ui.test.mjs`+### 对话顶部栏#### E2E-087:对话顶部栏在聊天路径上呈现diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.tsindex a511a7060..2e4713a5f 100644--- a/packages/agent-runtime/src/runtime.test.ts+++ b/packages/agent-runtime/src/runtime.test.ts@@ -3687,6 +3687,52 @@ describe("DesktopAgentRuntime session collaboration provenance", () => {await runtime.dispose();}});+ it("quotes a referenced conversation in the turn the model actually receives", async () => {+ const runtime = createRuntime();+ const agent = (runtime as any).agent;+ const handle = (runtime as any).handleAgentEvent.bind(runtime);+ const calls: Array<{ text: string; images: unknown[] }> = [];+ const respond = async (text: string, images: unknown[] = []) => {+ calls.push({ text, images: images ?? [] });+ await handle({ type: "agent_start" });+ const reply = assistantMessage({ content: [{ type: "text", text: "ok" }] });+ agent.state.messages = [{ role: "user", content: text, timestamp: 1 }, reply];+ await handle({ type: "message_start", message: reply });+ await handle({ type: "message_end", message: reply });+ await handle({ type: "turn_end" });+ await handle({ type: "agent_end", messages: [] });+ };+ agent.prompt = vi.fn(respond);+ agent.waitForIdle = vi.fn(async () => undefined);+ const excerpt = "user: ship the lockfile fix\nassistant: two advisories";+ try {+ await runtime.prompt(+ {+ text: "continue from the reference",+ attachments: [+ {+ path: "6f1d2c3b-4a59-4e7f-8a90-b1c2d3e4f506",+ name: "Nightly check",+ kind: "session",+ text: excerpt,+ },+ ],+ },+ "user-1",+ "turn-1",+ );+ expect(agent.prompt).toHaveBeenCalledOnce();+ const [turn] = calls;+ expect(turn?.text.startsWith("continue from the reference")).toBe(true);+ expect(turn?.text).toContain(+ '<session_reference name="Nightly check" session="6f1d2c3b-4a59-4e7f-8a90-b1c2d3e4f506">',+ );+ expect(turn?.text).toContain(excerpt);+ expect(turn?.images).toEqual([]);+ } finally {+ await runtime.dispose();+ }+ });});diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.tsindex 4b3a47556..8abdfb086 100644--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@ -266,9 +266,16 @@ import {export type { RuntimeProviderConfig } from "./provider-binding.js";-export type RuntimePromptAttachment = AgentPromptAttachment & {+export type RuntimePromptAttachment = Omit<AgentPromptAttachment, "kind"> & {+ /**+ * `session` is written by Electron main for a resolved+ * `pi-desktop://session/<id>` reference; the renderer never sends it.+ */+ kind: AgentPromptAttachment["kind"] | "session";/** Base64 payload is transient and only crosses the sidecar for this turn. */data?: string;+ /** Bounded excerpt of a referenced conversation (`kind: "session"`). */+ text?: string;};export type RuntimePrompt = {@@ -277,9 +284,24 @@ export type RuntimePrompt = {attachments?: RuntimePromptAttachment[];};+/**+ * The user's own words plus one quoted block per referenced conversation. The+ * visible prompt is never rewritten: references are additive, and the model+ * must receive this text — a reference accounted for by compaction but absent+ * from the provider request would be context the user never got.+ */+function promptText(input: RuntimePrompt): string {+ const references = (input.attachments ?? [])+ .map((attachment) => sessionReferenceBlock(attachment))+ .filter((block): block is string => block !== null);+ return references.length+ ? `${input.text}\n\n${references.join("\n\n")}`.trim()+ : input.text;+}+function promptContent(input: string | RuntimePrompt): UserMessage["content"] {if (typeof input === "string") return input;- const text = input.text;+ const text = promptText(input);const images = (input.attachments ?? []).filter((attachment) =>attachment.kind === "image" &&@@ -322,10 +344,32 @@ function runtimeAttachmentFromMessage(kind: attachment.kind,...(attachment.mimeType ? { mimeType: attachment.mimeType } : {}),...(attachment.size !== undefined ? { size: attachment.size } : {}),+ ...(attachment.text ? { text: attachment.text } : {}),...(data ? { data } : {}),};}+/** Attribute-safe text: a session title may contain quotes or angle brackets. */+function escapeAttribute(value: string): string {+ return value+ .replaceAll("&", "&")+ .replaceAll("<", "<")+ .replaceAll(">", ">")+ .replaceAll('"', """);+}++/**+ * A referenced conversation travels with the user's message as one delimited+ * block: it is quoted context, not the user's own words (a session link in the+ * draft produced it), so the model reads it as reference material.+ */+export function sessionReferenceBlock(attachment: RuntimePromptAttachment): string | null {+ const text = attachment.text?.trim();+ if (!text) return null;+ const title = escapeAttribute(attachment.name || attachment.path);+ return `<session_reference name="${title}" session="${escapeAttribute(attachment.path)}">\n${text}\n</session_reference>`;+}+// pi-ai's adapter retry is disabled here so setup and mid-stream 429s share// one runtime-owned budget instead of multiplying nested retry loops.const PROVIDER_REQUEST_MAX_RETRIES = 0;@@ -8260,7 +8304,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when theif (typeof modelInput === "string") {await this.agent.prompt(modelInput);} else {- await this.agent.prompt(modelInput.text, promptImages(modelInput));+ await this.agent.prompt(promptText(modelInput), promptImages(modelInput));}await this.waitForIdleAndSteering();void this.extensionRunner?.emit("agent_settled", { type: "agent_settled" });diff --git a/packages/agent-runtime/src/session-reference.test.ts b/packages/agent-runtime/src/session-reference.test.tsnew file mode 100644index 000000000..f7395d6b1--- /dev/null+++ b/packages/agent-runtime/src/session-reference.test.ts@@ -0,0 +1,34 @@+import { describe, expect, it } from "vitest";+import { sessionReferenceBlock } from "./runtime.js";++describe("session reference blocks", () => {+ it("quotes a referenced conversation with its identity", () => {+ const block = sessionReferenceBlock({+ path: "6f1d2c3b-4a59-4e7f-8a90-b1c2d3e4f506",+ name: "Nightly dependency check",+ kind: "session",+ text: "user: check the lockfile\nassistant: two advisories",+ });+ expect(block).toContain('name="Nightly dependency check"');+ expect(block).toContain('session="6f1d2c3b-4a59-4e7f-8a90-b1c2d3e4f506"');+ expect(block).toContain("user: check the lockfile");+ expect(block?.endsWith("</session_reference>")).toBe(true);+ });++ it("escapes a title that would break the block", () => {+ const block = sessionReferenceBlock({+ path: "abc",+ name: 'a "quoted" <title>',+ kind: "session",+ text: "user: hi",+ });+ expect(block).toContain('name="a "quoted" <title>"');+ expect(block?.startsWith('<session_reference name="')).toBe(true);+ });++ it("ignores every other attachment kind and empty text", () => {+ expect(sessionReferenceBlock({ path: "a.ts", name: "a.ts", kind: "file" })).toBeNull();+ expect(sessionReferenceBlock({ path: "pic.png", name: "pic.png", kind: "image", data: "x" })).toBeNull();+ expect(sessionReferenceBlock({ path: "abc", name: "Empty", kind: "session", text: " " })).toBeNull();+ });+});diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.tsindex 4ac094496..f07812de3 100644--- a/packages/i18n/src/locales/de/index.ts+++ b/packages/i18n/src/locales/de/index.ts@@ -186,6 +186,7 @@ export const de = {batchDelete: "{{count}} Sitzungen löschen",batchDeleteConfirm: "{{count}} Sitzungen löschen?","copyConversationId": "Gesprächs-ID kopieren",+ "copySessionLink": "Link zur Unterhaltung kopieren","openSessionPath": "Sitzungspfad öffnen","timeGroupYesterday": "Gestern","timeGroupThisWeek": "Vorherige 7 Tage",@@ -321,6 +322,8 @@ export const de = {"conversationMenu": "Gesprächsaktionen","selectMessageText": "Nachrichtentext auswählen","copyConversation": "Gespräch kopieren",+ "sessionReference": "Unterhaltung",+ "sessionReferenceOpen": "Unterhaltung {{title}} öffnen","selectConversationText": "Gesprächstext auswählen","scrollToTop": "Nach oben scrollen","speakerYou": "Du",diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex 3fbb662d0..7433d72ba 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -193,6 +193,7 @@ export const en = {batchDelete: "Delete {{count}} sessions",batchDeleteConfirm: "Delete {{count}} sessions?",copyConversationId: "Copy conversation ID",+ copySessionLink: "Copy conversation link",openSessionPath: "Open session path",timeGroupYesterday: "Yesterday",timeGroupThisWeek: "Previous 7 days",@@ -333,6 +334,8 @@ export const en = {conversationMenu: "Conversation actions",selectMessageText: "Select message text",copyConversation: "Copy conversation",+ sessionReference: "Conversation",+ sessionReferenceOpen: "Open conversation {{title}}",selectConversationText: "Select conversation text",scrollToTop: "Scroll to top",speakerYou: "You",diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.tsindex ca0c3a2fa..373028a0b 100644--- a/packages/i18n/src/locales/es/index.ts+++ b/packages/i18n/src/locales/es/index.ts@@ -186,6 +186,7 @@ export const es = {batchDelete: "Eliminar {{count}} sesiones",batchDeleteConfirm: "¿Eliminar {{count}} sesiones?","copyConversationId": "Copiar ID de conversación",+ "copySessionLink": "Copiar enlace de la conversación","openSessionPath": "Abrir ruta de sesión","timeGroupYesterday": "Ayer","timeGroupThisWeek": "Anterior 7 días",@@ -321,6 +322,8 @@ export const es = {"conversationMenu": "Acciones de la conversación","selectMessageText": "Seleccionar el texto del mensaje","copyConversation": "Copiar la conversación",+ "sessionReference": "Conversación",+ "sessionReferenceOpen": "Abrir la conversación {{title}}","selectConversationText": "Seleccionar el texto de la conversación","scrollToTop": "Ir al principio","speakerYou": "Tú",diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.tsindex 1c6a32753..bd88dbf4d 100644--- a/packages/i18n/src/locales/fr/index.ts+++ b/packages/i18n/src/locales/fr/index.ts@@ -186,6 +186,7 @@ export const fr = {batchDelete: "Supprimer {{count}} sessions",batchDeleteConfirm: "Supprimer {{count}} sessions ?","copyConversationId": "Copier l'ID de conversation",+ "copySessionLink": "Copier le lien de la conversation","openSessionPath": "Ouvrir le chemin de la session","timeGroupYesterday": "Hier","timeGroupThisWeek": "7 jours précédents",@@ -321,6 +322,8 @@ export const fr = {"conversationMenu": "Actions de la conversation","selectMessageText": "Sélectionner le texte du message","copyConversation": "Copier la conversation",+ "sessionReference": "Conversation",+ "sessionReferenceOpen": "Ouvrir la conversation {{title}}","selectConversationText": "Sélectionner le texte de la conversation","scrollToTop": "Aller en haut","speakerYou": "Vous",diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.tsindex f2a38bcee..a17be67ea 100644--- a/packages/i18n/src/locales/ko/index.ts+++ b/packages/i18n/src/locales/ko/index.ts@@ -195,6 +195,7 @@ export const ko = {batchDelete: "{{count}}개 세션 삭제",batchDeleteConfirm: "{{count}}개 세션을 삭제하시겠습니까?",copyConversationId: "대화 ID 복사",+ copySessionLink: "대화 링크 복사",openSessionPath: "세션 경로 열기",timeGroupYesterday: "어제",timeGroupThisWeek: "최근 7일",@@ -333,6 +334,8 @@ export const ko = {conversationMenu: "대화 작업",selectMessageText: "메시지 텍스트 선택",copyConversation: "대화 복사",+ sessionReference: "대화 참조",+ sessionReferenceOpen: "대화 {{title}} 열기",selectConversationText: "대화 텍스트 선택",scrollToTop: "맨 위로 이동",speakerYou: "나",diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.tsindex 1a3e60627..2577ddc8e 100644--- a/packages/i18n/src/locales/pt-BR/index.ts+++ b/packages/i18n/src/locales/pt-BR/index.ts@@ -185,6 +185,7 @@ export const ptBR = {batchDelete: "Excluir {{count}} sessões",batchDeleteConfirm: "Excluir {{count}} sessões?",copyConversationId: "Copiar ID da conversa",+ copySessionLink: "Copiar link da conversa",openSessionPath: "Abrir caminho da sessão",timeGroupYesterday: "Ontem",timeGroupThisWeek: "Últimos 7 dias",@@ -319,6 +320,8 @@ export const ptBR = {conversationMenu: "Ações da conversa",selectMessageText: "Selecionar texto da mensagem",copyConversation: "Copiar conversa",+ sessionReference: "Conversa",+ sessionReferenceOpen: "Abrir a conversa {{title}}",selectConversationText: "Selecionar texto da conversa",scrollToTop: "Rolar para o topo",speakerYou: "Você",diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.tsindex bbca80d00..c38169825 100644--- a/packages/i18n/src/locales/tr/index.ts+++ b/packages/i18n/src/locales/tr/index.ts@@ -195,6 +195,7 @@ export const tr = {batchDelete: "{{count}} oturumu sil",batchDeleteConfirm: "{{count}} oturum silinsin mi?",copyConversationId: "Konuşma kimliğini kopyala",+ copySessionLink: "Konuşma bağlantısını kopyala",openSessionPath: "Oturum yolunu aç",timeGroupYesterday: "Dün",timeGroupThisWeek: "Önceki 7 gün",@@ -333,6 +334,8 @@ export const tr = {conversationMenu: "Konuşma işlemleri",selectMessageText: "Mesaj metnini seç",copyConversation: "Konuşmayı kopyala",+ sessionReference: "Konuşma",+ sessionReferenceOpen: "{{title}} konuşmasını aç",selectConversationText: "Konuşma metnini seç",scrollToTop: "Başa kaydır",speakerYou: "Sen",diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.tsindex 8bdff779b..65d86e3e7 100644--- a/packages/i18n/src/locales/zh-CN/index.ts+++ b/packages/i18n/src/locales/zh-CN/index.ts@@ -188,6 +188,7 @@ export const zhCN = {batchDelete: "删除 {{count}} 个会话",batchDeleteConfirm: "确认删除 {{count}} 个会话?",copyConversationId: "复制对话 ID",+ copySessionLink: "复制会话链接",openSessionPath: "打开会话路径",timeGroupYesterday: "昨天",timeGroupThisWeek: "近 7 天",@@ -325,6 +326,8 @@ export const zhCN = {conversationMenu: "对话操作",selectMessageText: "选中消息文本",copyConversation: "复制整个对话",+ sessionReference: "会话引用",+ sessionReferenceOpen: "打开会话 {{title}}",selectConversationText: "选中对话文本",scrollToTop: "滚动到顶部",speakerYou: "你",diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.tsindex 7d4fa5fa4..3c711d3f5 100644--- a/packages/i18n/src/locales/zh-TW/index.ts+++ b/packages/i18n/src/locales/zh-TW/index.ts@@ -188,6 +188,7 @@ export const zhTW = {batchDelete: "刪除 {{count}} 個對話",batchDeleteConfirm: "確認刪除 {{count}} 個對話?",copyConversationId: "複製對話 ID",+ copySessionLink: "複製對話連結",openSessionPath: "開啟會話路徑",timeGroupYesterday: "昨天",timeGroupThisWeek: "近 7 天",@@ -325,6 +326,8 @@ export const zhTW = {conversationMenu: "對話操作",selectMessageText: "選取訊息文字",copyConversation: "複製整段對話",+ sessionReference: "對話引用",+ sessionReferenceOpen: "開啟對話 {{title}}",selectConversationText: "選取對話文字",scrollToTop: "捲動到頂端",speakerYou: "你",diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.tsindex d4406e7e7..6f02a6b8f 100644--- a/packages/shared/src/index.ts+++ b/packages/shared/src/index.ts@@ -8,6 +8,7 @@ export * from "./transcript-truncation.js";export * from "./keyboard-shortcuts.js";export * from "./changelog.js";export * from "./composer-trigger.js";+export * from "./session-link.js";export * from "./fuzzy.js";export * from "./mcp-import.js";export * from "./mcp-catalog.js";diff --git a/packages/shared/src/session-link.test.ts b/packages/shared/src/session-link.test.tsnew file mode 100644index 000000000..848da9708--- /dev/null+++ b/packages/shared/src/session-link.test.ts@@ -0,0 +1,46 @@+import { describe, expect, it } from "vitest";+import {+ formatSessionLink,+ isSessionLinkToken,+ MAX_SESSION_LINKS_PER_MESSAGE,+ parseSessionLinks,+} from "./session-link.js";++describe("session links", () => {+ it("round-trips the link a session row copies", () => {+ const id = "6f1d2c3b-4a59-4e7f-8a90-b1c2d3e4f506";+ const link = formatSessionLink(id);+ expect(link).toBe(`pi-desktop://session/${id}`);+ expect(parseSessionLinks(`please look at ${link} first`)).toEqual([id]);+ });++ it("keeps first-mention order and drops duplicates", () => {+ const text = [+ formatSessionLink("aaa"),+ formatSessionLink("bbb"),+ formatSessionLink("aaa"),+ ].join(" and ");+ expect(parseSessionLinks(text)).toEqual(["aaa", "bbb"]);+ });++ it("stops at the message bound", () => {+ const text = Array.from({ length: MAX_SESSION_LINKS_PER_MESSAGE + 3 }, (_, index) =>+ formatSessionLink(`session-${index}`),+ ).join(" ");+ expect(parseSessionLinks(text)).toHaveLength(MAX_SESSION_LINKS_PER_MESSAGE);+ });++ it("ignores prose, other schemes and remote ids", () => {+ expect(parseSessionLinks("")).toEqual([]);+ expect(parseSessionLinks("no links here")).toEqual([]);+ // A remote session id carries a colon, so it never parses as a local link.+ expect(parseSessionLinks("pi-desktop://session/remote:abc")).toEqual([]);+ expect(parseSessionLinks("https://example.com/session/abc")).toEqual([]);+ expect(parseSessionLinks("pi-desktop://session/")).toEqual([]);+ });++ it("recognizes one token without scanning prose", () => {+ expect(isSessionLinkToken(formatSessionLink("abc"))).toBe(true);+ expect(isSessionLinkToken("@src/index.ts")).toBe(false);+ });+});diff --git a/packages/shared/src/session-link.ts b/packages/shared/src/session-link.tsnew file mode 100644index 000000000..48f8c361b--- /dev/null+++ b/packages/shared/src/session-link.ts@@ -0,0 +1,54 @@+/**+ * Session links (`pi-desktop://session/<id>`): the one way a conversation is+ * referenced from another one.+ *+ * The link is plain text the user pastes into a Composer draft (or copies from+ * the session row), so referencing a conversation adds no new Composer trigger+ * symbol: `@` stays files and `/` stays commands (see `composer-trigger.ts`).+ * Electron main turns the tokens it finds in a prompt into bounded session+ * references before the turn is dispatched; the renderer only formats and+ * recognizes them.+ */++/** Custom scheme reserved for PI-Desktop links (deep link registration is A). */+export const SESSION_LINK_SCHEME = "pi-desktop";+/** Path segment that marks a session link. */+export const SESSION_LINK_HOST = "session";+/** References one message may carry; the rest stay plain text in the draft. */+export const MAX_SESSION_LINKS_PER_MESSAGE = 4;+/** Session ids are UUIDs; remote ids use `remote:` and never match. */+const SESSION_LINK_ID = /^[A-Za-z0-9_-]{1,64}$/;+/**+ * The id must end the token: a trailing `:` or `/` means this is a remote id+ * (`remote:…`) or a deeper path, so nothing is referenced at all.+ */+const SESSION_LINK_PATTERN =+ /pi-desktop:\/\/session\/([A-Za-z0-9_-]{1,64})(?![A-Za-z0-9_:/-])/g;++/** The link a session row copies and a Composer draft accepts. */+export function formatSessionLink(sessionId: string): string {+ return `${SESSION_LINK_SCHEME}://${SESSION_LINK_HOST}/${sessionId}`;+}++/**+ * Every distinct session a draft references, in first-mention order. A trailing+ * `)` or `.` a sentence added is not part of the id: the id character class+ * already stops at those.+ */+export function parseSessionLinks(text: string): string[] {+ if (!text?.includes(`${SESSION_LINK_SCHEME}://`)) return [];+ const found: string[] = [];+ for (const match of text.matchAll(SESSION_LINK_PATTERN)) {+ const id = match[1];+ if (!SESSION_LINK_ID.test(id)) continue;+ if (found.includes(id)) continue;+ found.push(id);+ if (found.length >= MAX_SESSION_LINKS_PER_MESSAGE) break;+ }+ return found;+}++/** Whether one token is a session link, used by renderer mention parsing. */+export function isSessionLinkToken(token: string): boolean {+ return parseSessionLinks(token).length > 0;+}diff --git a/packages/shared/src/types/messages.ts b/packages/shared/src/types/messages.tsindex 361a476c9..a7b1a88a0 100644--- a/packages/shared/src/types/messages.ts+++ b/packages/shared/src/types/messages.ts@@ -48,16 +48,29 @@ export type UsageOperation = Omit<MessageUsage, "operations" | "aggregation"> &export { addUsage, withUsageIdentity } from "../message-usage.js";export type MessageAttachment = {- kind: "image" | "file";+ kind: "image" | "file" | "session";name: string;- /** Workspace-relative path or session-scratch absolute path. */+ /** Workspace-relative path, session-scratch absolute path, or a session id. */ref: string;mimeType?: string;size?: number;+ /**+ * Bounded excerpt of a referenced conversation, written by Electron main when+ * the prompt carries a `pi-desktop://session/<id>` link. The model reads it+ * with the user's message; other attachment kinds never carry it.+ */+ text?: string;/** Sidecar-only hydrated image data; never persisted or sent by the host. */data?: string;};+/** Whether an attachment is a renderer-resolvable file or image reference. */+export function isRenderableAttachment(+ attachment: MessageAttachment,+): attachment is MessageAttachment & { kind: "image" | "file" } {+ return attachment.kind !== "session";+}+/** Estimated context footprint for one tool call and its returned result. */export type ToolTokenUsage = {argumentTokens: number;