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(session-reference): 外部任务链接解析失败时仍发送给 Agent (#1304)

Dash2a1f7427834d
diff --git a/apps/desktop/src/main/device-link/__tests__/outboundSessionReferences.test.ts b/apps/desktop/src/main/device-link/__tests__/outboundSessionReferences.test.ts
index 8c2a335f24..1d12e17da5 100644
--- a/apps/desktop/src/main/device-link/__tests__/outboundSessionReferences.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/outboundSessionReferences.test.ts
@@ -6,6 +6,7 @@ vi.mock('../../maker-ipc/sessionReferenceResolver.js', () => ({ resolveSessionRe
import {
outboundSessionReferencesRequested,
rewriteOutboundSessionReferences,
+ stripOutboundSessionReferenceSideChannels,
} from '../outboundSessionReferences.js';
import type { AgentInputQueuedMessage } from '../../../shared/agentInputQueue.js';
@@ -75,14 +76,17 @@ describe('rewriteOutboundSessionReferences', () => {
expect(JSON.stringify(rewritten)).not.toContain('renderer-forged history');
});
- it('does not borrow the target device identity when the controller cannot read a third device', async () => {
+ it('falls back to raw link text when the controller cannot read a third device', async () => {
resolveSessionReferences.mockRejectedValueOnce(new Error('source device access revoked'));
- await expect(
- rewriteOutboundSessionReferences('maker:input:steer', [
- 'target-on-b',
- queued([{ sessionId: 'on-c', deviceId: 'device-c' }]),
- ]),
- ).rejects.toThrow('access revoked');
+ const rewritten = await rewriteOutboundSessionReferences('maker:input:steer', [
+ 'target-on-b',
+ queued([{ sessionId: 'on-c', deviceId: 'device-c' }]),
+ ]);
+
+ expect((rewritten[1] as AgentInputQueuedMessage).text).toBe('compare linked session');
+ expect((rewritten[1] as AgentInputQueuedMessage).sessionRefs).toBeUndefined();
+ expect((rewritten[1] as AgentInputQueuedMessage).trustedSessionReferenceContexts)
+ .toBeUndefined();
});
it('lets a queued remove-from-queue steer use the target stored snapshot', async () => {
@@ -110,6 +114,26 @@ describe('rewriteOutboundSessionReferences', () => {
expect(rewritten[4]).toEqual(snapshot);
});
+ it('drops unresolved update-text side channels while preserving the edited text', async () => {
+ const refs = [{ sessionId: 'foreign', deviceId: 'device-c' }];
+ resolveSessionReferences.mockRejectedValueOnce(new Error('foreign session'));
+
+ const rewritten = await rewriteOutboundSessionReferences('maker:input:update-text', [
+ 'target-on-b',
+ 'client-1',
+ 'now use cindy://session/foreign',
+ refs,
+ ]);
+
+ expect(rewritten).toEqual([
+ 'target-on-b',
+ 'client-1',
+ 'now use cindy://session/foreign',
+ [],
+ [],
+ ]);
+ });
+
it('keeps the legacy three-argument update-text shape unchanged', async () => {
const args = ['target-on-b', 'client-1', 'plain edit'];
const rewritten = await rewriteOutboundSessionReferences('maker:input:update-text', args);
@@ -119,6 +143,39 @@ describe('rewriteOutboundSessionReferences', () => {
expect(resolveSessionReferences).not.toHaveBeenCalled();
});
+ it('strips every queue-mutation side channel without changing user text', () => {
+ const enqueue = stripOutboundSessionReferenceSideChannels('maker:input:enqueue', [
+ 'target-on-b',
+ queued([{ sessionId: 'source' }]),
+ ]);
+ const updateContent = stripOutboundSessionReferenceSideChannels('maker:input:update-content', [
+ 'target-on-b',
+ 'client-1',
+ queued([{ sessionId: 'source' }]),
+ ]);
+ const updateText = stripOutboundSessionReferenceSideChannels('maker:input:update-text', [
+ 'target-on-b',
+ 'client-1',
+ 'keep cindy://session/source',
+ [{ sessionId: 'source' }],
+ [{ sessionId: 'source', messages: [] }],
+ ]);
+
+ for (const item of [enqueue[1], updateContent[2]] as AgentInputQueuedMessage[]) {
+ expect(item.text).toBe('compare linked session');
+ expect(item.sessionRefs).toBeUndefined();
+ expect(item.trustedSessionReferenceContexts).toBeUndefined();
+ expect(item.sessionReferencesRequireTrustedSnapshot).toBeUndefined();
+ }
+ expect(updateText).toEqual([
+ 'target-on-b',
+ 'client-1',
+ 'keep cindy://session/source',
+ [],
+ [],
+ ]);
+ });
+
it('resolves references in a full queued-content replacement', async () => {
const refs = [{ sessionId: 'replacement', deviceId: 'device-c' }];
resolveSessionReferences.mockResolvedValueOnce([{ sessionId: 'replacement', messages: [] }]);
diff --git a/apps/desktop/src/main/device-link/__tests__/sessionReferenceCompatibility.test.ts b/apps/desktop/src/main/device-link/__tests__/sessionReferenceCompatibility.test.ts
index 6cd0cbbea7..af9004cf6b 100644
--- a/apps/desktop/src/main/device-link/__tests__/sessionReferenceCompatibility.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/sessionReferenceCompatibility.test.ts
@@ -22,11 +22,14 @@ function queuedWithReference() {
}
describe('device-link target session-reference capability gate', () => {
- it('rejects an old target before resolving or sending the referenced message', async () => {
- const invoke = vi.fn<DeviceLinkIpcDeps['invoke']>().mockResolvedValue({
- ok: false,
- error: { code: 'CHANNEL_NOT_ALLOWED', message: 'unknown channel' },
- });
+ it('sends raw link text when an old target cannot consume trusted reference fields', async () => {
+ const invoke = vi
+ .fn<DeviceLinkIpcDeps['invoke']>()
+ .mockResolvedValueOnce({
+ ok: false,
+ error: { code: 'CHANNEL_NOT_ALLOWED', message: 'unknown channel' },
+ })
+ .mockResolvedValueOnce({ ok: true, result: { accepted: true } });
const rewrite = vi.fn(async (_channel: string, args: unknown[]) => args);
await expect(
@@ -34,18 +37,28 @@ describe('device-link target session-reference capability gate', () => {
'target-session',
queuedWithReference(),
]),
- ).rejects.toThrow('[SESSION_REFERENCE_UNSUPPORTED]');
+ ).resolves.toEqual({ accepted: true });
- expect(invoke).toHaveBeenCalledTimes(1);
- expect(invoke).toHaveBeenCalledWith(
+ expect(invoke).toHaveBeenCalledTimes(2);
+ expect(invoke).toHaveBeenNthCalledWith(
+ 1,
'target-device',
DL_SESSION_REFERENCE_CAPABILITY_CHANNEL,
[],
);
- expect(rewrite).not.toHaveBeenCalled();
+ expect(invoke).toHaveBeenNthCalledWith(
+ 2,
+ 'target-device',
+ 'maker:input:enqueue',
+ [
+ 'target-session',
+ { text: 'compare cindy://session/source' },
+ ],
+ );
+ expect(rewrite).toHaveBeenCalledTimes(1);
});
- it('probes a new target before rewriting and sending the message', async () => {
+ it('rewrites before probing a new target and sending the message', async () => {
const invoke = vi
.fn<DeviceLinkIpcDeps['invoke']>()
.mockResolvedValueOnce({ ok: true, result: { supported: true, version: 1 } })
@@ -69,6 +82,33 @@ describe('device-link target session-reference capability gate', () => {
expect(rewrite).toHaveBeenCalledTimes(1);
});
+ it('sends a raw foreign link without probing reference support', async () => {
+ const invoke = vi
+ .fn<DeviceLinkIpcDeps['invoke']>()
+ .mockResolvedValueOnce({ ok: true, result: { accepted: true } });
+ const rewrite = vi.fn(async (_channel: string, args: unknown[]) => [
+ args[0],
+ { ...(args[1] as object), sessionRefs: undefined },
+ ]);
+
+ await expect(
+ handleInvoke(depsForInvoke(invoke, rewrite), 'target-device', 'maker:input:enqueue', [
+ 'target-session',
+ queuedWithReference(),
+ ]),
+ ).resolves.toEqual({ accepted: true });
+
+ expect(invoke).toHaveBeenCalledTimes(1);
+ expect(invoke).toHaveBeenCalledWith(
+ 'target-device',
+ 'maker:input:enqueue',
+ [
+ 'target-session',
+ expect.objectContaining({ text: 'compare cindy://session/source' }),
+ ],
+ );
+ });
+
it('accepts newer compatible capability versions', async () => {
const invoke = vi
.fn<DeviceLinkIpcDeps['invoke']>()
diff --git a/apps/desktop/src/main/device-link/ipc.ts b/apps/desktop/src/main/device-link/ipc.ts
index 168a35faa3..b6a19add69 100644
--- a/apps/desktop/src/main/device-link/ipc.ts
+++ b/apps/desktop/src/main/device-link/ipc.ts
@@ -43,6 +43,7 @@ import { rewriteOutboundMedia } from './outboundMedia';
import {
outboundSessionReferencesRequested,
rewriteOutboundSessionReferences,
+ stripOutboundSessionReferenceSideChannels,
} from './outboundSessionReferences';
import {
isPlaceholderDeviceName,
@@ -443,6 +444,22 @@ export async function handleInvoke(
}
let callArgs = Array.isArray(args) ? args : [];
+ // Resolve controller-relative references first. If the source session is
+ // foreign or unavailable, the rewrite drops only the optional reference
+ // side channel and preserves the raw link text. Recompute the capability
+ // need afterwards so that plain-link fallback also works with older targets.
+ if (deps.rewriteOutboundSessionReferences) {
+ try {
+ callArgs = await deps.rewriteOutboundSessionReferences(channel, callArgs);
+ } catch (err) {
+ throwIpcError(
+ 'SESSION_REFERENCE_UNAVAILABLE',
+ err instanceof Error ? err.message : String(err),
+ );
+ }
+ assertControlTargetEnabled(deps, normalizedDeviceId);
+ }
+
if (outboundSessionReferencesRequested(channel, callArgs)) {
let capability: InvokeResultPayload;
try {
@@ -456,55 +473,43 @@ export async function handleInvoke(
}
if (!capability.ok) {
if (capability.error.code === 'CHANNEL_NOT_ALLOWED') {
- throwIpcError(
- 'SESSION_REFERENCE_UNSUPPORTED',
- '目标设备版本不支持任务引用,请升级目标设备后重试',
- );
- }
- if (capability.error.code === 'IPC_ERROR') {
+ log.warn('target does not support session references; sending raw link text', {
+ channel,
+ });
+ callArgs = stripOutboundSessionReferenceSideChannels(channel, callArgs);
+ } else if (capability.error.code === 'IPC_ERROR') {
throwIpcError(
'SESSION_REFERENCE_UNAVAILABLE',
'目标设备仍在启动,任务引用暂不可用,请稍后重试',
);
+ } else {
+ throwIpcError(
+ DEVICE_LINK_CODE_MAP[capability.error.code] ?? 'INTERNAL',
+ capability.error.message,
+ );
+ }
+ } else {
+ const capabilityVersion =
+ capability.result &&
+ typeof capability.result === 'object' &&
+ !Array.isArray(capability.result)
+ ? (capability.result as { version?: unknown }).version
+ : undefined;
+ if (
+ !capability.result ||
+ typeof capability.result !== 'object' ||
+ Array.isArray(capability.result) ||
+ (capability.result as { supported?: unknown }).supported !== true ||
+ typeof capabilityVersion !== 'number' ||
+ !Number.isFinite(capabilityVersion) ||
+ capabilityVersion < 1
+ ) {
+ log.warn('target does not support session references; sending raw link text', {
+ channel,
+ });
+ callArgs = stripOutboundSessionReferenceSideChannels(channel, callArgs);
}
- throwIpcError(
- DEVICE_LINK_CODE_MAP[capability.error.code] ?? 'INTERNAL',
- capability.error.message,
- );
- }
- const capabilityVersion =
- capability.result &&
- typeof capability.result === 'object' &&
- !Array.isArray(capability.result)
- ? (capability.result as { version?: unknown }).version
- : undefined;
- if (
- !capability.result ||
- typeof capability.result !== 'object' ||
- Array.isArray(capability.result) ||
- (capability.result as { supported?: unknown }).supported !== true ||
- typeof capabilityVersion !== 'number' ||
- !Number.isFinite(capabilityVersion) ||
- capabilityVersion < 1
- ) {
- throwIpcError(
- 'SESSION_REFERENCE_UNSUPPORTED',
- '目标设备版本不支持任务引用,请升级目标设备后重试',
- );
- }
- }
-
- // 会话引用必须在控制端坐标系解析;放在附件上传前,引用失败时不产生无用 OSS 写入。
- if (deps.rewriteOutboundSessionReferences) {
- try {
- callArgs = await deps.rewriteOutboundSessionReferences(channel, callArgs);
- } catch (err) {
- throwIpcError(
- 'SESSION_REFERENCE_UNAVAILABLE',
- err instanceof Error ? err.message : String(err),
- );
}
- assertControlTargetEnabled(deps, normalizedDeviceId);
}
// 出方向附件:发往远程前先把本机附件上传 OSS、替换成引用串(bytes 不内联进 relay)。
diff --git a/apps/desktop/src/main/device-link/outboundSessionReferences.ts b/apps/desktop/src/main/device-link/outboundSessionReferences.ts
index f3baf67980..8e4d7063df 100644
--- a/apps/desktop/src/main/device-link/outboundSessionReferences.ts
+++ b/apps/desktop/src/main/device-link/outboundSessionReferences.ts
@@ -5,9 +5,11 @@
* 再解释。这里在越过 device-link 前由控制端 main 读取权威历史并固化快照。
*/
import type { AgentInputQueuedMessage } from '../../shared/agentInputQueue.js';
+import { createLogger } from '../logger.js';
import { resolveSessionReferences } from '../maker-ipc/sessionReferenceResolver.js';
const QUEUED_CHANNELS = new Set(['maker:input:enqueue', 'maker:input:steer', 'maker:input:update-content']);
+const log = createLogger('device-link:session-reference');
function usesTargetStoredSnapshot(channel: string, args: unknown[], item: AgentInputQueuedMessage): boolean {
if (channel !== 'maker:input:steer') return false;
@@ -37,6 +39,31 @@ export function outboundSessionReferencesRequested(channel: string, args: unknow
return Array.isArray(refs) && refs.length > 0;
}
+/** Preserve user-authored text while removing every trusted-reference side channel. */
+export function stripOutboundSessionReferenceSideChannels(
+ channel: string,
+ args: unknown[],
+): unknown[] {
+ if (channel === 'maker:input:update-text') {
+ if (!Array.isArray(args[3])) return args;
+ const next = [...args];
+ next[3] = [];
+ next[4] = [];
+ return next;
+ }
+ if (!QUEUED_CHANNELS.has(channel)) return args;
+ const itemIndex = channel === 'maker:input:update-content' ? 2 : 1;
+ const item = args[itemIndex];
+ if (!item || typeof item !== 'object' || Array.isArray(item)) return args;
+ const nextItem: AgentInputQueuedMessage = { ...(item as AgentInputQueuedMessage) };
+ delete nextItem.sessionRefs;
+ delete nextItem.trustedSessionReferenceContexts;
+ delete nextItem.sessionReferencesRequireTrustedSnapshot;
+ const next = [...args];
+ next[itemIndex] = nextItem;
+ return next;
+}
+
export async function rewriteOutboundSessionReferences(
channel: string,
args: unknown[],
@@ -45,7 +72,18 @@ export async function rewriteOutboundSessionReferences(
if (!Array.isArray(args[3])) return args;
const refs = args[3] as AgentInputQueuedMessage['sessionRefs'];
const next = [...args];
- next[4] = refs && refs.length > 0 ? await resolveSessionReferences(refs) : [];
+ try {
+ next[4] = refs && refs.length > 0 ? await resolveSessionReferences(refs) : [];
+ } catch (error) {
+ // Preserve the edited text, but do not ask the target to trust an
+ // unresolved controller-side reference or reject the whole edit.
+ log.warn('session reference enrichment skipped; sending raw link text', {
+ channel,
+ referenceCount: refs?.length ?? 0,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return stripOutboundSessionReferenceSideChannels(channel, args);
+ }
return next;
}
if (!QUEUED_CHANNELS.has(channel)) return args;
@@ -58,7 +96,19 @@ export async function rewriteOutboundSessionReferences(
// renderer 永远不能夹带可信正文;无论是否有 refs 都先清掉。
delete nextItem.trustedSessionReferenceContexts;
if (queued.sessionRefs && queued.sessionRefs.length > 0) {
- nextItem.trustedSessionReferenceContexts = await resolveSessionReferences(queued.sessionRefs);
+ try {
+ nextItem.trustedSessionReferenceContexts = await resolveSessionReferences(queued.sessionRefs);
+ } catch (error) {
+ // The raw deep link remains in `text`. Dropping both side-channel
+ // fields keeps the target from reinterpreting a foreign session id in
+ // its own account while still letting the Agent handle the link.
+ log.warn('session reference enrichment skipped; sending raw link text', {
+ channel,
+ referenceCount: queued.sessionRefs.length,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return stripOutboundSessionReferenceSideChannels(channel, args);
+ }
}
const next = [...args];
next[itemIndex] = nextItem;
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
index 4f202e1fa2..e1b27ae8c7 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
@@ -500,6 +500,32 @@ describe('AgentInputCoordinator trusted session reference snapshots', () => {
expect(latestProjection(h.projections).error).toBeNull();
});
+ it('sends a foreign session link as ordinary Agent text when history enrichment fails', async () => {
+ const h = createHarness();
+ h.resolveSessionReferences.mockRejectedValueOnce(new Error('session belongs to another account'));
+ const text = 'inspect cindy://session/foreign-session';
+
+ h.coordinator.enqueue('target-session', makeItem('quoted-foreign', text, {
+ sessionRefs: [{ sessionId: 'foreign-session' }],
+ }));
+ await flush();
+
+ expect(h.resolveSessionReferences).toHaveBeenCalledWith([
+ { sessionId: 'foreign-session' },
+ ]);
+ expect(h.sendToAgent).toHaveBeenCalledWith(
+ 'target-session',
+ { type: 'user', content: text },
+ expect.anything(),
+ expect.anything(),
+ );
+ expect(latestProjection(h.projections).error).toBeNull();
+ expect(mocks.logger.warn).toHaveBeenCalledWith(
+ 'session reference enrichment skipped',
+ expect.objectContaining({ referenceCount: 1 }),
+ );
+ });
+
it('clears a stale trusted snapshot on a full-content rewrite without refs', () => {
const h = createHarness();
const item = makeItem('quoted-content-rewrite', 'compare cindy://session/source-session', {
diff --git a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
index e8e0d8c987..4232c087f8 100644
--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
@@ -2236,7 +2236,19 @@ export class AgentInputCoordinator {
if (item.sessionReferencesRequireTrustedSnapshot) {
throw new Error('Remote session reference snapshot is missing; edit and resend the message.');
}
- return this.deps.resolveSessionReferences?.(item.sessionRefs) ?? [];
+ try {
+ return await (this.deps.resolveSessionReferences?.(item.sessionRefs) ?? []);
+ } catch (error) {
+ // Session links are still useful as ordinary Agent-facing text when the
+ // referenced session belongs to another account, was deleted, or is
+ // temporarily unavailable. Quoted history is an optional enrichment:
+ // fail closed on the history body, but do not fail the user's message.
+ log.warn('session reference enrichment skipped', {
+ referenceCount: item.sessionRefs.length,
+ error: errorMessage(error),
+ });
+ return [];
+ }
}
private isDispatchBoundaryBusy(sessionId: string, state: SessionInputState): boolean {
diff --git a/apps/mobile/src/__tests__/sessionReferences.test.ts b/apps/mobile/src/__tests__/sessionReferences.test.ts
index d486efb554..f3e365350a 100644
--- a/apps/mobile/src/__tests__/sessionReferences.test.ts
+++ b/apps/mobile/src/__tests__/sessionReferences.test.ts
@@ -1,4 +1,4 @@
-import { beforeAll, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import {
DeviceLinkError,
DL_HISTORY_MESSAGES_CHANNEL,
@@ -26,6 +26,14 @@ beforeAll(async () => {
await i18n.changeLanguage('zh-CN');
});
+beforeEach(() => {
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
function message(
sessionId: string,
id: string,
@@ -74,6 +82,29 @@ describe('mobile session-reference links', () => {
() => 'dev-source',
'dev-target',
)).resolves.toBe(item);
+ expect(console.warn).toHaveBeenCalledWith(
+ '[session-references] trusted history unavailable; preserving raw link text',
+ expect.objectContaining({ phase: 'stored-snapshot' }),
+ );
+ });
+
+ it('does not reuse a stored steer projection when the target itself is unavailable', async () => {
+ const item = {
+ text: 'continue cindy://session/source',
+ sessionRefs: [{ sessionId: 'source', deviceId: 'dev-source' }],
+ };
+ const invoke = asInvoke(async (_deviceId, channel) => {
+ expect(channel).toBe(DL_SESSION_REFERENCE_CAPABILITY_CHANNEL);
+ throw new DeviceLinkError('DEVICE_OFFLINE', 'target offline');
+ });
+
+ await expect(prepareMobileQueuedSessionReferencesForSteer(
+ item,
+ invoke,
+ () => 'dev-source',
+ 'dev-target',
+ )).rejects.toMatchObject({ code: 'SESSION_REFERENCE_OFFLINE' });
+ expect(console.warn).not.toHaveBeenCalled();
});
it('extracts both schemes, anchors, source devices, and removes exact duplicates', () => {
@@ -154,7 +185,7 @@ describe('mobile session-reference links', () => {
})).toBe('链接附近 · 4 条 · 已截断');
});
- it('rejects an old target before reading history from the source device', async () => {
+ it('falls back to raw link text when the target does not support references', async () => {
const invoke = vi.fn(async (deviceId: string, channel: string) => {
expect(deviceId).toBe('target-old');
expect(channel).toBe(DL_SESSION_REFERENCE_CAPABILITY_CHANNEL);
@@ -166,8 +197,59 @@ describe('mobile session-reference links', () => {
asInvoke(invoke),
() => 'source-device',
'target-old',
- )).rejects.toMatchObject({ code: 'SESSION_REFERENCE_UNSUPPORTED' });
+ )).resolves.toEqual({ text: 'compare cindy://session/source' });
expect(invoke).toHaveBeenCalledTimes(1);
+ expect(console.warn).toHaveBeenCalledWith(
+ '[session-references] trusted history unavailable; preserving raw link text',
+ expect.objectContaining({
+ phase: 'target-capability',
+ code: 'SESSION_REFERENCE_UNSUPPORTED',
+ }),
+ );
+ });
+
+ it('preserves target availability errors instead of treating them as source fallback', async () => {
+ const invoke = vi.fn(async (_deviceId: string, channel: string) => {
+ expect(channel).toBe(DL_SESSION_REFERENCE_CAPABILITY_CHANNEL);
+ throw new DeviceLinkError('DEVICE_OFFLINE', 'target offline');
+ });
+
+ await expect(prepareMobileQueuedSessionReferences(
+ { text: 'compare cindy://session/source' },
+ asInvoke(invoke),
+ () => 'source-device',
+ 'target-offline',
+ )).rejects.toMatchObject({ code: 'SESSION_REFERENCE_OFFLINE' });
+ expect(console.warn).not.toHaveBeenCalled();
+ });
+
+ it('falls back to raw link text when the source session is foreign', async () => {
+ const invoke = vi.fn(async (_deviceId: string, channel: string) => {
+ if (channel === DL_SESSION_REFERENCE_CAPABILITY_CHANNEL) {
+ return { supported: true, version: 1 };
+ }
+ if (channel === 'local-db:sessions:get') return null;
+ throw new Error(`unexpected channel ${channel}`);
+ });
+
+ await expect(prepareMobileQueuedSessionReferences(
+ {
+ text: 'compare cindy://session/foreign',
+ sessionRefs: [{ sessionId: 'stale', deviceId: 'old-device' }],
+ sessionReferencesRequireTrustedSnapshot: true,
+ },
+ asInvoke(invoke),
+ () => 'source-device',
+ 'target-new',
+ )).resolves.toEqual({ text: 'compare cindy://session/foreign' });
+ expect(invoke.mock.calls.map((call) => call[1])).toEqual([
+ DL_SESSION_REFERENCE_CAPABILITY_CHANNEL,
+ 'local-db:sessions:get',
+ ]);
+ expect(console.warn).toHaveBeenCalledWith(
+ '[session-references] trusted history unavailable; preserving raw link text',
+ expect.objectContaining({ phase: 'source-resolution' }),
+ );
});
it('probes a new target before resolving source history', async () => {
diff --git a/apps/mobile/src/session/sessionReferences.ts b/apps/mobile/src/session/sessionReferences.ts
index 795d0b4a61..24e1c3b037 100644
--- a/apps/mobile/src/session/sessionReferences.ts
+++ b/apps/mobile/src/session/sessionReferences.ts
@@ -789,18 +789,30 @@ export async function resolveMobileSessionReferences(
* This deliberately removes stale snapshots first, so editing a link away cannot retain
* previously trusted history and steering a display-safe projection always re-reads source data.
*/
-export async function prepareMobileQueuedSessionReferences<T extends MobileQueuedReferenceCarrier>(
+function stripMobileSessionReferenceSideChannels<T extends MobileQueuedReferenceCarrier>(
item: T,
- invoke: RemoteInvoke,
- deviceIdForSession: (sessionId: string) => string | undefined,
- targetDeviceId: string,
-): Promise<T> {
- const refs = extractMobileSessionReferences(item.text, deviceIdForSession, item.sessionRefs);
+): T {
const prepared = { ...item };
delete prepared.sessionRefs;
delete prepared.trustedSessionReferenceContexts;
delete prepared.sessionReferencesRequireTrustedSnapshot;
- if (refs.length === 0) return prepared;
+ return prepared;
+}
+
+function warnMobileSessionReferenceFallback(
+ phase: 'target-capability' | 'source-resolution' | 'stored-snapshot',
+ error: unknown,
+): void {
+ console.warn('[session-references] trusted history unavailable; preserving raw link text', {
+ phase,
+ code: error instanceof MobileSessionReferenceError ? error.code : 'UNKNOWN',
+ });
+}
+
+async function assertMobileTargetSessionReferenceCapability(
+ invoke: RemoteInvoke,
+ targetDeviceId: string,
+): Promise<void> {
try {
const capability = await invoke<unknown>(
targetDeviceId,
@@ -847,9 +859,45 @@ export async function prepareMobileQueuedSessionReferences<T extends MobileQueue
`The target device is unavailable: ${error instanceof Error ? error.message : String(error)}`,
);
}
- prepared.sessionRefs = refs;
- prepared.trustedSessionReferenceContexts = await resolveMobileSessionReferences(refs, invoke);
- return prepared;
+}
+
+/**
+ * Prepare optional trusted history for a queued mobile message.
+ *
+ * A session link may point at another account or an unavailable device. In
+ * that case the safe fallback is the already-present raw link text: omit all
+ * trusted-reference side channels and let the Agent handle the link itself.
+ */
+export async function prepareMobileQueuedSessionReferences<T extends MobileQueuedReferenceCarrier>(
+ item: T,
+ invoke: RemoteInvoke,
+ deviceIdForSession: (sessionId: string) => string | undefined,
+ targetDeviceId: string,
+): Promise<T> {
+ const refs = extractMobileSessionReferences(item.text, deviceIdForSession, item.sessionRefs);
+ const prepared = stripMobileSessionReferenceSideChannels(item);
+ if (refs.length === 0) return prepared;
+ try {
+ await assertMobileTargetSessionReferenceCapability(invoke, targetDeviceId);
+ } catch (error) {
+ if (!(error instanceof MobileSessionReferenceError) ||
+ error.code !== 'SESSION_REFERENCE_UNSUPPORTED') {
+ throw error;
+ }
+ warnMobileSessionReferenceFallback('target-capability', error);
+ return prepared;
+ }
+ try {
+ const contexts = await resolveMobileSessionReferences(refs, invoke);
+ return {
+ ...prepared,
+ sessionRefs: refs,
+ trustedSessionReferenceContexts: contexts,
+ };
+ } catch (error) {
+ warnMobileSessionReferenceFallback('source-resolution', error);
+ return prepared;
+ }
}
/** Reuse the target's trusted snapshot only when the source cannot currently be read. */
@@ -867,15 +915,32 @@ export async function prepareMobileQueuedSessionReferencesForSteer<T extends Mob
deviceIdForSession: (sessionId: string) => string | undefined,
targetDeviceId: string,
): Promise<T> {
+ const refs = extractMobileSessionReferences(item.text, deviceIdForSession, item.sessionRefs);
+ const prepared = stripMobileSessionReferenceSideChannels(item);
+ if (refs.length === 0) return prepared;
try {
- return await prepareMobileQueuedSessionReferences(
- item,
- invoke,
- deviceIdForSession,
- targetDeviceId,
- );
+ await assertMobileTargetSessionReferenceCapability(invoke, targetDeviceId);
+ } catch (error) {
+ if (!(error instanceof MobileSessionReferenceError) ||
+ error.code !== 'SESSION_REFERENCE_UNSUPPORTED') {
+ throw error;
+ }
+ warnMobileSessionReferenceFallback('target-capability', error);
+ return prepared;
+ }
+ try {
+ const contexts = await resolveMobileSessionReferences(refs, invoke);
+ return {
+ ...prepared,
+ sessionRefs: refs,
+ trustedSessionReferenceContexts: contexts,
+ };
} catch (error) {
- if (!canFallbackToStoredMobileSessionReferenceSnapshot(error)) throw error;
- return item;
+ if (canFallbackToStoredMobileSessionReferenceSnapshot(error)) {
+ warnMobileSessionReferenceFallback('stored-snapshot', error);
+ return item;
+ }
+ warnMobileSessionReferenceFallback('source-resolution', error);
+ return prepared;
}
}