Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): 引用远程会话的深链冻结归属设备,内容注入不再依赖发送时刻内存状态 (#274)

Chris Zhang76b0532330b6
diff --git a/apps/desktop/src/main/__tests__/agentInputQueue.test.ts b/apps/desktop/src/main/__tests__/agentInputQueue.test.ts
index 4f96fe0596..23d388150f 100644
--- a/apps/desktop/src/main/__tests__/agentInputQueue.test.ts
+++ b/apps/desktop/src/main/__tests__/agentInputQueue.test.ts
@@ -320,6 +320,56 @@ describe('agentInputQueue', () => {
]);
});
+ // 远程会话引用注入失败的回归:深链冻结的 `?device=` 必须在实时查表 miss
+ // (被控端离线 / relay 重连窗口注册表被 clear)时仍能把引用判定为远程。
+ it('binds the device frozen into the link even when the live lookup misses', () => {
+ expect(
+ reconcileSessionRefsForText(
+ '看这个 cindy://session/remote-1?device=dev-studio',
+ undefined,
+ () => undefined,
+ ),
+ ).toEqual([{ sessionId: 'remote-1', deviceId: 'dev-studio' }]);
+ });
+
+ it('prefers the frozen link device over live lookup and previous hints', () => {
+ expect(
+ reconcileSessionRefsForText(
+ 'cindy://session/remote-1?message=client-1&device=dev-frozen.',
+ [{ sessionId: 'remote-1', deviceId: 'dev-hint' }],
+ () => 'dev-live',
+ ),
+ ).toEqual([
+ { sessionId: 'remote-1', messageClientId: 'client-1', deviceId: 'dev-frozen' },
+ ]);
+ });
+
+ it('falls back to live lookup then previous hints for links without a device parameter', () => {
+ expect(
+ reconcileSessionRefsForText('cindy://session/remote-1', undefined, () => 'dev-live'),
+ ).toEqual([{ sessionId: 'remote-1', deviceId: 'dev-live' }]);
+ expect(
+ reconcileSessionRefsForText(
+ 'cindy://session/remote-1',
+ [{ sessionId: 'remote-1', deviceId: 'dev-hint' }],
+ () => undefined,
+ ),
+ ).toEqual([{ sessionId: 'remote-1', deviceId: 'dev-hint' }]);
+ });
+
+ it('treats an empty or malformed device parameter as absent', () => {
+ expect(
+ reconcileSessionRefsForText('cindy://session/remote-1?device=', undefined, () => undefined),
+ ).toEqual([{ sessionId: 'remote-1' }]);
+ expect(
+ reconcileSessionRefsForText(
+ 'cindy://session/remote-1?device=%ZZ&message=client-1',
+ undefined,
+ () => undefined,
+ ),
+ ).toEqual([{ sessionId: 'remote-1', messageClientId: 'client-1' }]);
+ });
+
it('projects encoded quote markers for Agent use without changing queue or persistence wire', () => {
const entry = queuedMessage(undefined);
const text = '> <!-- cindy-composer-quote -->\n> selected\n\nreply';
diff --git a/apps/desktop/src/main/__tests__/deepLink.test.ts b/apps/desktop/src/main/__tests__/deepLink.test.ts
index 2b3b413970..45bec117da 100644
--- a/apps/desktop/src/main/__tests__/deepLink.test.ts
+++ b/apps/desktop/src/main/__tests__/deepLink.test.ts
@@ -126,6 +126,22 @@ describe('parseDeepLink', () => {
});
});
+ it('tolerates the device-frozen link format when routing a click', () => {
+ // 远程会话深链带 `?device=`(renderer 生成);main 端点击路由按 sessionId
+ // 导航即可,未知参数不拖累 session / message 解析。
+ expect(parseDeepLink(buildSessionDeepLink('abc-123', { deviceId: 'dev-1' }))).toEqual({
+ type: 'session',
+ id: 'abc-123',
+ });
+ expect(
+ parseDeepLink(buildSessionMessageDeepLink('abc-123', 'm1', { deviceId: 'dev-1' })),
+ ).toEqual({
+ type: 'session',
+ id: 'abc-123',
+ messageClientId: 'm1',
+ });
+ });
+
it('ignores empty or malformed message anchor but keeps session id', () => {
expect(parseDeepLink('xdt-maker://session/abc-123?message=')).toEqual({
type: 'session',
diff --git a/apps/desktop/src/main/deepLink.ts b/apps/desktop/src/main/deepLink.ts
index c76229cd31..a5e7d968d4 100644
--- a/apps/desktop/src/main/deepLink.ts
+++ b/apps/desktop/src/main/deepLink.ts
@@ -159,13 +159,22 @@ function parseSessionMessageParam(rawValue: string): string | null {
* 注意:'new-session' 不提供 builder——它只由 --open-folder argv 产生,不进入
* "可复制 / 可粘贴"的 URL 域,避免和现有 project deep link 在 URL 域语义混淆。
*/
-export function buildSessionDeepLink(sessionId: string): string {
- return `${URL_PREFIX}session/${encodeURIComponent(sessionId)}`;
+export function buildSessionDeepLink(
+ sessionId: string,
+ opts?: { deviceId?: string | null },
+): string {
+ const device = opts?.deviceId ? `?device=${encodeURIComponent(opts.deviceId)}` : '';
+ return `${URL_PREFIX}session/${encodeURIComponent(sessionId)}${device}`;
}
/** 带消息锚点(`?message=<clientId>`)的会话深链,与 renderer 侧实现等价镜像。 */
-export function buildSessionMessageDeepLink(sessionId: string, messageClientId: string): string {
- return `${buildSessionDeepLink(sessionId)}?message=${encodeURIComponent(messageClientId)}`;
+export function buildSessionMessageDeepLink(
+ sessionId: string,
+ messageClientId: string,
+ opts?: { deviceId?: string | null },
+): string {
+ const device = opts?.deviceId ? `&device=${encodeURIComponent(opts.deviceId)}` : '';
+ return `${URL_PREFIX}session/${encodeURIComponent(sessionId)}?message=${encodeURIComponent(messageClientId)}${device}`;
}
/**
diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.ts
index 5ce53a72e9..e586e0afb7 100644
--- a/apps/desktop/src/main/device-link/index.ts
+++ b/apps/desktop/src/main/device-link/index.ts
@@ -662,6 +662,15 @@ export function closeRemoteLink(deviceId: string): void {
client?.closeLink(deviceId, 'user');
}
+/**
+ * 本机在 device-link 网络中的设备 id(relay ack 下发);未连接 / 未 ack 时 null。
+ * 供会话引用解析等消费方识别「指向本机自己的 deviceId」——深链是可复制的字符串,
+ * 控制端生成的 `?device=` 链接可能被带回归属设备本机粘贴发送。
+ */
+export function getSelfDeviceId(): string | null {
+ return client?.getSelfDeviceId() ?? null;
+}
+
/** 控制端:对目标设备远程 invoke 一个 allowlist 内的 channel。
* 被控端自身持有执行预算的 channel(desktop-cmd:run)按协议契约放宽隧道超时,
* 避免与被控端执行超时对撞(见 INVOKE_TIMEOUT_OVERRIDES_MS)。 */
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionReferenceResolver.local.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionReferenceResolver.local.test.ts
index 41be2a5e15..75828be3c5 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionReferenceResolver.local.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionReferenceResolver.local.test.ts
@@ -6,7 +6,11 @@ import { messages, sessions } from '../../localDb/schema.js';
const state = vi.hoisted(() => ({ db: null as ReturnType<typeof drizzle> | null }));
vi.mock('../../localDb/client/current.js', () => ({ getDbClient: () => ({ drizzle: state.db }) }));
-vi.mock('../../device-link/index.js', () => ({ remoteInvoke: vi.fn() }));
+const remoteInvoke = vi.hoisted(() => vi.fn());
+vi.mock('../../device-link/index.js', () => ({
+ remoteInvoke,
+ getSelfDeviceId: () => 'self-device',
+}));
import { resolveSessionReferences } from '../sessionReferenceResolver.js';
@@ -85,4 +89,17 @@ describe('sessionReferenceResolver local visibility', () => {
const [context] = await resolveSessionReferences([{ sessionId: 'local-session' }]);
expect(context.messages).toEqual([{ role: 'user', content: 'ssh history', createdAt: 101 }]);
});
+
+ // 深链是可复制的字符串:控制端生成的 `?device=` 链接被带回归属设备本机
+ // 粘贴发送时,ref.deviceId 指向本机自己——必须按本地会话解析,不得对
+ // 自己发起 device-link 隧道。
+ it('resolves refs pointing at the own device locally instead of tunneling', async () => {
+ insertMessage(sqlite, { id: 'own', role: 'user', content: 'own history', createdAt: 101 });
+ const [context] = await resolveSessionReferences([
+ { sessionId: 'local-session', deviceId: 'self-device' },
+ ]);
+ expect(context.messages).toEqual([{ role: 'user', content: 'own history', createdAt: 101 }]);
+ expect(context.source).toBe('local');
+ expect(remoteInvoke).not.toHaveBeenCalled();
+ });
});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionReferenceResolver.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionReferenceResolver.test.ts
index 926f4a734b..a670fe80b9 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionReferenceResolver.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionReferenceResolver.test.ts
@@ -3,7 +3,10 @@ import { DL_HISTORY_MESSAGES_CHANNEL } from '@cindy/device-link';
import { serializeSessionReferencePayload } from '../../../shared/agentInputQueue.js';
const remoteInvoke = vi.hoisted(() => vi.fn());
-vi.mock('../../device-link/index.js', () => ({ remoteInvoke }));
+vi.mock('../../device-link/index.js', () => ({
+ remoteInvoke,
+ getSelfDeviceId: () => 'self-device',
+}));
import {
estimateReferenceTokens,
diff --git a/apps/desktop/src/main/maker-ipc/sessionReferenceResolver.ts b/apps/desktop/src/main/maker-ipc/sessionReferenceResolver.ts
index d2214697ad..b60b083e69 100644
--- a/apps/desktop/src/main/maker-ipc/sessionReferenceResolver.ts
+++ b/apps/desktop/src/main/maker-ipc/sessionReferenceResolver.ts
@@ -6,7 +6,7 @@
*/
import { and, asc, desc, eq, gt, inArray, isNull, lt, or, sql, type SQL } from 'drizzle-orm';
import { DL_HISTORY_MESSAGES_CHANNEL } from '@cindy/device-link';
-import { remoteInvoke as invokeRemote } from '../device-link/index.js';
+import { getSelfDeviceId, remoteInvoke as invokeRemote } from '../device-link/index.js';
import { getDbClient } from '../localDb/client/current.js';
import { messages, sessions } from '../localDb/schema.js';
import { messageToCamel } from '../localDb/mapper.js';
@@ -691,8 +691,14 @@ export async function resolveSessionReferences(
const refsLeft = refs.length - index;
const messageLimit = Math.max(1, Math.floor(remainingMessages / refsLeft));
const tokenBudget = Math.max(1, Math.floor(remainingTokens / refsLeft));
- const resolved = ref.deviceId
- ? await resolveRemote(ref, messageLimit, tokenBudget)
+ // 深链是可复制的字符串:控制端生成的 `?device=` 链接可能被带回归属设备
+ // 本机粘贴发送,此时 deviceId 指向本机自己——按本地会话解析,不能对自己
+ // 发起 device-link 隧道(本机不是自己的控制端,必然失败)。
+ const remoteDeviceId = ref.deviceId && ref.deviceId !== getSelfDeviceId()
+ ? ref.deviceId
+ : undefined;
+ const resolved = remoteDeviceId
+ ? await resolveRemote({ ...ref, deviceId: remoteDeviceId }, messageLimit, tokenBudget)
: await resolveLocal(ref, messageLimit, tokenBudget);
contexts.push(resolved.context);
remainingMessages -= resolved.context.messageCount;
diff --git a/apps/desktop/src/renderer/__tests__/sessionDeepLink.test.ts b/apps/desktop/src/renderer/__tests__/sessionDeepLink.test.ts
index 0b37ef6076..383b6d2aca 100644
--- a/apps/desktop/src/renderer/__tests__/sessionDeepLink.test.ts
+++ b/apps/desktop/src/renderer/__tests__/sessionDeepLink.test.ts
@@ -7,6 +7,7 @@ import {
parseProjectDeepLinkHref,
parseSessionDeepLinkHref,
PROJECT_DEEP_LINK_RE_SOURCE,
+ SESSION_DEEP_LINK_RE_SOURCE,
} from '../lib/deepLink';
describe('buildProjectDeepLink(严格编码,review P2)', () => {
@@ -29,6 +30,7 @@ describe('parseSessionDeepLinkHref', () => {
expect(parseSessionDeepLinkHref('xdt-maker://session/abc-123')).toEqual({
sessionId: 'abc-123',
messageClientId: null,
+ deviceId: null,
});
});
@@ -36,10 +38,12 @@ describe('parseSessionDeepLinkHref', () => {
expect(parseSessionDeepLinkHref(buildSessionDeepLink('id with space'))).toEqual({
sessionId: 'id with space',
messageClientId: null,
+ deviceId: null,
});
expect(parseSessionDeepLinkHref(buildSessionMessageDeepLink('abc', 'client/9'))).toEqual({
sessionId: 'abc',
messageClientId: 'client/9',
+ deviceId: null,
});
});
@@ -47,14 +51,17 @@ describe('parseSessionDeepLinkHref', () => {
expect(parseSessionDeepLinkHref('xdt-maker://session/abc?message=')).toEqual({
sessionId: 'abc',
messageClientId: null,
+ deviceId: null,
});
expect(parseSessionDeepLinkHref('xdt-maker://session/abc?message=%ZZ')).toEqual({
sessionId: 'abc',
messageClientId: null,
+ deviceId: null,
});
expect(parseSessionDeepLinkHref('xdt-maker://session/abc?foo=1&message=m1')).toEqual({
sessionId: 'abc',
messageClientId: 'm1',
+ deviceId: null,
});
});
@@ -62,6 +69,7 @@ describe('parseSessionDeepLinkHref', () => {
expect(parseSessionDeepLinkHref('xdt-maker://session/abc/#frag')).toEqual({
sessionId: 'abc',
messageClientId: null,
+ deviceId: null,
});
});
@@ -73,6 +81,53 @@ describe('parseSessionDeepLinkHref', () => {
});
});
+// 远程会话深链冻结归属设备(`?device=`):生成/解析对称,旧格式回退 null。
+describe('session deep link device parameter', () => {
+ it('freezes deviceId into the link and roundtrips through the parser', () => {
+ const href = buildSessionDeepLink('abc-123', { deviceId: 'dev-mac~1' });
+ expect(href).toBe('cindy://session/abc-123?device=dev-mac~1');
+ expect(parseSessionDeepLinkHref(href)).toEqual({
+ sessionId: 'abc-123',
+ messageClientId: null,
+ deviceId: 'dev-mac~1',
+ });
+ });
+
+ it('combines message anchor and device parameter', () => {
+ const href = buildSessionMessageDeepLink('abc', 'client/9', { deviceId: 'dev-1' });
+ expect(href).toBe('cindy://session/abc?message=client%2F9&device=dev-1');
+ expect(parseSessionDeepLinkHref(href)).toEqual({
+ sessionId: 'abc',
+ messageClientId: 'client/9',
+ deviceId: 'dev-1',
+ });
+ });
+
+ it('omits the parameter for local sessions (null/undefined deviceId)', () => {
+ expect(buildSessionDeepLink('abc', { deviceId: null })).toBe('cindy://session/abc');
+ expect(buildSessionMessageDeepLink('abc', 'm1', {})).toBe('cindy://session/abc?message=m1');
+ });
+
+ it('ignores empty or malformed device values but keeps the rest of the link', () => {
+ expect(parseSessionDeepLinkHref('cindy://session/abc?device=')).toEqual({
+ sessionId: 'abc',
+ messageClientId: null,
+ deviceId: null,
+ });
+ expect(parseSessionDeepLinkHref('cindy://session/abc?device=%ZZ&message=m1')).toEqual({
+ sessionId: 'abc',
+ messageClientId: 'm1',
+ deviceId: null,
+ });
+ });
+
+ it('is fully matched by the free-text session link pattern', () => {
+ const href = buildSessionMessageDeepLink('abc', 'm1', { deviceId: 'dev-1' });
+ const match = `看这条 ${href}。`.match(new RegExp(SESSION_DEEP_LINK_RE_SOURCE));
+ expect(match?.[0].replace(/[.,;:!?]+$/, '')).toBe(href);
+ });
+});
+
// 双 scheme 收敛:生成一律 cindy://,解析 cindy + 历史 xdt-maker 都认
// (上面的 xdt-maker:// 用例即历史 scheme 回归)。
describe('dual scheme (cindy primary + legacy xdt-maker)', () => {
@@ -88,6 +143,7 @@ describe('dual scheme (cindy primary + legacy xdt-maker)', () => {
expect(parseSessionDeepLinkHref('cindy://session/abc-123?message=m1')).toEqual({
sessionId: 'abc-123',
messageClientId: 'm1',
+ deviceId: null,
});
expect(parseProjectDeepLinkHref('cindy://project/%2Ftmp%2Fx')).toEqual({
workingDir: '/tmp/x',
diff --git a/apps/desktop/src/renderer/components/chat/AssistantMessage.tsx b/apps/desktop/src/renderer/components/chat/AssistantMessage.tsx
index e57f5ee44d..d75a796510 100644
--- a/apps/desktop/src/renderer/components/chat/AssistantMessage.tsx
+++ b/apps/desktop/src/renderer/components/chat/AssistantMessage.tsx
@@ -51,6 +51,7 @@ import { useAgentCapabilities, type AgentKind as MakerAgentKind } from '@/hooks/
import { useSessionFileOrigin } from './ChatSessionFileContext';
import { originDeviceId } from '@/lib/sessionFileOrigin';
import { buildSessionMessageDeepLink } from '@/lib/deepLink';
+import { getStickySessionDeviceId } from '@/features/device-link/stickySessionOrigin';
import { insertSessionLinkIntoComposer } from '@/lib/composerActionsBus';
import { MarkdownRenderer } from './MarkdownRenderer';
import { MessageActionBar } from './MessageActionBar';
@@ -247,8 +248,12 @@ export const AssistantMessage = memo(function AssistantMessage({
navigationMode === 'route-owner' &&
Boolean(currentSessionId && messageClientId) &&
forkSupported;
+ // 远程会话的消息深链把归属设备冻进 `?device=`(粘滞解析,relay 重连窗口不丢),
+ // 复制/「加入对话」产出的链接在任何时刻发送都能路由回来源设备。
const messageDeepLink = currentSessionId && messageClientId
- ? buildSessionMessageDeepLink(currentSessionId, messageClientId)
+ ? buildSessionMessageDeepLink(currentSessionId, messageClientId, {
+ deviceId: getStickySessionDeviceId(currentSessionId),
+ })
: undefined;
const handleAddToChat = useCallback(() => {
if (!currentSessionId || !messageDeepLink) return;
diff --git a/apps/desktop/src/renderer/components/chat/UserMessage.tsx b/apps/desktop/src/renderer/components/chat/UserMessage.tsx
index 845a35ee44..51c9a44dce 100644
--- a/apps/desktop/src/renderer/components/chat/UserMessage.tsx
+++ b/apps/desktop/src/renderer/components/chat/UserMessage.tsx
@@ -86,6 +86,7 @@ import { findLinkifyMatches } from './userMessageLinkify';
import { SessionLinkChip } from './SessionLinkChip';
import { ProjectLinkChip } from './ProjectLinkChip';
import { buildSessionMessageDeepLink, parseSessionDeepLinkHref } from '@/lib/deepLink';
+import { getStickySessionDeviceId } from '@/features/device-link/stickySessionOrigin';
import { insertSessionLinkIntoComposer } from '@/lib/composerActionsBus';
import { MENTION_TOKEN_SPLIT, parseMentionToken } from '@/lib/mentionRefFormat';
import { parseGhostCommandWord, splitGhostDirective } from '@/cindy-brain/ghostCommand';
@@ -847,9 +848,13 @@ export function UserMessage({
const copyText = hasFiles
? `${copyBody}\n\n${t('chat.userMessage.attachmentPrefix')}${files!.map((f) => f.name).join(', ')}`
: copyBody;
+ // 远程会话的消息深链把归属设备冻进 `?device=`(粘滞解析,relay 重连窗口不丢),
+ // 复制/「加入对话」产出的链接在任何时刻发送都能路由回来源设备。
const messageDeepLink =
sessionId && messageClientId
- ? buildSessionMessageDeepLink(sessionId, messageClientId)
+ ? buildSessionMessageDeepLink(sessionId, messageClientId, {
+ deviceId: getStickySessionDeviceId(sessionId),
+ })
: undefined;
const handleAddToChat = useCallback(() => {
if (!sessionId || !messageDeepLink) return;
diff --git a/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx b/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx
index edd7c7285b..e81c95690c 100644
--- a/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx
@@ -247,16 +247,19 @@ export function SessionContentHeader({
t,
]);
- /* ---- 复制对话链接(cindy://session/<id> 深链,与 SessionItem 同语义) ---- */
+ /* ---- 复制对话链接(cindy://session/<id> 深链,与 SessionItem 同语义;
+ 远程会话把归属设备冻进 ?device=) ---- */
const handleCopyDeepLink = useCallback(async () => {
try {
- await navigator.clipboard.writeText(buildSessionDeepLink(session.id));
+ await navigator.clipboard.writeText(
+ buildSessionDeepLink(session.id, { deviceId: session.deviceLinkDeviceId }),
+ );
toast.success(t('ccAgent.sidebar.deepLink.copied'));
} catch (err) {
log.warn('clipboard write failed', err);
toast.warning(t('ccAgent.sidebar.deepLink.copyFailed'));
}
- }, [session.id, t]);
+ }, [session.deviceLinkDeviceId, session.id, t]);
const handleOpenInNewWindow = useCallback(() => {
if (remoteWritesBlocked) {
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx
index 7616f9174c..c1c49505fc 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx
@@ -348,8 +348,9 @@ export function SessionCard({
}
}, [session.id, navigate]);
+ // 远程会话把归属设备冻进 `?device=`:发送时的引用解析不再依赖被控端此刻在线。
const handleCopyDeepLinkSelect = useCallback(async () => {
- const link = buildSessionDeepLink(session.id);
+ const link = buildSessionDeepLink(session.id, { deviceId: session.deviceLinkDeviceId });
try {
await navigator.clipboard.writeText(link);
toast.success(t('ccAgent.sidebar.deepLink.copied'));
@@ -357,7 +358,7 @@ export function SessionCard({
log.warn('clipboard write failed', err);
toast.warning(t('ccAgent.sidebar.deepLink.copyFailed'));
}
- }, [session.id, t]);
+ }, [session.deviceLinkDeviceId, session.id, t]);
// 单项「复制对话链接」:直接复制 cindy://session/<id> 深链。原「复制会话 ID」
// 二级菜单(深度链接 / 仅 ID / Agent)已按产品决策收敛为这一项;不自带分隔线,
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx
index d78c31db88..8b36618ca5 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx
@@ -524,8 +524,9 @@ export const SessionItem = memo(function SessionItem({
// 复制 cindy://session/<id> 深度链接到剪贴板。三个变体(标准/Pinned/Archived/Draft)
// 共用此 handler — sessionId 始终存在(draft 也是 DB-backed 的 Session row)。
+ // 远程会话把归属设备冻进 `?device=`:发送时的引用解析不再依赖被控端此刻在线。
const handleCopyDeepLinkSelect = useCallback(async () => {
- const link = buildSessionDeepLink(session.id);
+ const link = buildSessionDeepLink(session.id, { deviceId: session.deviceLinkDeviceId });
try {
await navigator.clipboard.writeText(link);
toast.success(t('ccAgent.sidebar.deepLink.copied'));
@@ -533,7 +534,7 @@ export const SessionItem = memo(function SessionItem({
log.warn('clipboard write failed', err);
toast.warning(t('ccAgent.sidebar.deepLink.copyFailed'));
}
- }, [session.id, t]);
+ }, [session.deviceLinkDeviceId, session.id, t]);
// 单项「复制对话链接」:直接复制 cindy://session/<id> 深链(可粘贴到聊天里
// 渲染成会话 chip)。原「复制会话 ID」二级菜单(深度链接 / 仅 ID / Agent)已按
diff --git a/apps/desktop/src/renderer/lib/deepLink.ts b/apps/desktop/src/renderer/lib/deepLink.ts
index 1893602129..55a96dab10 100644
--- a/apps/desktop/src/renderer/lib/deepLink.ts
+++ b/apps/desktop/src/renderer/lib/deepLink.ts
@@ -19,13 +19,39 @@ import {
const URL_PREFIX = DEEP_LINK_URL_PREFIX;
const SESSION_PREFIX = `${URL_PREFIX}session/`;
-export function buildSessionDeepLink(sessionId: string): string {
- return `${SESSION_PREFIX}${encodeURIComponent(sessionId)}`;
+/** 深链构建可选项:deviceId = 会话归属的 device-link 设备(远程会话冻结来源)。 */
+export interface SessionDeepLinkOptions {
+ /**
+ * 会话归属设备(device-link deviceId)。远程会话在生成深链时就把来源设备
+ * 冻进 `?device=` 参数——发送时的 sessionRefs 解析不再依赖「被控端此刻
+ * 在线且会话列表已同步」的内存实时状态(relay 重连窗口内查表 miss 会把
+ * 远程会话错判成本地,引用内容注入失败)。本机会话传 undefined/null,
+ * 生成不带参数的旧格式。
+ */
+ deviceId?: string | null;
+}
+
+function sessionDeepLinkQuery(
+ opts: SessionDeepLinkOptions | undefined,
+ messageClientId?: string,
+): string {
+ const pairs: string[] = [];
+ if (messageClientId) pairs.push(`message=${encodeURIComponent(messageClientId)}`);
+ if (opts?.deviceId) pairs.push(`device=${encodeURIComponent(opts.deviceId)}`);
+ return pairs.length > 0 ? `?${pairs.join('&')}` : '';
+}
+
+export function buildSessionDeepLink(sessionId: string, opts?: SessionDeepLinkOptions): string {
+ return `${SESSION_PREFIX}${encodeURIComponent(sessionId)}${sessionDeepLinkQuery(opts)}`;
}
/** 带消息锚点的会话深链:点击后跳到会话内指定消息(clientId 语义,跨设备稳定)。 */
-export function buildSessionMessageDeepLink(sessionId: string, messageClientId: string): string {
- return `${buildSessionDeepLink(sessionId)}?message=${encodeURIComponent(messageClientId)}`;
+export function buildSessionMessageDeepLink(
+ sessionId: string,
+ messageClientId: string,
+ opts?: SessionDeepLinkOptions,
+): string {
+ return `${SESSION_PREFIX}${encodeURIComponent(sessionId)}${sessionDeepLinkQuery(opts, messageClientId)}`;
}
/**
@@ -122,6 +148,8 @@ export interface SessionDeepLinkTarget {
sessionId: string;
/** `?message=<clientId>` 锚点;无锚点 / 锚点值非法时为 null(sessionId 仍有效)。 */
messageClientId: string | null;
+ /** `?device=<deviceId>` 冻结的会话归属设备;旧格式深链 / 参数值非法时为 null。 */
+ deviceId: string | null;
}
/**
@@ -148,23 +176,28 @@ export function parseSessionDeepLinkHref(href: string): SessionDeepLinkTarget |
}
if (!sessionId) return null;
let messageClientId: string | null = null;
+ let deviceId: string | null = null;
if (queryIdx >= 0) {
const query = noHash.slice(queryIdx + 1);
for (const pair of query.split('&')) {
const eqIdx = pair.indexOf('=');
- if (eqIdx <= 0 || pair.slice(0, eqIdx) !== 'message') continue;
+ if (eqIdx <= 0) continue;
+ const key = pair.slice(0, eqIdx);
+ if (key !== 'message' && key !== 'device') continue;
+ if (key === 'message' ? messageClientId !== null : deviceId !== null) continue;
const rawValue = pair.slice(eqIdx + 1);
- if (!rawValue) break;
+ if (!rawValue) continue;
try {
const decoded = decodeURIComponent(rawValue);
- if (decoded) messageClientId = decoded;
+ if (!decoded) continue;
+ if (key === 'message') messageClientId = decoded;
+ else deviceId = decoded;
} catch {
- // 锚点编码非法 → 按无锚点处理,不拖累整条链接
+ // 参数编码非法 → 按无该参数处理,不拖累整条链接
}
- break;
}
}
- return { sessionId, messageClientId };
+ return { sessionId, messageClientId, deviceId };
}
/**
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index 15dd9f7376..1e933e625f 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -55,6 +55,7 @@ import {
remoteProjectsStore,
requestRemoteReseed,
} from '@/features/device-link/remoteProjectsStore';
+import { getStickySessionDeviceId } from '@/features/device-link/stickySessionOrigin';
import {
noteRemoteSessionSyncCompleted,
noteRemoteSessionSyncStarted,
@@ -5285,11 +5286,10 @@ function extractSessionRefs(
text: string,
previous?: readonly AgentInputSessionRef[],
): NonNullable<AgentInputQueuedMessage['sessionRefs']> {
- return reconcileSessionRefsForText(
- text,
- previous,
- (sessionId) => remoteProjectsStore.getSessionDeviceId(sessionId),
- );
+ // 粘滞版归属解析(与 learn/goal/makerTransport 链路对齐):relay 瞬时重连
+ // 会 clear sessionId→deviceId 注册表,裸查表在这个窗口把远程会话错判成
+ // 本地 → 引用解析落到控制端空本地库,内容注入失败。
+ return reconcileSessionRefsForText(text, previous, getStickySessionDeviceId);
}
function buildCreateOptsForCurrentSession(
diff --git a/apps/desktop/src/shared/agentInputQueue.ts b/apps/desktop/src/shared/agentInputQueue.ts
index e779af9e52..30562b4ede 100644
--- a/apps/desktop/src/shared/agentInputQueue.ts
+++ b/apps/desktop/src/shared/agentInputQueue.ts
@@ -448,24 +448,34 @@ export function reconcileSessionRefsForText(
}
if (!sessionId) continue;
let messageClientId: string | undefined;
+ let linkDeviceId: string | undefined;
// 链接常作为句子末尾的一部分出现;句号等标点不属于 query,
// 否则锚点 clientId 会被解析成 `id.` 而无法命中消息。
const query = (match[2] ?? '').replace(/[.,;:!?]+$/, '');
for (const pair of query.split('&')) {
const eq = pair.indexOf('=');
- if (eq <= 0 || pair.slice(0, eq) !== 'message') continue;
+ if (eq <= 0) continue;
+ const paramKey = pair.slice(0, eq);
+ if (paramKey !== 'message' && paramKey !== 'device') continue;
+ if (paramKey === 'message' ? messageClientId !== undefined : linkDeviceId !== undefined) {
+ continue;
+ }
try {
const decoded = decodeURIComponent(pair.slice(eq + 1));
- if (decoded) messageClientId = decoded;
+ if (!decoded) continue;
+ if (paramKey === 'message') messageClientId = decoded;
+ else linkDeviceId = decoded;
} catch {
- // Invalid anchor: treat it as an unanchored session reference.
+ // Invalid parameter: treat it as absent.
}
- break;
}
const key = `${sessionId}\u0000${messageClientId ?? ''}`;
if (seen.has(key)) continue;
seen.add(key);
- const deviceId = deviceIdForSession?.(sessionId) ?? hints.get(sessionId);
+ // 深链里冻结的 `?device=`(chip 生成时刻的会话归属)最可信;其次才是
+ // 发送时刻的实时查表与旧 ref 的 device hint——会话归属不会迁移,冻结值
+ // 不受 relay 重连窗口内 sessionId→deviceId 注册表被 clear 的时序影响。
+ const deviceId = linkDeviceId ?? deviceIdForSession?.(sessionId) ?? hints.get(sessionId);
refs.push({
sessionId,
...(messageClientId ? { messageClientId } : {}),
diff --git a/apps/mobile/src/__tests__/sessionLinks.test.ts b/apps/mobile/src/__tests__/sessionLinks.test.ts
index 2924bab8fc..cf2babfda1 100644
--- a/apps/mobile/src/__tests__/sessionLinks.test.ts
+++ b/apps/mobile/src/__tests__/sessionLinks.test.ts
@@ -19,28 +19,58 @@ describe('session links', () => {
expect(parseSessionDeepLinkUrl('cindy://session/abc-123')).toEqual({
sessionId: 'abc-123',
messageClientId: null,
+ deviceId: null,
});
expect(parseSessionDeepLinkUrl('xdt-maker://session/abc-123')).toEqual({
sessionId: 'abc-123',
messageClientId: null,
+ deviceId: null,
});
expect(parseSessionDeepLinkUrl(buildMobileSessionMessageDeepLink('abc', 'client/9'))).toEqual({
sessionId: 'abc',
messageClientId: 'client/9',
+ deviceId: null,
});
expect(parseSessionDeepLinkUrl('xdt-maker://session/abc?message=')).toEqual({
sessionId: 'abc',
messageClientId: null,
+ deviceId: null,
});
expect(parseSessionDeepLinkUrl('xdt-maker://session/abc?message=%ZZ')).toEqual({
sessionId: 'abc',
messageClientId: null,
+ deviceId: null,
});
expect(parseSessionDeepLinkUrl('xdt-maker://project/foo')).toBeNull();
expect(parseSessionDeepLinkUrl('xdt-maker://session/')).toBeNull();
expect(parseSessionDeepLinkUrl('xdt-maker://session/%ZZ')).toBeNull();
});
+ it('parses the frozen device parameter emitted by desktop deep links', () => {
+ // 桌面端远程会话深链把归属设备冻进 `?device=`;手机端解析同口径,
+ // 空值 / 编码非法回退 null,不拖累整条链接。
+ expect(parseSessionDeepLinkUrl('cindy://session/abc?device=dev-studio')).toEqual({
+ sessionId: 'abc',
+ messageClientId: null,
+ deviceId: 'dev-studio',
+ });
+ expect(parseSessionDeepLinkUrl('cindy://session/abc?message=m1&device=dev-1')).toEqual({
+ sessionId: 'abc',
+ messageClientId: 'm1',
+ deviceId: 'dev-1',
+ });
+ expect(parseSessionDeepLinkUrl('cindy://session/abc?device=')).toEqual({
+ sessionId: 'abc',
+ messageClientId: null,
+ deviceId: null,
+ });
+ expect(parseSessionDeepLinkUrl('cindy://session/abc?device=%ZZ&message=m1')).toEqual({
+ sessionId: 'abc',
+ messageClientId: 'm1',
+ deviceId: null,
+ });
+ });
+
it('extracts unique session ids from message text', () => {
const a = 'xdt-maker://session/03e0c22d-19db-4ac5-814f-1ea04040b471';
const b = 'xdt-maker://session/aaaa1111-2222-3333-4444-555566667777?message=m1';
diff --git a/apps/mobile/src/__tests__/sessionReferences.test.ts b/apps/mobile/src/__tests__/sessionReferences.test.ts
index 7df03b10d5..77b85e311d 100644
--- a/apps/mobile/src/__tests__/sessionReferences.test.ts
+++ b/apps/mobile/src/__tests__/sessionReferences.test.ts
@@ -110,6 +110,19 @@ describe('mobile session-reference links', () => {
)).toEqual([{ sessionId: 'source', deviceId: 'source-device' }]);
});
+ it('prefers the device frozen into the link over store lookup and hints', () => {
+ // 桌面端深链冻结的 `?device=` 优先;store 查不到时也不丢远程判定。
+ expect(extractMobileSessionReferences(
+ 'cindy://session/source?device=dev-frozen',
+ () => 'dev-live',
+ [{ sessionId: 'source', deviceId: 'dev-hint' }],
+ )).toEqual([{ sessionId: 'source', deviceId: 'dev-frozen' }]);
+ expect(extractMobileSessionReferences(
+ 'cindy://session/source?message=anchor&device=dev-frozen',
+ () => undefined,
+ )).toEqual([{ sessionId: 'source', messageClientId: 'anchor', deviceId: 'dev-frozen' }]);
+ });
+
it('clears stale refs and trusted snapshots when an edit removes the link', async () => {
const invoke = vi.fn();
const prepared = await prepareMobileQueuedSessionReferences({
diff --git a/apps/mobile/src/session/sessionLinks.ts b/apps/mobile/src/session/sessionLinks.ts
index 76ac8d4aa3..3eeb1b361d 100644
--- a/apps/mobile/src/session/sessionLinks.ts
+++ b/apps/mobile/src/session/sessionLinks.ts
@@ -37,6 +37,8 @@ export interface SessionDeepLinkTarget {
sessionId: string;
/** `?message=<clientId>` 锚点;无锚点 / 锚点值非法时为 null(sessionId 仍有效)。 */
messageClientId: string | null;
+ /** `?device=<deviceId>` 冻结的会话归属设备;旧格式深链 / 参数值非法时为 null。 */
+ deviceId: string | null;
}
/**
@@ -63,23 +65,28 @@ export function parseSessionDeepLinkUrl(url: string): SessionDeepLinkTarget | nu
}
if (!sessionId) return null;
let messageClientId: string | null = null;
+ let deviceId: string | null = null;
if (queryIdx >= 0) {
const query = noHash.slice(queryIdx + 1);
for (const pair of query.split('&')) {
const eqIdx = pair.indexOf('=');
- if (eqIdx <= 0 || pair.slice(0, eqIdx) !== 'message') continue;
+ if (eqIdx <= 0) continue;
+ const key = pair.slice(0, eqIdx);
+ if (key !== 'message' && key !== 'device') continue;
+ if (key === 'message' ? messageClientId !== null : deviceId !== null) continue;
const rawValue = pair.slice(eqIdx + 1);
- if (!rawValue) break;
+ if (!rawValue) continue;
try {
const decoded = decodeURIComponent(rawValue);
- if (decoded) messageClientId = decoded;
+ if (!decoded) continue;
+ if (key === 'message') messageClientId = decoded;
+ else deviceId = decoded;
} catch {
- // 锚点编码非法 → 按无锚点处理
+ // 参数编码非法 → 按无该参数处理
}
- break;
}
}
- return { sessionId, messageClientId };
+ return { sessionId, messageClientId, deviceId };
}
/**
diff --git a/apps/mobile/src/session/sessionReferences.ts b/apps/mobile/src/session/sessionReferences.ts
index 1fc6cd0365..ae2dbf133e 100644
--- a/apps/mobile/src/session/sessionReferences.ts
+++ b/apps/mobile/src/session/sessionReferences.ts
@@ -157,7 +157,11 @@ export function extractMobileSessionReferences(
const key = mobileSessionReferenceMetadataKey(target.sessionId, target.messageClientId);
if (seen.has(key)) continue;
seen.add(key);
- const deviceId = deviceIdForSession(target.sessionId)
+ // 深链里冻结的 `?device=`(生成时刻的会话归属)优先——与桌面端
+ // reconcileSessionRefsForText 同口径;会话归属不会迁移,冻结值不受
+ // 发送时刻 store 状态(设备离线 / 列表未同步)影响。
+ const deviceId = target.deviceId
+ ?? deviceIdForSession(target.sessionId)
?? previousDeviceIds.get(key)
?? previousDeviceIdsBySession.get(target.sessionId);
refs.push({