Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(sharing): separate task scope from physical device addresses
DavidShen87001406d11d
diff --git a/apps/desktop/src/main/device-link/__tests__/dispatchWeakNetwork.test.ts b/apps/desktop/src/main/device-link/__tests__/dispatchWeakNetwork.test.tsindex a37ec6befc..ed48448c92 100644--- a/apps/desktop/src/main/device-link/__tests__/dispatchWeakNetwork.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/dispatchWeakNetwork.test.ts@@ -1,3 +1,4 @@+import { sharedTaskGuestPeer } from '@cindy/device-link';/*** dispatchWeakNetwork.test.ts — 被控端弱网收尾行为契约。* -------------------------------------------------------------------------@@ -247,7 +248,7 @@ describe('[1] link-accept 发送失败的有限重试', () => {it('refreshes first-join authority and ignores an older failed open after a newer success', async () => {const client = mkClient();__testing.setActiveClient(client as never);- const peer = 'shared-task~m~guest~g~d';+ const peer = sharedTaskGuestPeer('m', 'g', 'd');const payload = { controllerName: 'Guest', protocolVersion: PROTOCOL_VERSION, appVersion: '0.0.0-test', capabilities: [SHARED_TASK_CAPABILITY] };let rejectOld!: (error: Error) => void;sharedTask.capture.mockReturnValue({ author: { displayName: 'Guest' } });diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskDispatch.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskDispatch.test.tsindex 93c8734de0..87119598df 100644--- a/apps/desktop/src/main/device-link/__tests__/sharedTaskDispatch.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskDispatch.test.ts@@ -1,3 +1,4 @@+import { sharedTaskGuestPeer } from '@cindy/device-link';import { afterEach, describe, expect, it } from 'vitest';import { assertSharedTaskInvoke, assertSharedTaskReferences, captureSharedTaskPush, setSharedTaskQueueReader, type SharedTaskPeerCapture } from '../sharedTaskDispatch.js';@@ -80,7 +81,7 @@ describe('sharedTask dispatch scope', () => {});it('rejects expired captured authorization and unbound sharedTask pushes without changing same-account traffic', () => {expect(() => assertSharedTaskInvoke({ ...capture(), isCurrent: () => false }, { channel: 'local-db:messages:list', args: ['task'] })).toThrow();- expect(captureSharedTaskPush('shared-task~m~guest~g~d', 'maker:event', { sessionId: 'task' })).toBeNull();+ expect(captureSharedTaskPush(sharedTaskGuestPeer('m', 'g', 'd'), 'maker:event', { sessionId: 'task' })).toBeNull();expect(captureSharedTaskPush('my-phone', 'maker:provider:changed', {})?.()).toBe(true);});});diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskHost.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskHost.test.tsindex c7e7ca5c5e..051810986f 100644--- a/apps/desktop/src/main/device-link/__tests__/sharedTaskHost.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskHost.test.ts@@ -1,3 +1,5 @@+import { sharedTaskHostPeer } from '@cindy/device-link';+import { sharedTaskGuestPeer } from '@cindy/device-link';import { beforeEach, describe, expect, it, vi } from 'vitest';import { createSharedTaskApi, parseSharedTaskSnapshot, type SharedTaskDetail } from '@cindy/device-link';import type { SharedTaskJournalEntry } from '../../localDb/sharedTasks.js';@@ -62,7 +64,7 @@ describe('task host sharedTask lifecycle', () => {it('waits for archive durability and server closure before creating a fresh share', async () => {await host.open('session');- const oldCapture = host.capturePeer('shared-task~sharedTask~guest~member-a~phone-a')!;+ const oldCapture = host.capturePeer(sharedTaskGuestPeer('sharedTask', 'member-a', 'phone-a'))!;let finishRefresh!: (value: SharedTaskDetail) => void;api.get.mockImplementationOnce(() => new Promise<SharedTaskDetail>((resolve) => { finishRefresh = resolve; }));const refresh = host.refresh('sharedTask');@@ -96,7 +98,7 @@ describe('task host sharedTask lifecycle', () => {expect(oldCapture.isCurrent()).toBe(false);expect(records.get('sharedTask')?.terminal).toBe(true);expect(records.get('fresh-sharedTask')?.terminal).toBe(false);- expect(host.capturePeer('shared-task~fresh-sharedTask~guest~member-a~phone-a')?.isCurrent()).toBe(true);+ expect(host.capturePeer(sharedTaskGuestPeer('fresh-sharedTask', 'member-a', 'phone-a'))?.isCurrent()).toBe(true);});it('keeps an old open fenced when the restored task is already sharing again', async () => {@@ -153,7 +155,7 @@ describe('task host sharedTask lifecycle', () => {serverDetail = { ...detail(), sharedTaskId: 'fresh' };await expect(host.open('session')).resolves.toBe('fresh');expect(api.close).toHaveBeenCalledTimes(2);- expect(host.capturePeer('shared-task~sharedTask~guest~member-a~phone-a')).toBeNull();+ expect(host.capturePeer(sharedTaskGuestPeer('sharedTask', 'member-a', 'phone-a'))).toBeNull();});it.each([undefined, 'session'])('drains creates from a retired same-profile host at boundary (%s)', async (sessionId) => {@@ -176,7 +178,7 @@ describe('task host sharedTask lifecycle', () => {expect(await closing).toEqual(['late-sharedTask']);await rejected;expect(records.get('late-sharedTask')?.terminal).toBe(true);- expect(replacement.capturePeer('shared-task~late-shared-task~guest~member-a~phone-a')).toBeNull();+ expect(replacement.capturePeer(sharedTaskGuestPeer('late-shared-task', 'member-a', 'phone-a'))).toBeNull();});it.each([undefined, 'session'])('drains a late committed create before releasing the outgoing profile (%s)', async (sessionId) => {let reply!: (value: unknown) => void;@@ -233,7 +235,7 @@ describe('task host sharedTask lifecycle', () => {release();await expect(refreshing).rejects.toThrow('closed');expect(canRead()).toBe(false);- expect(host.capturePeer('shared-task~sharedTask~guest~member-a~phone-a')).toBeNull();+ expect(host.capturePeer(sharedTaskGuestPeer('sharedTask', 'member-a', 'phone-a'))).toBeNull();});it('durably closes the outgoing profile after its network generation is fenced', async () => {await host.open('session');@@ -246,7 +248,7 @@ describe('task host sharedTask lifecycle', () => {const restored = new SharedTaskHost(options);await restored.restore();expect(api.close).toHaveBeenCalledWith('sharedTask');- expect(restored.capturePeer('shared-task~sharedTask~guest~member-a~phone-a')).toBeNull();+ expect(restored.capturePeer(sharedTaskGuestPeer('sharedTask', 'member-a', 'phone-a'))).toBeNull();});it('closes only the archived task and propagates a journal failure', async () => {@@ -260,10 +262,10 @@ describe('task host sharedTask lifecycle', () => {});it('invalidates old captures without revoking existing devices when a member adds a device', async () => {await host.open('session');- expect(host.capturePeer('shared-task~sharedTask~host')).toBeNull();- expect(host.capturePeer('shared-task~sharedTask~guest~member-a~phone-b')).toBeNull();- const a = host.capturePeer('shared-task~sharedTask~guest~member-a~phone-a')!;- const b = host.capturePeer('shared-task~sharedTask~guest~member-b~phone-b')!;+ expect(host.capturePeer(sharedTaskHostPeer('sharedTask', 'desktop'))).toBeNull();+ expect(host.capturePeer(sharedTaskGuestPeer('sharedTask', 'member-a', 'phone-b'))).toBeNull();+ const a = host.capturePeer(sharedTaskGuestPeer('sharedTask', 'member-a', 'phone-a'))!;+ const b = host.capturePeer(sharedTaskGuestPeer('sharedTask', 'member-b', 'phone-b'))!;expect(a.author.accountId).toBe('guest-a');expect(a.isCurrent()).toBe(true);serverDetail = { ...detail(2), guests: detail().guests.map((member) => member.memberId === 'member-a' ? { ...member, version: 2, deviceIds: [...member.deviceIds, 'second-phone'] } : member) };@@ -271,8 +273,8 @@ describe('task host sharedTask lifecycle', () => {expect(a.isCurrent()).toBe(false);expect(b.isCurrent()).toBe(true);expect(options.revoke).not.toHaveBeenCalled();- expect(host.capturePeer('shared-task~sharedTask~guest~member-a~phone-a')?.isCurrent()).toBe(true);- expect(host.capturePeer('shared-task~sharedTask~guest~member-a~second-phone')?.isCurrent()).toBe(true);+ expect(host.capturePeer(sharedTaskGuestPeer('sharedTask', 'member-a', 'phone-a'))?.isCurrent()).toBe(true);+ expect(host.capturePeer(sharedTaskGuestPeer('sharedTask', 'member-a', 'second-phone'))?.isCurrent()).toBe(true);await host.dispose();expect(b.isCurrent()).toBe(false);});@@ -338,7 +340,7 @@ describe('task host sharedTask lifecycle', () => {await host.refresh('sharedTask');expect(canRead()).toBe(true);expect(options.revoke).not.toHaveBeenCalled();- expect(host.capturePeer('shared-task~sharedTask~guest~member-a~phone-a')?.isCurrent()).toBe(true);+ expect(host.capturePeer(sharedTaskGuestPeer('sharedTask', 'member-a', 'phone-a'))?.isCurrent()).toBe(true);});it('closes locally before awaiting the server and retries durable closure after restart', async () => {await host.open('session');diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskPush.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskPush.test.tsindex e77e546e1f..af9e8fe463 100644--- a/apps/desktop/src/main/device-link/__tests__/sharedTaskPush.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskPush.test.ts@@ -1,3 +1,4 @@+import { sharedTaskGuestPeer } from '@cindy/device-link';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { DL_SUBSCRIBE_CHANNEL } from '@cindy/device-link';@@ -15,8 +16,8 @@ import * as subscriptions from '../subscriptions';import { setSharedTaskDispatchHost } from '../sharedTaskDispatch';import type { SharedTaskHost } from '../sharedTaskHost';-const guestA = 'shared-task~sharedTask-a~guest~member-a~device-a';-const guestB = 'shared-task~sharedTask-b~guest~member-b~device-b';+const guestA = sharedTaskGuestPeer('sharedTask-a', 'member-a', 'device-a');+const guestB = sharedTaskGuestPeer('sharedTask-b', 'member-b', 'device-b');const grants = new Map<string, string>();const metadata = [['local-db:sessions:created', { sessionId: 'task-a' }],diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskTransientAccess.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskTransientAccess.test.tsindex 5c89081442..a19cc25510 100644--- a/apps/desktop/src/main/device-link/__tests__/sharedTaskTransientAccess.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskTransientAccess.test.ts@@ -1,3 +1,4 @@+import { sharedTaskGuestPeer } from '@cindy/device-link';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { PROTOCOL_VERSION, SHARED_TASK_CAPABILITY, type SharedTaskDetail } from '@cindy/device-link';@@ -16,7 +17,7 @@ import { SharedTaskHost } from '../sharedTaskHost';import { setSharedTaskDispatchHost } from '../sharedTaskDispatch';import type { SharedTaskJournalEntry } from '../../localDb/sharedTasks';-const peer = 'shared-task~sharedTask~guest~member~phone';+const peer = sharedTaskGuestPeer('sharedTask', 'member', 'phone');const read = { channel: 'local-db:messages:list', args: ['task'] };const subscribe = { channel: 'device-link:subscribe', args: [{ topics: ['session:task'] }] };let detail: SharedTaskDetail;@@ -127,7 +128,7 @@ describe('shared task temporary authority fences preserve membership', () => {});it('treats unrestored or replaced host authority as unavailable rather than revoked', async () => {- expect(host.peerStatus('shared-task~unknown~guest~member~phone')).toBe('unavailable');+ expect(host.peerStatus(sharedTaskGuestPeer('unknown', 'member', 'phone'))).toBe('unavailable');setSharedTaskDispatchHost(null);expect(await runInvoke(peer, read)).toMatchObject({ ok: false, error: { code: 'NOT_CONNECTED' } });});diff --git a/apps/desktop/src/renderer/__tests__/cindyMakeInlineEntry.test.ts b/apps/desktop/src/renderer/__tests__/cindyMakeInlineEntry.test.tsindex d1a07f7d75..1a2c2bb2c8 100644--- a/apps/desktop/src/renderer/__tests__/cindyMakeInlineEntry.test.ts+++ b/apps/desktop/src/renderer/__tests__/cindyMakeInlineEntry.test.ts@@ -1,3 +1,4 @@+import { sharedTaskHostPeer } from '@cindy/device-link';import { readFileSync } from 'node:fs';import { resolve } from 'node:path';import { describe, expect, it } from 'vitest';@@ -43,11 +44,11 @@ describe('Cindy Make composer presentation', () => {'pendingIssueConfirm', 'pendingRenameSessionsConfirm', 'pendingGhostGrantConfirm'];const hidesComposer = new Function('isSharedTaskPeer', 'remoteDeviceId', ...prompts,`return Boolean(${condition!.getText(ast)});`);- for (const deviceId of [undefined, 'own-device', 'shared-task~m~host']) {+ for (const deviceId of [undefined, 'own-device', sharedTaskHostPeer('m', 'desktop')]) {expect(hidesComposer(isSharedTaskPeer, deviceId, ...prompts.map(() => false))).toBe(false);for (const active of prompts) {expect(hidesComposer(isSharedTaskPeer, deviceId, ...prompts.map((name) => name === active)),- `${deviceId ?? 'local'}: ${active}`).toBe(deviceId !== 'shared-task~m~host');+ `${deviceId ?? 'local'}: ${active}`).toBe(deviceId !== sharedTaskHostPeer('m', 'desktop'));}}expect(sessionView).toContain('if (cindyMakeInputLocked) return false;');diff --git a/apps/desktop/src/renderer/__tests__/machineSwitcher.test.ts b/apps/desktop/src/renderer/__tests__/machineSwitcher.test.tsindex f4a1159ecf..9e46ecf084 100644--- a/apps/desktop/src/renderer/__tests__/machineSwitcher.test.ts+++ b/apps/desktop/src/renderer/__tests__/machineSwitcher.test.ts@@ -1,3 +1,4 @@+import { sharedTaskHostPeer } from '@cindy/device-link';import { afterEach, describe, expect, it } from 'vitest';import type { Session } from '@/lib/ccAgent.types';@@ -52,7 +53,7 @@ function mkSession(id: string, deviceLinkDeviceId?: string): Session {}it('never lists shared-task peers as devices, including disconnected and rejected peers', () => {- const peer = 'shared-task~share-1~host';+ const peer = sharedTaskHostPeer('share-1', 'desktop');expect(buildSwitcherDevices({fullList: [mkDevice('real-pc'), mkDevice(peer)],syncedDevices: [{ deviceId: peer, deviceName: 'Shared task', sessionCount: 1, connected: false }],diff --git a/apps/desktop/src/renderer/__tests__/remoteDataOwnerPushFence.test.ts b/apps/desktop/src/renderer/__tests__/remoteDataOwnerPushFence.test.tsindex 366ac3912b..91a688d74e 100644--- a/apps/desktop/src/renderer/__tests__/remoteDataOwnerPushFence.test.ts+++ b/apps/desktop/src/renderer/__tests__/remoteDataOwnerPushFence.test.ts@@ -1,9 +1,10 @@+import { sharedTaskGuestPeer } from '@cindy/device-link';import { beforeEach, describe, expect, it } from 'vitest';import { sharedTaskHostPeer } from '@cindy/device-link';import { setDataOwnerGeneration } from '../contexts/dataOwnerGeneration';import { bindSharedTaskPushOwner, isDeviceLinkRemotePushCurrent, isRemoteDataOwnerPushCurrent, resetRemoteDataOwnerPushFence } from '../lib/remoteDataOwnerPushFence';-const peer = sharedTaskHostPeer('shared-task');+const peer = sharedTaskHostPeer('shared-task', 'desktop');const hostStamp = { dataOwnerId: 'host-account', ownerGeneration: 4 };const localStamp = { dataOwnerId: 'guest-account', ownerGeneration: 2 };@@ -30,7 +31,7 @@ describe('shared task push owner', () => {});it('never resets an unrelated peer or accepts an epoch from a stale account', () => {- const other = sharedTaskHostPeer('other-task');+ const other = sharedTaskHostPeer('other-task', 'desktop');bindSharedTaskPushOwner(peer, 'host-account');bindSharedTaskPushOwner(other, 'host-account');const push = { deviceId: peer, ownerStamp: hostStamp, sourceEpoch: 1 };@@ -60,7 +61,7 @@ describe('shared task push owner', () => {expect(isRemoteDataOwnerPushCurrent(peer, undefined)).toBe(false);expect(isRemoteDataOwnerPushCurrent(peer, null)).toBe(false);expect(isRemoteDataOwnerPushCurrent(peer, {})).toBe(false);- expect(isRemoteDataOwnerPushCurrent('shared-task~shared-task~guest~member~device', hostStamp)).toBe(false);+ expect(isRemoteDataOwnerPushCurrent(sharedTaskGuestPeer('shared-task', 'member', 'device'), hostStamp)).toBe(false);});it('invalidates bindings when the local account or generation changes', () => {@@ -86,7 +87,7 @@ describe('shared task push owner', () => {});it('rejects delayed frames after removal, without affecting another shared task', () => {- const other = sharedTaskHostPeer('other-task');+ const other = sharedTaskHostPeer('other-task', 'desktop');bindSharedTaskPushOwner(peer, 'host-account');bindSharedTaskPushOwner(other, 'host-account');resetRemoteDataOwnerPushFence(peer);diff --git a/apps/desktop/src/renderer/features/device-link/JoinSharedTaskDialog.tsx b/apps/desktop/src/renderer/features/device-link/JoinSharedTaskDialog.tsxindex d34e37df96..331823a40a 100644--- a/apps/desktop/src/renderer/features/device-link/JoinSharedTaskDialog.tsx+++ b/apps/desktop/src/renderer/features/device-link/JoinSharedTaskDialog.tsx@@ -86,7 +86,7 @@ export function JoinSharedTaskDialog({ open, onOpenChange }: { open: boolean; onconst openTask = () => void run(async (current) => {const detail = await window.electronAPI.sharedTask.account({ action: 'get', sharedTaskId: request!.sharedTaskId }) as SharedTaskDetail;if (!current()) return;- const peer = sharedTaskHostPeer(detail.sharedTaskId);+ const peer = sharedTaskHostPeer(detail.sharedTaskId, detail.hostDeviceId);bindSharedTaskPushOwner(peer, detail.ownerAccountId);await window.electronAPI.deviceLink.openLink(peer);if (!current()) return;diff --git a/apps/desktop/src/renderer/features/device-link/__tests__/JoinSharedTaskDialog.test.tsx b/apps/desktop/src/renderer/features/device-link/__tests__/JoinSharedTaskDialog.test.tsxindex 72cbd5835f..3809014f53 100644--- a/apps/desktop/src/renderer/features/device-link/__tests__/JoinSharedTaskDialog.test.tsx+++ b/apps/desktop/src/renderer/features/device-link/__tests__/JoinSharedTaskDialog.test.tsx@@ -1,3 +1,4 @@+import { sharedTaskHostPeer } from '@cindy/device-link';// @vitest-environment jsdomimport { createElement } from 'react';import { render, screen, fireEvent, waitFor, cleanup, within, act } from '@testing-library/react';@@ -15,7 +16,7 @@ beforeEach(() => {vi.clearAllMocks(); setDataOwnerGeneration('guest');state.account.mockImplementation(async ({ action }) => action === 'owned' ? [] : action === 'join'? { sharedTaskId: 'share-1', memberId: 'member-1', status: 'joined' }- : { sharedTaskId: 'share-1', sessionId: 'task-1', ownerAccountId: 'host', title: 'Test Task', status: 'active' });+ : { sharedTaskId: 'share-1', sessionId: 'task-1', ownerAccountId: 'host', hostDeviceId: 'desktop', title: 'Test Task', status: 'active' });state.invoke.mockResolvedValue({ id: 'task-1' });Object.assign(window, { electronAPI: { sharedTask: { account: state.account }, deviceLink: { openLink: state.openLink, invoke: state.invoke } } });});@@ -100,7 +101,7 @@ it('shows the joined task before entering through the existing remote link', asyexpect(state.openLink).not.toHaveBeenCalled();fireEvent.click(screen.getByRole('button', { name: 'sharedTask.enterTask' }));await waitFor(() => expect(close).toHaveBeenCalledWith(false));- expect(state.invoke).toHaveBeenCalledWith('shared-task~share-1~host', 'local-db:sessions:get', ['task-1']);+ expect(state.invoke).toHaveBeenCalledWith(sharedTaskHostPeer('share-1', 'desktop'), 'local-db:sessions:get', ['task-1']);});it('lets a newly joined visitor cancel leaving, then leave with confirmation', async () => {open(); fill(); await screen.findByText('sharedTask.joinedTitle:Test Task');diff --git a/apps/desktop/src/renderer/features/device-link/__tests__/SharedTaskButton.test.tsx b/apps/desktop/src/renderer/features/device-link/__tests__/SharedTaskButton.test.tsxindex d42d5deaa6..81e9fc9177 100644--- a/apps/desktop/src/renderer/features/device-link/__tests__/SharedTaskButton.test.tsx+++ b/apps/desktop/src/renderer/features/device-link/__tests__/SharedTaskButton.test.tsx@@ -146,7 +146,7 @@ it('shows the host-offline ending for a guest whose share closed', async () => {state.account.mockImplementation((command: { action: string }) => command.action === 'get'? Promise.resolve({ ...detail, status: 'closed' }): Promise.resolve([]));- const body = await openWindow({ id: 'session-1', deviceLinkDeviceId: sharedTaskHostPeer('st1') } as Session);+ const body = await openWindow({ id: 'session-1', deviceLinkDeviceId: sharedTaskHostPeer('st1', 'desktop') } as Session);await waitFor(() => expect(body.textContent).toContain('sharedTask.hostOfflineTitle'));expect(body.textContent).toContain('sharedTask.hostOfflineBody');expect(body.textContent).not.toContain('sharedTask.leave');diff --git a/apps/desktop/src/renderer/features/device-link/__tests__/SharedTaskEndedNotice.test.tsx b/apps/desktop/src/renderer/features/device-link/__tests__/SharedTaskEndedNotice.test.tsxindex 05e6dc5260..570725e7b7 100644--- a/apps/desktop/src/renderer/features/device-link/__tests__/SharedTaskEndedNotice.test.tsx+++ b/apps/desktop/src/renderer/features/device-link/__tests__/SharedTaskEndedNotice.test.tsx@@ -15,7 +15,7 @@ it('keeps ordinary remote exits unchanged and offers a new invitation after a shrender(<SharedTaskEndedNotice onJoin={onJoin} />);act(() => { expect(notifySharedTaskEnded('ordinary-device')).toBe(false); });expect(screen.queryByRole('dialog')).toBeNull();- act(() => { expect(notifySharedTaskEnded(sharedTaskHostPeer('share-1'))).toBe(true); });+ act(() => { expect(notifySharedTaskEnded(sharedTaskHostPeer('share-1', 'desktop'))).toBe(true); });expect(screen.getByRole('dialog').textContent).toContain('sharedTask.accessEndedBody');fireEvent.click(screen.getByRole('button', { name: 'sharedTask.rejoin' }));expect(onJoin).toHaveBeenCalledOnce();@@ -25,7 +25,7 @@ it('keeps ordinary remote exits unchanged and offers a new invitation after a shit('does not keep an ending notice visible across an account boundary', () => {const onJoin = vi.fn();const view = render(<SharedTaskEndedNotice onJoin={onJoin} />);- act(() => { notifySharedTaskEnded(sharedTaskHostPeer('share-1')); });+ act(() => { notifySharedTaskEnded(sharedTaskHostPeer('share-1', 'desktop')); });expect(screen.getByRole('dialog')).toBeTruthy();setDataOwnerGeneration('other');view.rerender(<SharedTaskEndedNotice onJoin={onJoin} />);diff --git a/apps/desktop/src/renderer/features/device-link/__tests__/SharedTasksSection.test.tsx b/apps/desktop/src/renderer/features/device-link/__tests__/SharedTasksSection.test.tsxindex 1d3646fa6f..4da103cc85 100644--- a/apps/desktop/src/renderer/features/device-link/__tests__/SharedTasksSection.test.tsx+++ b/apps/desktop/src/renderer/features/device-link/__tests__/SharedTasksSection.test.tsx@@ -1,3 +1,4 @@+import { sharedTaskHostPeer } from '@cindy/device-link';// @vitest-environment jsdomimport { render, screen, fireEvent, cleanup, waitFor, act } from '@testing-library/react';import { afterEach, beforeEach, expect, it, vi } from 'vitest';@@ -13,7 +14,7 @@ vi.mock('../remoteProjectsStore', () => ({useRemoteProjectSessions: () => state.sessions, isRemoteDeviceMarkedDisconnected: () => false,remoteProjectsStore: { pinSessionOrigin: state.pin },}));-const guestTask = { id: 'joined-1', title: 'Joined task', deviceLinkDeviceId: 'shared-task~share-1~host' } as Session;+const guestTask = { id: 'joined-1', title: 'Joined task', deviceLinkDeviceId: sharedTaskHostPeer('share-1', 'desktop') } as Session;beforeEach(() => {vi.clearAllMocks(); setDataOwnerGeneration('guest');state.sessions = [guestTask, { id: 'own-device-task', title: 'Own device task', deviceLinkDeviceId: 'my-computer' } as Session];diff --git a/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts b/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.tsindex b7942d38ce..d79b73da5a 100644--- a/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts+++ b/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts@@ -33,6 +33,7 @@ import { evictTaskTagCatalog } from '../task-tags/taskTagEvents';*/import { useEffect, useRef } from 'react';+import { isSharedTaskPeer } from '@cindy/device-link';import { useAuth } from '@/contexts/AuthContext';import { isDeviceLinkRemotePushCurrent } from '@/lib/remoteDataOwnerPushFence';import { createLogger } from '@/lib/logger';@@ -590,7 +591,7 @@ export function useDeviceLinkRemoteProjects(const authoritative = new Set(devices.map((d) => d.deviceId));for (const deviceId of remoteProjectsStore.getAllDeviceIds()) {// SharedTask shards are reconciled against membership, not the own-device directory.- if (deviceId.startsWith('shared-task~')) continue;+ if (isSharedTaskPeer(deviceId)) continue;if (authoritative.has(deviceId) || eligible.has(deviceId)) continue;log.debug(`removing cached shard absent from listDevices: ${deviceId.slice(0, 8)}`);clearArchivedSessionRetry(deviceId);diff --git a/apps/desktop/src/renderer/features/device-link/useSharedTaskTasks.ts b/apps/desktop/src/renderer/features/device-link/useSharedTaskTasks.tsindex 88371e7730..6d8cfcb725 100644--- a/apps/desktop/src/renderer/features/device-link/useSharedTaskTasks.ts+++ b/apps/desktop/src/renderer/features/device-link/useSharedTaskTasks.ts@@ -23,7 +23,7 @@ export function useSharedTaskTasks(): void {try {const sharedTasks = await window.electronAPI.sharedTask.account({ action: 'list' }) as SharedTaskListItem[];if (!currentOwner()) return;- const current = new Set(sharedTasks.map((sharedTask) => sharedTaskHostPeer(sharedTask.sharedTaskId)));+ const current = new Set(sharedTasks.map((sharedTask) => sharedTaskHostPeer(sharedTask.sharedTaskId, sharedTask.hostDeviceId)));for (const id of remoteProjectsStore.getAllDeviceIds()) {if (!parseSharedTaskPeer(id) || current.has(id)) continue;linked.delete(id);@@ -33,7 +33,7 @@ export function useSharedTaskTasks(): void {}for (const sharedTask of sharedTasks) {if (!currentOwner()) return;- const peer = sharedTaskHostPeer(sharedTask.sharedTaskId);+ const peer = sharedTaskHostPeer(sharedTask.sharedTaskId, sharedTask.hostDeviceId);bindSharedTaskPushOwner(peer, sharedTask.ownerAccountId);try {if (!linked.has(peer)) {diff --git a/apps/mobile/app/shared-session.tsx b/apps/mobile/app/shared-session.tsxindex 7c0b50593e..8bd1ba70ce 100644--- a/apps/mobile/app/shared-session.tsx+++ b/apps/mobile/app/shared-session.tsx@@ -54,18 +54,20 @@ export default function SharedSessionScreen() {const epoch = useRef(0);const peer = deviceId ? parseSharedTaskPeer(deviceId) : null;const guestId = peer?.role === 'host' ? peer.sharedTaskId : joinedId;+ const guestTarget = peer?.role === 'host' ? deviceId+ : guestId && state?.detail ? sharedTaskHostPeer(guestId, state.detail.hostDeviceId) : undefined;const hostContext = !!sessionId && !!deviceId && !guestId;const host = useCallback((command: SharedTaskHostCommand) => link.invoke(deviceId!, SHARED_TASK_HOST_CHANNEL, [command]), [deviceId, link.invoke]);const endAccess = useCallback(() => {confirmationPending.current = null;setEnded(true); setState(null); setNotice('');- if (guestId) {- const target = sharedTaskHostPeer(guestId);+ if (guestTarget) {+ const target = guestTarget;markDeviceAccessRevoked(target);link.closeLink(target);remoteSessionStore.removeDevice(target);}- }, [guestId, link.closeLink]);+ }, [guestTarget, link.closeLink]);const load = useCallback(async (visible: () => boolean = () => true) => {const captured = epoch.current;const owner = getMobileAuthOwner();@@ -174,7 +176,7 @@ export default function SharedSessionScreen() {const detail = await api.get(id);if (!current()) return;if (detail.status !== 'active') { endAccess(); return; }- const target = sharedTaskHostPeer(id);+ const target = sharedTaskHostPeer(id, detail.hostDeviceId);await link.openLink(target);if (!current()) return;const task = await link.invoke<RemoteSession>(target, 'local-db:sessions:get', [detail.sessionId]);@@ -200,8 +202,8 @@ export default function SharedSessionScreen() {const leave = () => confirm(t('sharedTask.leaveTitle'), t('sharedTask.leaveBody'), t('sharedTask.leaveKeep'), t('sharedTask.leave'), async (current) => {await api.leave(guestId!);if (!current()) return;- const target = sharedTaskHostPeer(guestId!);- link.closeLink(target); remoteSessionStore.removeDevice(target); router.replace('/devices');+ if (guestTarget) { link.closeLink(guestTarget); remoteSessionStore.removeDevice(guestTarget); }+ router.replace('/devices');}, false);const taskCard = <View style={styles.taskRow}><FileText size={iconSize.md} color={colors.textTertiary} /><View style={styles.grow}><Text style={styles.taskTitle}>{title}</Text><Text style={styles.metadata}>{task?.deviceLinkDeviceName ?? t('sharedTask.runsOnHostDevice')}</Text></View></View>;return <SharedTaskScreendiff --git a/apps/mobile/src/__tests__/SessionMenuContextEntry.test.tsx b/apps/mobile/src/__tests__/SessionMenuContextEntry.test.tsxindex ae7a29d99f..985632f4f6 100644--- a/apps/mobile/src/__tests__/SessionMenuContextEntry.test.tsx+++ b/apps/mobile/src/__tests__/SessionMenuContextEntry.test.tsx@@ -142,7 +142,7 @@ it("reopening the primary menu after info does not initialize an engine, but entexpect(props.onOpenSearch).toHaveBeenCalledOnce();const sharing = host.querySelector('[data-testid="session.sharingButton"]');expect(sharing?.textContent).toBe('共享任务');- await act(async () => root.render(<SessionMenuSheet {...props} initialView="menu" session={{ ...props.session, deviceLinkDeviceId: sharedTaskHostPeer('shared') }} />));+ await act(async () => root.render(<SessionMenuSheet {...props} initialView="menu" session={{ ...props.session, deviceLinkDeviceId: sharedTaskHostPeer('shared', 'desktop') }} />));expect(host.querySelector('[data-testid="session.sharingButton"]')).toBeNull();const leave = host.querySelector('[data-testid="session.leaveSharingButton"]');expect(leave?.textContent).toBe('退出共享任务');diff --git a/apps/mobile/src/__tests__/connectionBannerVisibility.test.ts b/apps/mobile/src/__tests__/connectionBannerVisibility.test.tsindex 9c405124d8..2be8c669f3 100644--- a/apps/mobile/src/__tests__/connectionBannerVisibility.test.ts+++ b/apps/mobile/src/__tests__/connectionBannerVisibility.test.ts@@ -17,7 +17,7 @@ const base = {};it('does not infer shared task disconnection from the account device list', () => {- const guest = { deviceId: sharedTaskHostPeer('shared'), sessionCount: 1, available: false };+ const guest = { deviceId: sharedTaskHostPeer('shared', 'desktop'), sessionCount: 1, available: false };const host = { deviceId: 'my-computer', sessionCount: 2, available: false };expect(resolveHomeDeviceDisconnected([guest], null, false)).toBe(false);expect(resolveHomeDeviceDisconnected([guest, host], guest.deviceId, false)).toBe(false);diff --git a/apps/mobile/src/__tests__/sharedTaskFlow.test.tsx b/apps/mobile/src/__tests__/sharedTaskFlow.test.tsxindex b4e9168b2b..5b6be9d337 100644--- a/apps/mobile/src/__tests__/sharedTaskFlow.test.tsx+++ b/apps/mobile/src/__tests__/sharedTaskFlow.test.tsx@@ -61,7 +61,7 @@ vi.mock('@/platform/chrome/SimpleStackHeader', () => ({ SimpleStackHeader: ({ tivi.mock('@/theme', () => ({ useTheme: () => ({ colors: {} }), useThemedStyles: () => ({}) }));let element: HTMLDivElement;let root: Root;-const detail = { sharedTaskId: 'shared', sessionId: 'task', status: 'active', title: 'Design review', memberLabels: [{ memberId: 'member', displayName: 'Guest' }] };+const detail = { sharedTaskId: 'shared', sessionId: 'task', hostDeviceId: 'desktop', status: 'active', title: 'Design review', memberLabels: [{ memberId: 'member', displayName: 'Guest' }] };const owned = (id: string) => ({ sharedTaskId: id, sessionId: 'task', title: id, ownerAccountId: 'owner', hostDeviceId: 'host' });async function render() { await act(async () => root.render(createElement(SharedSessionScreen))); }async function click(label: string) {@@ -97,12 +97,12 @@ it('uses a multiline invitation and stops at the joined screen before opening thexpect(h.link.openLink).not.toHaveBeenCalled();h.link.invoke.mockResolvedValue({ id: 'task' });await click('sharedTask.enterTask');- expect(h.link.invoke).toHaveBeenCalledWith(sharedTaskHostPeer('shared'), 'local-db:sessions:get', ['task']);+ expect(h.link.invoke).toHaveBeenCalledWith(sharedTaskHostPeer('shared', 'desktop'), 'local-db:sessions:get', ['task']);expect(h.router.replace).toHaveBeenCalledWith(expect.objectContaining({ pathname: '/sessions/[sessionId]' }));});it.each(['ios', 'android'] as const)('%s preserves the page on cancel and rejects an old account confirmation', async (platform) => {Platform.OS = platform;- h.params = { sessionId: 'task', deviceId: sharedTaskHostPeer('shared') }; await render();+ h.params = { sessionId: 'task', deviceId: sharedTaskHostPeer('shared', 'desktop') }; await render();const originalPage = element.innerHTML;await click('sharedTask.leave');expect(h.alert).toHaveBeenCalledTimes(1);@@ -135,7 +135,7 @@ it('replaces stale guest state only for confirmed membership loss and can join aawait act(async () => vi.advanceTimersByTimeAsync(5_000));expect(element.textContent).toContain('sharedTask.ended');expect(element.textContent).not.toContain('sharedTask.leave');- expect(h.revoked).toHaveBeenCalledWith(sharedTaskHostPeer('shared'));+ expect(h.revoked).toHaveBeenCalledWith(sharedTaskHostPeer('shared', 'desktop'));await act(async () => oldConfirm.onPress());expect(h.api.leave).not.toHaveBeenCalled();await click('sharedTask.rejoin'); expect(element.querySelector('textarea')).not.toBeNull();diff --git a/apps/mobile/src/__tests__/useLeaveSharedTask.test.tsx b/apps/mobile/src/__tests__/useLeaveSharedTask.test.tsxindex 5626e51c44..f3c748344d 100644--- a/apps/mobile/src/__tests__/useLeaveSharedTask.test.tsx+++ b/apps/mobile/src/__tests__/useLeaveSharedTask.test.tsx@@ -24,7 +24,7 @@ vi.mock('@/device-link/revokedDevicesStore', () => ({ revokedDevicesStore: { haslet root: Root;let host: HTMLDivElement;let resolveConfirm: (value: boolean) => void;-const peer = sharedTaskHostPeer('shared');+const peer = sharedTaskHostPeer('shared', 'desktop');function Harness({ enabled = true, deviceId = peer }) {const exit = useLeaveSharedTask({ deviceId, enabled, onLeft: h.left, onError: h.error });return <button disabled={exit.busy} onClick={() => void exit.leave()}>leave</button>;@@ -71,7 +71,7 @@ it.each(['account', 'menu', 'device', 'revoked'])('ignores confirmation after %sawait click();if (change === 'account') setMobileAuthOwner('other');if (change === 'menu') await act(async () => root.render(<Harness enabled={false} />));- if (change === 'device') await act(async () => root.render(<Harness deviceId={sharedTaskHostPeer('other')} />));+ if (change === 'device') await act(async () => root.render(<Harness deviceId={sharedTaskHostPeer('other', 'desktop')} />));if (change === 'revoked') h.revoked.mockReturnValue(true);await act(async () => resolveConfirm(true));expect(h.api.leave).not.toHaveBeenCalled(); expect(h.left).not.toHaveBeenCalled();diff --git a/apps/mobile/src/__tests__/useSessionResourceCards.test.tsx b/apps/mobile/src/__tests__/useSessionResourceCards.test.tsxindex 01b0b850e3..09ee94b34b 100644--- a/apps/mobile/src/__tests__/useSessionResourceCards.test.tsx+++ b/apps/mobile/src/__tests__/useSessionResourceCards.test.tsx@@ -141,7 +141,7 @@ function foreground(next: string) {});}it('does not discover host-wide cards or retry them for a shared-task guest', async () => {- const peer = sharedTaskHostPeer('shared-task');+ const peer = sharedTaskHostPeer('shared-task', 'desktop');root = createRoot(document.createElement('div'));await act(async () => root!.render(createElement(Probe, { device: peer })));expect(h.manifest).not.toHaveBeenCalled();diff --git a/apps/mobile/src/device-link/useSharedTasks.ts b/apps/mobile/src/device-link/useSharedTasks.tsindex e24d1a77e8..3d21424d57 100644--- a/apps/mobile/src/device-link/useSharedTasks.ts+++ b/apps/mobile/src/device-link/useSharedTasks.ts@@ -24,7 +24,7 @@ export function useSharedTasks(): void {try {const tasks = (await api.list()).filter((task) => task.ownerAccountId !== owner.accountId);if (!current()) return;- const peers = new Set(tasks.map((task) => sharedTaskHostPeer(task.sharedTaskId)));+ const peers = new Set(tasks.map((task) => sharedTaskHostPeer(task.sharedTaskId, task.hostDeviceId)));for (const task of remoteSessionStore.getSessions()) {const peer = task.deviceLinkDeviceId;if (peer && isSharedTaskPeer(peer) && !peers.has(peer)) {@@ -34,7 +34,7 @@ export function useSharedTasks(): void {}for (const task of tasks) {if (!current()) return;- const peer = sharedTaskHostPeer(task.sharedTaskId);+ const peer = sharedTaskHostPeer(task.sharedTaskId, task.hostDeviceId);try {await openLink(peer);if (!current()) return;diff --git a/docs/product-rules/shared-task-mode.md b/docs/product-rules/shared-task-mode.mdindex 8616914ff0..69f7bba49b 100644--- a/docs/product-rules/shared-task-mode.md+++ b/docs/product-rules/shared-task-mode.md@@ -59,7 +59,10 @@2026-09-18 用户确认:功能仍在开发,不维护旧共享协议和存储命名兼容层。客户端和服务端各自维护本仓协议包并同步更新;独立 cindy-protocol 仓不再被当前 workspace 消费。-- 类型与函数统一为 SharedTask / sharedTask,能力为 shared-task-v1,逻辑 peer 前缀为 shared-task~,REST 为 /api/device-link/shared-tasks,标识字段为 sharedTaskId,IPC 为 maker:shared-task / shared-task:account。普通同账号远控协议不变。+- 类型与函数统一为 SharedTask / sharedTask,能力为 shared-task-v2,REST 为 /api/device-link/shared-tasks,标识字段为 sharedTaskId,IPC 为 maker:shared-task / shared-task:account。共享是原任务的状态与授权关系,原 sessionId 不变。+- relay 的 src/dst 始终为真实设备 ID;可选 sharedTask 字段独立携带共享 ID 与目标角色/成员,来源角色/成员由服务端按已验证账号与设备重写。不带范围的帧沿用同账号远控,包括 ID 恰好带 shared-task~ 前缀的真实设备;非法范围直接拒绝,不能降级。+- 客户端仅在 relay 声明 v2 后发送共享帧,服务端还检查双方能力、任务状态、成员与真实目标设备绑定。先升级全部 relay 再发布客户端;不兼容未发布的共享 v1 开发版,已发布普通远控协议不变。+- 客户端缓存/IPC 使用包含共享范围的本地连接索引,长度大于物理设备 ID 的 128 字符上限,避免同设备普通连接与多个共享连接碰撞;索引不会进入 wire 的设备地址字段。请求、结果、ACK、重连与错误都按各自连接范围隔离,不扩大到其他任务或设备。实现与回归见 packages/device-link/src/sharedTaskEnvelope.ts、sharedTaskPeer.ts 及其测试。- SQLite 使用 shared_task_events / shared_task_id;Prisma 使用 SharedTask、SharedTaskGuest、SharedTaskInvitation。初版直接使用最终命名建表,不保留旧开发版搬迁脚本、旧接口、双写或别名。- 不支持新旧共享开发版本混用,也不自动转换旧开发数据库。旧开发沙箱保留原库,使用新的隔离数据库和沙箱验证新版,不修改现有验收数据。- 旧开发分支 migration 0108、0110 未进入 main,已与新主干编号冲突。基于 2026-09-20 的主干 0113 重新生成 0114_shared_task_events。旧分支沙箱保留原库备份,使用新的独立沙箱验收,禁止改写 schema_version 或强行打开不匹配库。0114 只新增最终命名的共享记录表,不读取或改写旧开发版记录、消息作者与队列作者。diff --git a/packages/device-link-protocol/src/protocol.ts b/packages/device-link-protocol/src/protocol.tsindex 48acef3208..be7ca85d2c 100644--- a/packages/device-link-protocol/src/protocol.ts+++ b/packages/device-link-protocol/src/protocol.ts@@ -56,6 +56,8 @@ export interface Envelope {src?: string;/** 目标 deviceId(隧道层帧必填) */dst?: string;+ /** Optional cross-account task scope; absent means legacy same-account routing. */+ sharedTask?: import('./sharedTask.js').SharedTaskScope;payload?: unknown;}diff --git a/packages/device-link-protocol/src/sharedTask.ts b/packages/device-link-protocol/src/sharedTask.tsindex afaa690c76..547aacf2bb 100644--- a/packages/device-link-protocol/src/sharedTask.ts+++ b/packages/device-link-protocol/src/sharedTask.ts@@ -1,50 +1,37 @@-/**- * Task-scoped logical peers multiplexed over the existing reliable device link.- * A sharedTask peer is NOT a physical device identifier or an authorization grant.- * Relay and both endpoints must negotiate this capability before using it.- */-export const SHARED_TASK_RELAY_CAPABILITY = 'shared-task-v1';-export const SHARED_TASK_PEER_PREFIX = 'shared-task~';-export type SharedTaskPeer =- | { sharedTaskId: string; role: 'host' }- | { sharedTaskId: string; role: 'guest'; memberId: string; deviceId: string };--function identifier(value: string): string {- if (typeof value !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(value)) throw new Error('Invalid sharedTask peer identifier');- return value;+/** Explicit task scope; src/dst always remain physical device identifiers. */+export const SHARED_TASK_RELAY_CAPABILITY = 'shared-task-v2';+export type SharedTaskEndpoint = { role: 'host' } | { role: 'guest'; memberId: string };+export interface SharedTaskScope {+ sharedTaskId: string;+ target: SharedTaskEndpoint;+ /** Authored by the relay, never trusted from a sending client. */+ source?: SharedTaskEndpoint;}-/** Matches auth-server's device claim contract; never use for internal IDs. */export function sharedTaskDeviceId(value: unknown): string {if (typeof value !== 'string' || value.length < 1 || value.length > 128) throw new Error('Invalid sharedTask device identifier');return value;}-function encodeDeviceId(value: string): string {- const deviceId = sharedTaskDeviceId(value);- // Preserve the existing encoding for normal IDs. JSON quotes distinguish the- // extended domain and preserve every UTF-16 code unit, including surrogates.- const encoded = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(deviceId) ? deviceId : JSON.stringify(deviceId);- return encodeURIComponent(encoded).replaceAll('~', '%7E');-}-export function sharedTaskHostPeer(sharedTaskId: string): string {- return `${SHARED_TASK_PEER_PREFIX}${encodeURIComponent(identifier(sharedTaskId))}~host`;-}-export function sharedTaskGuestPeer(sharedTaskId: string, memberId: string, deviceId: string): string {- return `${SHARED_TASK_PEER_PREFIX}${encodeURIComponent(identifier(sharedTaskId))}~guest~${encodeURIComponent(identifier(memberId))}~${encodeDeviceId(deviceId)}`;+export function sharedTaskIdentifier(value: unknown): string {+ if (typeof value !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(value)) throw new Error('Invalid sharedTask identifier');+ return value;}-export function isSharedTaskPeer(value: unknown): value is `shared-task~${string}` {- return typeof value === 'string' && value.startsWith(SHARED_TASK_PEER_PREFIX);+function endpoint(value: unknown): SharedTaskEndpoint {+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Invalid sharedTask endpoint');+ const row = value as Record<string, unknown>;+ if (row.role === 'host' && row.memberId === undefined) return { role: 'host' };+ if (row.role === 'guest') return { role: 'guest', memberId: sharedTaskIdentifier(row.memberId) };+ throw new Error('Invalid sharedTask endpoint');}-/** Malformed reserved peers must be rejected, never retried as legacy device IDs. */-export function parseSharedTaskPeer(value: unknown): SharedTaskPeer | null {- if (!isSharedTaskPeer(value) || value.length > 2048) return null;+/** Request parsing deliberately discards any client-supplied source. */+export function parseSharedTaskScope(value: unknown, withSource = false): SharedTaskScope | null {try {- const parts = value.split('~');- const sharedTaskId = identifier(decodeURIComponent(parts[1] ?? ''));- if (parts.length === 3 && parts[2] === 'host' && sharedTaskHostPeer(sharedTaskId) === value) return { sharedTaskId, role: 'host' };- if (parts.length !== 5 || parts[2] !== 'guest') return null;- const memberId = identifier(decodeURIComponent(parts[3]));- const decodedDeviceId = decodeURIComponent(parts[4]);- const deviceId = sharedTaskDeviceId(decodedDeviceId.startsWith('"') ? JSON.parse(decodedDeviceId) : decodedDeviceId);- return sharedTaskGuestPeer(sharedTaskId, memberId, deviceId) === value ? { sharedTaskId, role: 'guest', memberId, deviceId } : null;+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;+ const row = value as Record<string, unknown>;+ const scope: SharedTaskScope = { sharedTaskId: sharedTaskIdentifier(row.sharedTaskId), target: endpoint(row.target) };+ if (withSource) {+ scope.source = endpoint(row.source);+ if (scope.source.role === scope.target.role) return null;+ }+ return scope;} catch { return null; }}diff --git a/packages/device-link/src/__tests__/client.test.ts b/packages/device-link/src/__tests__/client.test.tsindex 968113b4b0..46b94ce5b2 100644--- a/packages/device-link/src/__tests__/client.test.ts+++ b/packages/device-link/src/__tests__/client.test.ts@@ -7,6 +7,8 @@ import { DeviceLinkClient, computeReconnectDelayMs, type WsLike } from '../clienimport {PROTOCOL_VERSION,DeviceLinkError,+ sharedTaskHostPeer,+ SHARED_TASK_RELAY_CAPABILITY,type Envelope,type LinkAcceptPayload,} from '../protocol.js';@@ -66,12 +68,12 @@ class FakeWs implements WsLike {this.emit('message', { toString: () => JSON.stringify(env) });}/** 完成 open + hello-ack 流程 */- ack(): void {+ ack(capabilities?: string[]): void {this.emit('open');this.push({v: PROTOCOL_VERSION,kind: 'hello-ack',- payload: { serverProtocolVersion: PROTOCOL_VERSION, deviceId: 'dev-self', userId: 'u1' },+ payload: { serverProtocolVersion: PROTOCOL_VERSION, deviceId: 'dev-self', userId: 'u1', capabilities },});}}@@ -8947,3 +8949,80 @@ describe('定时重发的单趟预算(TRANSPORT_RETRY_PASS_BUDGET)', () => {h.client.stop();}, 10_000);});++describe('physical addressing with explicit shared task scope', () => {+ it('isolates ordinary remote control and two shared reliable streams on the same host', async () => {+ const h = makeHarness({ timing: { pingIntervalMs: 60_000, requestTimeoutMs: 5_000, transportRetryIntervalMs: 50 } });+ h.client.start(); await tick(); h.current().ack([SHARED_TASK_RELAY_CAPABILITY]);+ const peers = ['desktop', sharedTaskHostPeer('task-a', 'desktop'), sharedTaskHostPeer('task-b', 'desktop')];+ const received: string[] = [];+ h.client.onFrame(env => { if (env.kind === 'push') received.push(env.src!); });+ const inbound = (index: number, env: Envelope): Envelope => ({ ...env, src: 'desktop', dst: 'dev-self',+ ...(index ? { sharedTask: { sharedTaskId: index === 1 ? 'task-a' : 'task-b', source: { role: 'host' as const }, target: { role: 'guest' as const, memberId: 'member' } } } : {}),+ });+ try {+ for (let index = 0; index < peers.length; index++) {+ const opened = h.client.openLink(peers[index], { controllerName: 'Test' });+ const request = h.current().sent.filter(env => env.kind === 'link-open').at(-1)!;+ expect(request.dst).toBe('desktop');+ h.current().push(inbound(index, { v: 1, kind: 'link-accept', id: request.id, payload: {+ appVersion: '1', allowlistHash: 'hash', capabilities: [DEVICE_LINK_CAPABILITY_RELIABLE_TRANSPORT], transportStreamId: 'same-remote-stream',+ } }));+ await opened;+ }+ // Same source device, stream ID and sequence must still be delivered once per scope.+ for (let index = 0; index < peers.length; index++) {+ const push = inbound(index, { v: 1, kind: 'push', payload: { channel: 'maker:event', payload: {} } });+ for (const part of encodeReliableFrames(push, 'same-remote-stream', 1)) h.current().push(part);+ }+ await tick();+ expect(received).toEqual(peers);+ const acks = h.current().sent.filter(env => parseTransportAck(env));+ expect(acks).toHaveLength(3);+ expect(acks.map(env => env.sharedTask?.sharedTaskId)).toEqual([undefined, 'task-a', 'task-b']);+ expect(acks.every(env => env.dst === 'desktop')).toBe(true);+ const settled: number[] = [];+ const requests = peers.map((peer, index) => h.client.invoke(peer, { channel: 'local-db:sessions:get', args: ['original-session'] })+ .then(value => { settled.push(index); return value; }));+ const outbound = h.current().sent.filter(env => env.kind === 'invoke');+ expect(outbound).toHaveLength(3);+ // A valid result or error for B cannot settle A's request, even with A's request ID.+ h.current().push(inbound(2, { v: 1, kind: 'invoke-result', id: outbound[1].id, payload: { ok: true, result: 'wrong-scope' } }));+ h.current().push({ v: 1, kind: 'relay-error', id: outbound[1].id,+ sharedTask: { sharedTaskId: 'task-b', target: { role: 'host' } },+ payload: { code: 'DEVICE_OFFLINE', message: 'offline', dst: 'desktop' } });+ await tick(); expect(settled).toEqual([]);+ for (let index = 0; index < peers.length; index++) {+ const result = inbound(index, { v: 1, kind: 'invoke-result', id: outbound[index].id, payload: { ok: true, result: index } });+ for (const part of encodeReliableFrames(result, 'same-remote-stream', 2)) h.current().push(part);+ }+ expect(await Promise.all(requests)).toEqual([0, 1, 2].map(result => ({ ok: true, result })));+ const count = (index: number) => h.current().sent.filter(env => env.kind === 'invoke' && env.id === outbound[index].id).length;+ const beforeAck = peers.map((_, index) => count(index));+ const sent = parseTransportPayload(outbound[1].payload)!;+ h.current().push(inbound(1, { v: 1, kind: 'push', payload: { channel: DEVICE_LINK_TRANSPORT_ACK_CHANNEL,+ payload: { streamId: sent.meta.streamId, ackSeq: sent.meta.seq } } }));+ await vi.waitFor(() => { expect(count(0)).toBeGreaterThan(beforeAck[0]); expect(count(2)).toBeGreaterThan(beforeAck[2]); });+ expect(count(1)).toBe(beforeAck[1]);+ h.client.closeLink(peers[1], 'user');+ expect(h.current().sent.at(-1)).toMatchObject({ kind: 'link-close', dst: 'desktop', sharedTask: { sharedTaskId: 'task-a' } });+ for (const index of [0, 2]) h.client.sendPush(peers[index], 'maker:event', {});+ expect(h.current().sent.slice(-2).map(env => env.sharedTask?.sharedTaskId)).toEqual([undefined, 'task-b']);+ expect(h.sockets).toHaveLength(1);+ } finally { h.client.stop(); }+ });+ it('refuses shared frames on an old relay while allowing a legacy prefixed physical device', async () => {+ const h = makeHarness({ timing: { pingIntervalMs: 60_000 } });+ h.client.start(); await tick(); h.current().ack();+ try {+ await expect(h.client.openLink(sharedTaskHostPeer('task', 'desktop'), { controllerName: 'Test' })).rejects.toMatchObject({ code: 'VERSION_MISMATCH' });+ expect(h.current().sent.some(env => env.kind === 'link-open')).toBe(false);+ const device = 'shared-task~task~host';+ const opened = h.client.openLink(device, { controllerName: 'Test' });+ const frame = h.current().sent.find(env => env.kind === 'link-open')!;+ expect(frame.dst).toBe(device); expect(frame.sharedTask).toBeUndefined();+ h.current().push({ v: 1, kind: 'link-accept', id: frame.id, src: device, payload: { appVersion: '1', allowlistHash: 'hash' } });+ await opened;+ } finally { h.client.stop(); }+ });+});diff --git a/packages/device-link/src/__tests__/sharedTask.test.ts b/packages/device-link/src/__tests__/sharedTask.test.tsindex a340d169ce..f4385afd86 100644--- a/packages/device-link/src/__tests__/sharedTask.test.ts+++ b/packages/device-link/src/__tests__/sharedTask.test.ts@@ -1,3 +1,4 @@+import { sharedTaskHostPeer } from '../protocol.js';import { describe, expect, it } from 'vitest';import {authorizeSharedTaskOperation as authorize,@@ -28,7 +29,7 @@ describe('sharedTask authorization', () => {expect(authorize(parsed, { accountId: 'guest-b', deviceId: ' 手机~1 ' }, 'session-1', 'history.read').allowed).toBe(false);});it('keeps task subscriptions but removes the full-device list from shared peers', () => {- expect(sharedTaskTopics('shared-task~shared~host', ['sessions', 'session:task'])).toEqual(['session:task']);+ expect(sharedTaskTopics(sharedTaskHostPeer('shared', 'desktop'), ['sessions', 'session:task'])).toEqual(['session:task']);expect(sharedTaskTopics('my-desktop', ['sessions', 'session:task'])).toEqual(['sessions', 'session:task']);});it('only permits attachment references in this sharing namespace', () => {diff --git a/packages/device-link/src/__tests__/sharedTaskDeviceId.test.ts b/packages/device-link/src/__tests__/sharedTaskDeviceId.test.tsindex cbbc3676b0..07131f4f06 100644--- a/packages/device-link/src/__tests__/sharedTaskDeviceId.test.ts+++ b/packages/device-link/src/__tests__/sharedTaskDeviceId.test.ts@@ -1,20 +1,24 @@import { describe, expect, it } from 'vitest';-import { sharedTaskDeviceId, sharedTaskGuestPeer, parseSharedTaskPeer } from '@cindy/device-link-protocol/protocol';+import { sharedTaskDeviceId, parseSharedTaskScope } from '@cindy/device-link-protocol/protocol';// Keep identical fixtures in both repositories' device-link tests.-describe('shared task device claim encoding', () => {- it.each(['phone:1', '_legacy', ' device ', '设备/手机', 'phone~1', '%3A', '"quoted"', '\ud800', '\u0000'.repeat(128), 'x'.repeat(128)])('round-trips the auth device domain: %j', deviceId => {+describe('shared task wire scope and physical device domain', () => {+ it.each(['phone:1', '_legacy', ' device ', '设备/手机', 'phone~1', '%3A', '"quoted"', '\ud800', '\u0000'.repeat(128), 'x'.repeat(128), 'shared-task~task~host'])('round-trips the auth device domain: %j', deviceId => {expect(sharedTaskDeviceId(deviceId)).toBe(deviceId);- const peer = sharedTaskGuestPeer('t' + ':'.repeat(127), 'm' + ':'.repeat(127), deviceId);- expect(peer.length).toBeLessThanOrEqual(2048);- expect(peer.split('~')).toHaveLength(5);- expect(parseSharedTaskPeer(peer)).toEqual({ sharedTaskId: 't' + ':'.repeat(127), role: 'guest', memberId: 'm' + ':'.repeat(127), deviceId });+ const frame = { src: deviceId, dst: deviceId, sharedTask: { sharedTaskId: 'task', target: { role: 'host' }, source: { role: 'guest', memberId: 'member' } } };+ const decoded = JSON.parse(JSON.stringify(frame));+ expect(decoded).toEqual(frame);+ expect(parseSharedTaskScope(decoded.sharedTask, true)).toEqual(frame.sharedTask);});- it('preserves old peer encoding and rejects noncanonical aliases', () => {- expect(sharedTaskGuestPeer('task', 'member', 'phone:1')).toBe('shared-task~task~guest~member~phone%3A1');- expect(parseSharedTaskPeer('shared-task~task~guest~member~%22phone%3A1%22')).toBeNull();- expect(parseSharedTaskPeer('shared-task~task~guest~member~%22phone~1%22')).toBeNull();- expect(parseSharedTaskPeer('shared-task~task~guest~member~%5B1%5D')).toBeNull();+ it('discards client-supplied source and extraneous fields', () => {+ expect(parseSharedTaskScope({ sharedTaskId: 'task', target: { role: 'host' }, source: { role: 'host' }, grant: 'forged' }))+ .toEqual({ sharedTaskId: 'task', target: { role: 'host' } });+ });+ it.each([null, [], {}, { sharedTaskId: 'task', target: { role: 'guest' } },+ { sharedTaskId: 'task', target: { role: 'host', memberId: 'member' } },+ { sharedTaskId: 'task', target: { role: 'host' }, source: { role: 'host' } },+ { sharedTaskId: '../task', target: { role: 'host' } }])('rejects invalid received scope %j', value => {+ expect(parseSharedTaskScope(value, true)).toBeNull();});it.each(['', 'x'.repeat(129), null, 1])('rejects an invalid device claim: %j', value => {expect(() => sharedTaskDeviceId(value)).toThrow();diff --git a/packages/device-link/src/__tests__/sharedTaskEnvelope.test.ts b/packages/device-link/src/__tests__/sharedTaskEnvelope.test.tsnew file mode 100644index 0000000000..9777529a18--- /dev/null+++ b/packages/device-link/src/__tests__/sharedTaskEnvelope.test.ts@@ -0,0 +1,56 @@+import { describe, expect, it } from 'vitest';+import { encodeSharedTaskEnvelope as encode, decodeSharedTaskEnvelope as decode } from '../sharedTaskEnvelope.js';+import { sharedTaskHostPeer, sharedTaskGuestPeer, parseSharedTaskPeer, isSharedTaskPeer } from '../sharedTaskPeer.js';+import { PROTOCOL_VERSION, type Envelope } from '../protocol.js';++const frame = (dst: string): Envelope => ({ v: PROTOCOL_VERSION, kind: 'invoke', id: 'request', dst, payload: { channel: 'local-db:sessions:get', args: ['original-session'] } });++describe('shared task local handles and wire scope', () => {+ it('round-trips maximum identifiers without truncating or escaping the physical address twice', () => {+ const task = 't'.repeat(128);+ const member = 'm'.repeat(128);+ const device = String.fromCharCode(0).repeat(128);+ const key = sharedTaskGuestPeer(task, member, device);+ expect(key.length).toBeLessThanOrEqual(2048);+ expect(parseSharedTaskPeer(key)).toEqual({ sharedTaskId: task, role: 'guest', memberId: member, deviceId: device });+ expect(JSON.parse(JSON.stringify(encode({ ...frame(key), kind: 'invoke-result' }, true)))).toMatchObject({+ dst: device, sharedTask: { sharedTaskId: task, target: { role: 'guest', memberId: member } },+ });+ });+ it.each(['shared-task~task~host', 'shared-task~task~guest~member~phone', '_legacy', '设备/手机', ' '.repeat(128), '\u0000'.repeat(128), '\ud800', '%3A', '"quoted"'])('never treats a physical ID as a scoped handle: %j', id => {+ expect(isSharedTaskPeer(id)).toBe(false);+ expect(encode(frame(id), false)).toEqual(frame(id));+ expect(decode({ ...frame(id), src: id }, false)).toEqual({ ...frame(id), src: id });+ const key = sharedTaskGuestPeer('task', 'member', id);+ expect(key.length).toBeGreaterThan(128);+ expect(parseSharedTaskPeer(key)).toEqual({ sharedTaskId: 'task', role: 'guest', memberId: 'member', deviceId: id });+ expect(decode({ ...frame(id), src: key }, true)).toBeNull();+ });+ it('separates two scopes on one device without changing task payloads or wire addresses', () => {+ const first = sharedTaskHostPeer('share-a', 'desktop');+ const second = sharedTaskHostPeer('share-b', 'desktop');+ expect(new Set(['desktop', first, second]).size).toBe(3);+ expect(encode(frame(first), true)).toEqual({ ...frame('desktop'), sharedTask: { sharedTaskId: 'share-a', target: { role: 'host' } } });+ expect(encode(frame(second), true).payload).toEqual(frame(first).payload);+ expect(JSON.stringify(encode(frame(first), true))).not.toContain(first);+ });+ it('requires negotiated relay support and rejects malformed local handles', () => {+ expect(() => encode(frame(sharedTaskHostPeer('task', 'desktop')), false)).toThrow(/shared-task-v2/);+ expect(() => encode({ ...frame('desktop'), sharedTask: { sharedTaskId: 'task', target: { role: 'host' } } }, true)).toThrow();+ const key = sharedTaskHostPeer('task', 'desktop');+ for (const alias of [key + '~', key.trimEnd() + ' ', key.replace('null', 'false')]) expect(parseSharedTaskPeer(alias)).toBeNull();+ });+ it('only converts a valid relay-authored source and keeps malformed scope out of legacy dispatch', () => {+ const incoming: Envelope = { ...frame('desktop'), src: 'phone', sharedTask: { sharedTaskId: 'task', target: { role: 'host' }, source: { role: 'guest', memberId: 'member' } } };+ expect(decode(incoming, true)).toMatchObject({ src: sharedTaskGuestPeer('task', 'member', 'phone'), dst: sharedTaskHostPeer('task', 'desktop') });+ expect(decode(incoming, false)).toBeNull();+ for (const scope of [null, {}, { sharedTaskId: 'task', target: { role: 'host' } }, { ...incoming.sharedTask, source: { role: 'host' } }]) {+ expect(decode({ ...incoming, sharedTask: scope as Envelope['sharedTask'] }, true)).toBeNull();+ }+ });+ it('correlates relay failures to the scope, not to the physical host alone', () => {+ const error: Envelope = { v: PROTOCOL_VERSION, kind: 'relay-error', id: 'request', payload: { code: 'DEVICE_OFFLINE', message: 'offline', dst: 'desktop' }, sharedTask: { sharedTaskId: 'task', target: { role: 'host' } } };+ expect(decode(error, true)?.payload).toEqual({ code: 'DEVICE_OFFLINE', message: 'offline', dst: sharedTaskHostPeer('task', 'desktop') });+ expect(decode({ ...error, sharedTask: undefined, payload: { ...error.payload as object, dst: sharedTaskHostPeer('task', 'desktop') } }, true)).toBeNull();+ });+});diff --git a/packages/device-link/src/__tests__/sharedTaskProbe.test.ts b/packages/device-link/src/__tests__/sharedTaskProbe.test.tsindex c17bf34cab..9b43478927 100644--- a/packages/device-link/src/__tests__/sharedTaskProbe.test.ts+++ b/packages/device-link/src/__tests__/sharedTaskProbe.test.ts@@ -2,7 +2,7 @@ import { describe, expect, it, vi } from 'vitest';import { sharedTaskHostPeer } from '../protocol.js';import { probeSharedTaskHost } from '../sharedTaskProbe.js';-const peer = sharedTaskHostPeer('sharedTask');+const peer = sharedTaskHostPeer('sharedTask', 'desktop');function fixture() {return {isCurrent: vi.fn(() => true),diff --git a/packages/device-link/src/client.ts b/packages/device-link/src/client.tsindex 31ea949969..8cac2895b5 100644--- a/packages/device-link/src/client.ts+++ b/packages/device-link/src/client.ts@@ -1,4 +1,7 @@import { isPeerResetRetryableReadChannel } from './invokePolicy.js';+import { encodeSharedTaskEnvelope, decodeSharedTaskEnvelope } from './sharedTaskEnvelope.js';+import { isSharedTaskPeer } from './sharedTaskPeer.js';+import { SHARED_TASK_RELAY_CAPABILITY } from '@cindy/device-link-protocol';import {requestSessionTagCatalog,decodeSessionTagCatalog,@@ -2061,7 +2064,8 @@ export class DeviceLinkClient {this.log.warn('dropping invalid device-link frame');return;}- const env = parsed;+ const env = decodeSharedTaskEnvelope(parsed, this.hasServerCapability(SHARED_TASK_RELAY_CAPABILITY));+ if (!env) { this.log.warn('dropping invalid device-link routing scope'); return; }const validForHeartbeat = isValidInboundEnvelope(env);// 畸形 invoke / link-close 仍须进入 Desktop 业务层:前者生成结构化拒绝,后者// 走既有 fail-generic 的 peer teardown;但两者都不能因此喂活 heartbeat。@@ -2254,6 +2258,8 @@ export class DeviceLinkClient {// 配对要 id + kind 双重命中:仅 id 撞而 kind 不符(如 invoke-result 撞到一个// 等 link-accept 的 pending)的帧不得错误 resolve —— 留它超时,本帧当未知帧交 host。const p = env.id ? this.pending.get(env.id) : undefined;+ // A request ID alone cannot authorize a reply from another device or task scope.+ if (p?.dst && env.src !== p.dst) return true;if (p && p.expectKind === env.kind) {if (env.kind === 'link-accept' && env.src) {const accepted = env.payload as LinkAcceptPayload | undefined;@@ -2316,6 +2322,8 @@ export class DeviceLinkClient {|| payload.code === 'REMOTE_DISABLED');const pending = env.id ? this.pending.get(env.id) : undefined;+ if (pending && ((payload.dst !== undefined && payload.dst !== pending.dst)+ || (isSharedTaskPeer(pending.dst) && env.sharedTask === undefined))) return true;const routeDeviceId = payload.dst ?? pending?.dst;const rememberedGeneration = env.id? this.consumeOutboundRouteGeneration(env.id, routeDeviceId)@@ -3044,7 +3052,7 @@ export class DeviceLinkClient {// pending 可在 link down 时入队,并在后续 link generation 才首次上网;// 路由错误必须归属每次真实物理发送,而不是逻辑消息的入队代次。this.sendRoutedEnvelope(frame, peer.linkGeneration);- writtenBytes += byteLength(JSON.stringify(frame));+ writtenBytes += byteLength(JSON.stringify(encodeSharedTaskEnvelope(frame, true)));pending.sent = true;sent += 1;}@@ -3119,7 +3127,8 @@ export class DeviceLinkClient {}private measureReliableFrames(frames: readonly Envelope[]): number {- return frames.reduce((sum, frame) => sum + byteLength(JSON.stringify(frame)), 0);+ // Budget the physical wire envelope, not the local scoped connection handle.+ return frames.reduce((sum, frame) => sum + byteLength(JSON.stringify(encodeSharedTaskEnvelope(frame, true))), 0);}/**@@ -3147,7 +3156,7 @@ export class DeviceLinkClient {private sendEnvelope(env: Envelope): void {const ws = this.ws;if (!ws) throw new DeviceLinkError('NOT_CONNECTED', 'no active connection');- const text = JSON.stringify(env);+ const text = JSON.stringify(encodeSharedTaskEnvelope(env, this.hasServerCapability(SHARED_TASK_RELAY_CAPABILITY)));// 按 UTF-8 字节数判定,与服务端 MAX_FRAME_BYTES(Buffer.byteLength)一致。// 用 text.length(UTF-16 码元)会与服务端不符:CJK 等多字节内容客户端自检通过、// 服务端却 PAYLOAD_TOO_LARGE 丢帧,invoke 只能等 30s 超时而非快速失败。diff --git a/packages/device-link/src/protocol.ts b/packages/device-link/src/protocol.tsindex 11b1c2e9c6..31cef1d8c8 100644--- a/packages/device-link/src/protocol.ts+++ b/packages/device-link/src/protocol.ts@@ -25,8 +25,9 @@ import {type RelayErrorPayload,} from '@cindy/device-link-protocol';-export { SHARED_TASK_RELAY_CAPABILITY, SHARED_TASK_PEER_PREFIX, sharedTaskHostPeer, sharedTaskGuestPeer, sharedTaskDeviceId, isSharedTaskPeer, parseSharedTaskPeer } from '@cindy/device-link-protocol';-export type { SharedTaskPeer } from '@cindy/device-link-protocol';+export { SHARED_TASK_RELAY_CAPABILITY, sharedTaskDeviceId, parseSharedTaskScope, type SharedTaskScope } from '@cindy/device-link-protocol';+export { sharedTaskHostPeer, sharedTaskGuestPeer, isSharedTaskPeer, parseSharedTaskPeer } from './sharedTaskPeer.js';+export type { SharedTaskPeer } from './sharedTaskPeer.js';export {MAX_FRAME_BYTES,diff --git a/packages/device-link/src/sharedTask.ts b/packages/device-link/src/sharedTask.tsindex 833f798790..4961e87168 100644--- a/packages/device-link/src/sharedTask.ts+++ b/packages/device-link/src/sharedTask.ts@@ -15,7 +15,7 @@ export function isSharedTaskAttachment(value: string, sharedTaskId: string): booparts.slice(3).every((part) => /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(part));}-export const SHARED_TASK_CAPABILITY = 'shared-task-v1';+export const SHARED_TASK_CAPABILITY = 'shared-task-v2';export const SHARED_TASK_MAX_ACTIVE_PER_OWNER = 2;export const SHARED_TASK_MAX_JOINED_PER_ACCOUNT = 2;export const SHARED_TASK_MAX_GUESTS = 2;diff --git a/packages/device-link/src/sharedTaskEnvelope.ts b/packages/device-link/src/sharedTaskEnvelope.tsnew file mode 100644index 0000000000..4a25439853--- /dev/null+++ b/packages/device-link/src/sharedTaskEnvelope.ts@@ -0,0 +1,50 @@+import { ROUTED_KINDS, SHARED_TASK_RELAY_CAPABILITY, parseSharedTaskScope, sharedTaskDeviceId, type Envelope, type SharedTaskEndpoint } from '@cindy/device-link-protocol';+import { DeviceLinkError } from './protocol.js';+import { parseSharedTaskPeer, sharedTaskGuestPeer, sharedTaskHostPeer } from './sharedTaskPeer.js';++function peerKey(task: string, endpoint: SharedTaskEndpoint, device: unknown): string {+ const id = sharedTaskDeviceId(device);+ return endpoint.role === 'host' ? sharedTaskHostPeer(task, id) : sharedTaskGuestPeer(task, endpoint.memberId, id);+}+/** Encode only at the socket boundary, after local reliable-link bookkeeping. */+export function encodeSharedTaskEnvelope(env: Envelope, supportsScope: boolean): Envelope {+ const peer = parseSharedTaskPeer(env.dst);+ if (!peer) {+ if (env.sharedTask !== undefined) throw new DeviceLinkError('BAD_REQUEST', 'shared scope requires a scoped local peer');+ if (env.dst !== undefined) sharedTaskDeviceId(env.dst);+ return env;+ }+ if (!supportsScope) throw new DeviceLinkError('VERSION_MISMATCH', 'shared task routing requires ' + SHARED_TASK_RELAY_CAPABILITY);+ if (!ROUTED_KINDS.has(env.kind)) throw new DeviceLinkError('BAD_REQUEST', 'invalid shared task frame kind');+ const { src: _src, sharedTask: _scope, ...frame } = env;+ return { ...frame, dst: peer.deviceId, sharedTask: {+ sharedTaskId: peer.sharedTaskId,+ target: peer.role === 'host' ? { role: 'host' } : { role: 'guest', memberId: peer.memberId },+ } };+}+/** Only relay-authored scope can become a local scoped key. Invalid scope never falls back. */+export function decodeSharedTaskEnvelope(env: Envelope, supportsScope: boolean): Envelope | null {+ try {+ if (env.sharedTask === undefined) {+ if (env.src !== undefined) sharedTaskDeviceId(env.src);+ if (env.dst !== undefined) sharedTaskDeviceId(env.dst);+ if (env.kind === 'relay-error') {+ const dst = (env.payload as { dst?: unknown } | undefined)?.dst;+ if (dst !== undefined) sharedTaskDeviceId(dst);+ }+ return env;+ }+ if (!supportsScope || (!ROUTED_KINDS.has(env.kind) && env.kind !== 'relay-error')) return null;+ const scope = parseSharedTaskScope(env.sharedTask, env.kind !== 'relay-error');+ if (!scope) return null;+ if (env.kind === 'relay-error') {+ const payload = env.payload as Record<string, unknown> | undefined;+ if (!payload || typeof payload !== 'object') return null;+ return { ...env, payload: { ...payload, dst: peerKey(scope.sharedTaskId, scope.target, payload.dst) } };+ }+ return { ...env,+ src: peerKey(scope.sharedTaskId, scope.source!, env.src),+ dst: peerKey(scope.sharedTaskId, scope.target, env.dst),+ };+ } catch { return null; }+}diff --git a/packages/device-link/src/sharedTaskPeer.ts b/packages/device-link/src/sharedTaskPeer.tsnew file mode 100644index 0000000000..5596199ecb--- /dev/null+++ b/packages/device-link/src/sharedTaskPeer.ts@@ -0,0 +1,31 @@+import { sharedTaskDeviceId, sharedTaskIdentifier, type SharedTaskEndpoint } from '@cindy/device-link-protocol';++export type SharedTaskPeer = { sharedTaskId: string; deviceId: string } & SharedTaskEndpoint;+// Local map/IPC handles only, NEVER relay addresses. Physical auth IDs are <=128+// code units. Keeping scoped keys outside that domain makes collisions impossible,+// including deliberately fabricated IDs. Padding costs no wire bytes.+function key(peer: SharedTaskPeer): string {+ return JSON.stringify([peer.sharedTaskId, peer.role, peer.role === 'guest' ? peer.memberId : null, peer.deviceId]).padEnd(129, '~');+}+export function sharedTaskHostPeer(sharedTaskId: string, deviceId: string): string {+ return key({ sharedTaskId: sharedTaskIdentifier(sharedTaskId), role: 'host', deviceId: sharedTaskDeviceId(deviceId) });+}+export function sharedTaskGuestPeer(sharedTaskId: string, memberId: string, deviceId: string): string {+ return key({ sharedTaskId: sharedTaskIdentifier(sharedTaskId), role: 'guest', memberId: sharedTaskIdentifier(memberId), deviceId: sharedTaskDeviceId(deviceId) });+}+export function parseSharedTaskPeer(value: unknown): SharedTaskPeer | null {+ if (typeof value !== 'string' || value.length <= 128 || value.length > 2048) return null;+ try {+ const parts: unknown = JSON.parse(value.replace(/~+$/, ''));+ if (!Array.isArray(parts) || parts.length !== 4) return null;+ const [task, role, member, device] = parts;+ const sharedTaskId = sharedTaskIdentifier(task);+ const deviceId = sharedTaskDeviceId(device);+ let peer: SharedTaskPeer;+ if (role === 'host' && member === null) peer = { sharedTaskId, role, deviceId };+ else if (role === 'guest') peer = { sharedTaskId, role, deviceId, memberId: sharedTaskIdentifier(member) };+ else return null;+ return key(peer) === value ? peer : null;+ } catch { return null; }+}+export function isSharedTaskPeer(value: unknown): boolean { return parseSharedTaskPeer(value) !== null; }