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。

feat(shared-task): support invitation links and account nicknames

DavidShen8ecf37cbe547
diff --git a/apps/desktop/src/main/__tests__/deepLink.test.ts b/apps/desktop/src/main/__tests__/deepLink.test.ts
index 234af96d43..e671cbaa76 100644
--- a/apps/desktop/src/main/__tests__/deepLink.test.ts
+++ b/apps/desktop/src/main/__tests__/deepLink.test.ts
@@ -18,14 +18,8 @@ vi.mock('electron', () => ({
}));
// logger 依赖 electron-log + app path, 在测试里要么 mock 要么吞日志。给个 noop logger。
-vi.mock('../logger', () => ({
- createLogger: () => ({
- info: () => {},
- warn: () => {},
- error: () => {},
- debug: () => {},
- }),
-}));
+const logs = vi.hoisted(() => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }));
+vi.mock('../logger', () => ({ createLogger: () => logs }));
import { vi } from 'vitest';
import {
@@ -64,6 +58,27 @@ function providerImportUrl(scheme: 'cindy' | 'xdt-maker'): string {
return `${scheme}://provider/import?v=1&data=${Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url')}`;
}
+describe('shared task invitation handoff', () => {
+ it('buffers until the authenticated renderer takes it, without logging the secret', () => {
+ const invitation = 'A'.repeat(43);
+ const url = 'cindy://shared-task/join?invitation=' + invitation + '&server=https%3A%2F%2Frelay.example.test';
+ setDeepLinkMainWindow(null);
+ handleIncomingDeepLink(url, 'test');
+ expect(takePendingDeepLink()).toEqual({ type: 'shared-task-join', invitation, server: 'https://relay.example.test' });
+ expect(takePendingDeepLink()).toBeNull();
+ expect(JSON.stringify(Object.values(logs).map(log => log.mock.calls))).not.toContain(invitation);
+ const argv = ['cindy.exe', url, 'cindy://shared-task/join?invitation=invalid-secret'];
+ redactConsumedDeepLinkInArgv(argv, url);
+ expect(argv.join(' ')).not.toContain(invitation);
+ expect(argv.join(' ')).not.toContain('invalid-secret');
+ });
+ it('rejects malformed and duplicate invitation fields', () => {
+ const url = 'cindy://shared-task/join?invitation=' + 'A'.repeat(43) + '&server=https%3A%2F%2Frelay.example.test';
+ expect(parseDeepLink(url + '&invitation=' + 'B'.repeat(43))).toBeNull();
+ expect(parseDeepLink(url.replace('https%3A%2F%2Frelay.example.test', 'javascript%3Aalert(1)'))).toBeNull();
+ });
+});
+
describe('user-initiated main-window focus', () => {
it('activates and raises the target window before focusing on Windows', () => {
const calls: string[] = [];
diff --git a/apps/desktop/src/main/__tests__/deepLinkWindowsRegistration.test.ts b/apps/desktop/src/main/__tests__/deepLinkWindowsRegistration.test.ts
new file mode 100644
index 0000000000..1b9c8b0077
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/deepLinkWindowsRegistration.test.ts
@@ -0,0 +1,46 @@
+import { beforeEach, expect, it, vi } from 'vitest';
+
+const execute = vi.hoisted(() => {
+ const fn = vi.fn();
+ // Node's execFile has a custom promisifier returning both output streams.
+ Object.defineProperty(fn, Symbol.for('nodejs.util.promisify.custom'), {
+ value: (...args: unknown[]) => new Promise((resolve, reject) => {
+ fn(...args, (error: Error | null, stdout: string, stderr: string) => {
+ if (error) reject(error);
+ else resolve({ stdout, stderr });
+ });
+ }),
+ });
+ return fn;
+});
+vi.mock('node:child_process', () => ({ execFile: execute }));
+vi.mock('../logger', () => ({ createLogger: () => ({ warn: vi.fn() }) }));
+import { registerWindowsDeepLinkName } from '../deepLinkWindowsRegistration';
+
+beforeEach(() => {
+ execute.mockReset();
+ execute.mockImplementation((_file, args, _options, callback) => {
+ callback(args[0] === 'query' ? new Error('missing') : null, '', '');
+ });
+});
+it.each(['cindy', 'xdt-maker'])('names only the registered %s protocol, retaining the Electron launch command', async (scheme) => {
+ await registerWindowsDeepLinkName(scheme, 'win32');
+ const writes = execute.mock.calls.filter(([, args]) => args[0] === 'add');
+ expect(writes).toHaveLength(1);
+ expect(writes[0].slice(0, 3)).toEqual(['reg.exe', [
+ 'add', `HKCU\\Software\\Classes\\${scheme}\\Application`, '/v', 'ApplicationName', '/t', 'REG_SZ', '/d', 'Cindy', '/f',
+ ], { windowsHide: true, encoding: 'utf8', timeout: 3_000 }]);
+});
+it('leaves correct names untouched and does not write on other platforms or to arbitrary protocols', async () => {
+ execute.mockImplementation((_file, _args, _options, callback) => callback(null, ' ApplicationName REG_SZ Cindy\r\n', ''));
+ await registerWindowsDeepLinkName('cindy', 'win32');
+ expect(execute).toHaveBeenCalledTimes(1);
+ execute.mockClear();
+ await registerWindowsDeepLinkName('cindy', 'darwin');
+ await registerWindowsDeepLinkName('https', 'win32');
+ expect(execute).not.toHaveBeenCalled();
+});
+it('does not fail application startup when Windows refuses the metadata write', async () => {
+ execute.mockImplementation((_file, _args, _options, callback) => callback(new Error('denied'), '', ''));
+ await expect(registerWindowsDeepLinkName('cindy', 'win32')).resolves.toBeUndefined();
+});
diff --git a/apps/desktop/src/main/__tests__/providerImportWiring.test.ts b/apps/desktop/src/main/__tests__/providerImportWiring.test.ts
index 19ec97f6ff..1bab0ea719 100644
--- a/apps/desktop/src/main/__tests__/providerImportWiring.test.ts
+++ b/apps/desktop/src/main/__tests__/providerImportWiring.test.ts
@@ -10,7 +10,7 @@ const mainLayout = readFileSync(new URL('../../renderer/components/layout/MainLa
describe('provider import wiring', () => {
it('consumes the main pending slot when an import wake-up reaches MainLayout', () => {
- expect(mainLayout).toMatch(/onDeepLinkNavigate\(\(payload\) => \{\s*if \(payload.type !== 'provider-import'\) \{\s*handleDeepLinkPayload\(payload\);\s*return;\s*\}[\s\S]*?takePendingDeepLink\(\)\.then\(\(pending\) => \{\s*if \(pending\) handleDeepLinkPayload\(pending\);/);
+ expect(mainLayout).toMatch(/onDeepLinkNavigate\(\(payload\) => \{\s*if \(payload.type !== 'provider-import' && payload.type !== 'shared-task-join'\) \{\s*handleDeepLinkPayload\(payload\);\s*return;\s*\}[\s\S]*?takePendingDeepLink\(\)\.then\(\(pending\) => \{\s*if \(pending\) handleDeepLinkPayload\(pending\);/);
});
it('passes sanitized JS argv explicitly instead of replaying Electron native startup arguments', () => {
for (const source of [bootstrap, updateService]) {
diff --git a/apps/desktop/src/main/background-task-output/__tests__/reader.test.ts b/apps/desktop/src/main/background-task-output/__tests__/reader.test.ts
index c4835291e2..1434952464 100644
--- a/apps/desktop/src/main/background-task-output/__tests__/reader.test.ts
+++ b/apps/desktop/src/main/background-task-output/__tests__/reader.test.ts
@@ -2,7 +2,7 @@ import { promises as fs } from 'node:fs';
import os from 'node:os';
import path from 'node:path';
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { readBackgroundTaskOutputTail, readSessionBackgroundTaskOutputTail } from '../reader';
@@ -57,10 +57,20 @@ describe('readBackgroundTaskOutputTail', () => {
it('rejects a link whose real target is not an output file', async () => {
const target = path.join(dir, 'secret.txt');
- await fs.writeFile(target, 'secret');
+ // Junctions need no file-symlink privilege on Windows. Canonical extension
+ // validation must reject either target before inspecting or opening it.
+ if (process.platform === 'win32') await fs.mkdir(target);
+ else await fs.writeFile(target, 'secret');
const link = path.join(dir, 'b6.output');
- await fs.symlink(target, link);
- expect(await readBackgroundTaskOutputTail(link)).toEqual({ ok: false, reason: 'forbidden' });
+ await fs.symlink(target, link, process.platform === 'win32' ? 'junction' : 'file');
+ expect((await fs.lstat(link)).isSymbolicLink()).toBe(true);
+ const stat = vi.spyOn(fs, 'stat');
+ const open = vi.spyOn(fs, 'open');
+ try {
+ expect(await readBackgroundTaskOutputTail(link)).toEqual({ ok: false, reason: 'forbidden' });
+ expect(stat).not.toHaveBeenCalled();
+ expect(open).not.toHaveBeenCalled();
+ } finally { stat.mockRestore(); open.mockRestore(); }
});
it('reads through a symlinked parent directory by checking the canonical path', async () => {
@@ -69,7 +79,7 @@ describe('readBackgroundTaskOutputTail', () => {
await fs.mkdir(realDir);
await fs.writeFile(path.join(realDir, 'b7.output'), 'via link\n');
const linkedDir = path.join(dir, 'linked');
- await fs.symlink(realDir, linkedDir, 'dir');
+ await fs.symlink(realDir, linkedDir, process.platform === 'win32' ? 'junction' : 'dir');
expect(await readBackgroundTaskOutputTail(path.join(linkedDir, 'b7.output'))).toMatchObject({
ok: true,
text: 'via link\n',
diff --git a/apps/desktop/src/main/deepLink.ts b/apps/desktop/src/main/deepLink.ts
index a28b7e493f..4e436dffba 100644
--- a/apps/desktop/src/main/deepLink.ts
+++ b/apps/desktop/src/main/deepLink.ts
@@ -41,7 +41,9 @@
import { app, BrowserWindow } from 'electron';
import path from 'node:path';
+import { parseSharedTaskInvitationIntent } from '@cindy/device-link';
import { createLogger } from './logger';
+import { registerWindowsDeepLinkName } from './deepLinkWindowsRegistration';
import {
DEEP_LINK_PRIMARY_SCHEME,
DEEP_LINK_SCHEMES,
@@ -63,6 +65,7 @@ export const OPEN_FOLDER_FLAG = '--open-folder';
export const OPEN_SHARE_FILE_FLAG = '--open-share-file';
export type DeepLinkPayload =
+ | { type: 'shared-task-join'; invitation: string; server: string }
| { type: 'session'; id: string; messageClientId?: string }
| { type: 'project'; workingDir: string }
/**
@@ -100,6 +103,8 @@ export type DeepLinkPayload =
*/
export function parseDeepLink(url: string): DeepLinkPayload | null {
if (typeof url !== 'string') return null;
+ const invitation = parseSharedTaskInvitationIntent(url);
+ if (invitation) return { type: 'shared-task-join', ...invitation };
const prefix = matchDeepLinkPrefix(url);
if (prefix === null) return null;
const rest = url.slice(prefix.length);
@@ -288,7 +293,7 @@ export function handleIncomingDeepLink(url: string, source: string): void {
log.warn('ignoring unparseable deep link', { source });
return;
}
- log.info('received deep link', { source, payload });
+ log.info('received deep link', { source, payload: safeDeepLinkLog(payload) });
dispatchDeepLink(payload);
}
@@ -406,6 +411,10 @@ export function sendMainWindowMessage(channel: string, payload: unknown): boolea
return true;
}
+function safeDeepLinkLog(payload: DeepLinkPayload) {
+ return payload.type === 'shared-task-join' ? { type: payload.type } : payload;
+}
+
function dispatchDeepLink(payload: DeepLinkPayload, shouldFocus = true): void {
// 纯前台意图:main 进程内消化。冷启动时窗口还没建,app 启动流程本身会前台,直接丢弃。
if (payload.type === 'focus') {
@@ -416,7 +425,7 @@ function dispatchDeepLink(payload: DeepLinkPayload, shouldFocus = true): void {
const windowReady = win && !win.isDestroyed() && win.webContents && !win.webContents.isLoading();
// A loaded login/LocalDbGate page has no MainLayout listener yet. Imports stay
// in the existing pending slot until the authenticated consumer takes them.
- if (!windowReady || payload.type === 'provider-import') {
+ if (!windowReady || payload.type === 'provider-import' || payload.type === 'shared-task-join') {
// 保留"用户最后意图"语义:同一次冷启动如果先后入站多条 (例如 argv 同时含
// deep link URL 和 --open-folder, 现实场景极罕见但 bootstrap 两条 scan 都
// 会触发),后到的覆盖前者。但 warn log 留下排查线索,事后能从日志识别这种
@@ -426,12 +435,12 @@ function dispatchDeepLink(payload: DeepLinkPayload, shouldFocus = true): void {
cancelProviderImport(pendingDeepLink.importId);
}
log.warn('overwriting buffered pending payload', {
- previous: pendingDeepLink,
- next: payload,
+ previous: safeDeepLinkLog(pendingDeepLink),
+ next: safeDeepLinkLog(payload),
});
}
pendingDeepLink = payload;
- log.debug('buffered pending deep link until renderer pull', payload);
+ log.debug('buffered pending deep link until renderer pull', safeDeepLinkLog(payload));
// Agent-key first tap may switch in the background. A buffered deep link
// from that path must not steal the frontmost app.
if (!windowReady) {
@@ -458,7 +467,7 @@ export function takePendingDeepLink(): DeepLinkPayload | null {
if (!pendingDeepLink) return null;
const payload = pendingDeepLink;
pendingDeepLink = null;
- log.info('renderer pulled pending deep link', payload);
+ log.info('renderer pulled pending deep link', safeDeepLinkLog(payload));
return payload;
}
@@ -486,7 +495,7 @@ export function redactConsumedDeepLinkInArgv(argv: string[], deepLink?: string):
for (let i = argv.length - 1; i >= 0; i -= 1) {
const arg = argv[i];
const prefix = typeof arg === 'string' ? matchDeepLinkPrefix(arg) : null;
- if (arg !== deepLink && !(prefix && arg.slice(prefix.length).startsWith('provider/'))) continue;
+ if (arg !== deepLink && !(prefix && /^(provider\/|shared-task\/|shared-session\?)/.test(arg.slice(prefix.length)))) continue;
argv[i] = `${DEEP_LINK_PRIMARY_SCHEME}://consumed`;
}
}
@@ -568,16 +577,18 @@ function isWindowsSlashSwitch(value: string): boolean {
*/
export function registerDeepLinkProtocol(): void {
for (const scheme of DEEP_LINK_SCHEMES) {
+ let registered: boolean;
if (process.defaultApp) {
// dev:用 Electron 解释器跑 main 入口
if (process.argv.length >= 2) {
- app.setAsDefaultProtocolClient(scheme, process.execPath, [path.resolve(process.argv[1])]);
+ registered = app.setAsDefaultProtocolClient(scheme, process.execPath, [path.resolve(process.argv[1])]);
} else {
- app.setAsDefaultProtocolClient(scheme);
+ registered = app.setAsDefaultProtocolClient(scheme);
}
} else {
// packaged:直接调,OS 用 app bundle 路径
- app.setAsDefaultProtocolClient(scheme);
+ registered = app.setAsDefaultProtocolClient(scheme);
}
+ if (registered) void registerWindowsDeepLinkName(scheme);
}
}
diff --git a/apps/desktop/src/main/deepLinkWindowsRegistration.ts b/apps/desktop/src/main/deepLinkWindowsRegistration.ts
new file mode 100644
index 0000000000..7cd35d39ca
--- /dev/null
+++ b/apps/desktop/src/main/deepLinkWindowsRegistration.ts
@@ -0,0 +1,27 @@
+import { execFile } from 'node:child_process';
+import { promisify } from 'node:util';
+import { BRAND_IDENTITY } from '@cindy/maker-shared/brand-identity';
+import { DEEP_LINK_SCHEMES } from '../shared/deepLinkSchemes';
+import { createLogger } from './logger';
+
+const execFileAsync = promisify(execFile);
+const log = createLogger('deepLink');
+const options = { windowsHide: true, encoding: 'utf8' as const, timeout: 3_000 };
+
+/** Protocol-scoped name: never rename the shared Electron executable or other apps' handlers. */
+export async function registerWindowsDeepLinkName(scheme: string, platform = process.platform): Promise<void> {
+ if (platform !== 'win32' || !DEEP_LINK_SCHEMES.some(value => value === scheme)) return;
+ const key = `HKCU\\Software\\Classes\\${scheme}\\Application`;
+ try {
+ let existing = '';
+ try {
+ const result = await execFileAsync('reg.exe', ['query', key, '/v', 'ApplicationName'], options);
+ existing = /ApplicationName\s+REG_SZ\s+([^\r\n]*)/.exec(result.stdout)?.[1]?.trim() ?? '';
+ } catch { /* First registration has no Application metadata yet. */ }
+ if (existing === BRAND_IDENTITY.displayName) return;
+ await execFileAsync('reg.exe', ['add', key, '/v', 'ApplicationName', '/t', 'REG_SZ', '/d', BRAND_IDENTITY.displayName, '/f'], options);
+ } catch {
+ // A missing display label must never block startup or change the existing launch command.
+ log.warn('could not register protocol display name', { scheme });
+ }
+}
diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskApi.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskApi.test.ts
index a3042f6838..662009d97c 100644
--- a/apps/desktop/src/main/device-link/__tests__/sharedTaskApi.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskApi.test.ts
@@ -3,7 +3,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
const state = vi.hoisted(() => ({ key: 'account:1', endpoint: 'https://relay.example.test', authenticated: true, boundary: false, accountId: 'owner', region: 'global', token: 'test-old-token' }));
const http = vi.hoisted(() => vi.fn());
vi.mock('../../appSessionState.js', () => ({ activeOwnerScopeKey: () => state.key, isAppSessionBoundaryPending: () => state.boundary }));
-vi.mock('../../authManager.js', () => ({ getAuthState: () => ({ isAuthenticated: state.authenticated }),
+vi.mock('../../authManager.js', () => ({ getAuthState: () => ({ isAuthenticated: state.authenticated, user: { name: 'Account Guest' } }),
getCurrentUserId: () => state.accountId, getActiveAuthRealm: () => state.region, getAccessToken: () => state.token }));
vi.mock('../../clientEndpointsService.js', () => ({ getClientEndpoint: () => state.endpoint }));
vi.mock('../../serverApiClient.js', () => ({ serverApiFetch: http }));
@@ -15,6 +15,24 @@ beforeEach(() => {
http.mockReset();
});
describe('sharedTask Main HTTP adapter', () => {
+ it('adds a fragment invitation link without changing the legacy invite result', async () => {
+ const invitation = 'A'.repeat(43);
+ http.mockResolvedValue({ sharedTaskId: 'shared', invitation });
+ await expect(sharedTaskApi.invite('shared')).resolves.toEqual({ sharedTaskId: 'shared', invitation,
+ invitationLink: state.endpoint + '/shared-task/join#' + invitation });
+ });
+ it('joins a link using the account nickname even when an old caller supplies a custom name', async () => {
+ const invitation = 'A'.repeat(43);
+ http.mockResolvedValue({ sharedTaskId: 'shared', memberId: 'member', status: 'joined', created: true });
+ await sharedTaskApi.join(state.endpoint + '/shared-task/join#' + invitation, 'Custom name');
+ expect(http).toHaveBeenCalledWith('/api/device-link/shared-tasks/join', expect.objectContaining({
+ body: { invitation, displayName: 'Account Guest' },
+ }));
+ });
+ it('rejects another service before making any request', async () => {
+ await expect(sharedTaskApi.join('https://other.example.test/shared-task/join#' + 'A'.repeat(43), 'Guest')).rejects.toThrow('REGION_MISMATCH');
+ expect(http).not.toHaveBeenCalled();
+ });
it.each([['NOT_FOUND', 'NOT_FOUND'], ['PERMISSION_DENIED', 'PERMISSION_DENIED'],
['INVALID_PARAMS', 'INVALID_PARAMS'], ['NETWORK_ERROR', 'DEVICE_LINK_NOT_CONNECTED']])(
'retains actionable %s across the Electron boundary without leaking details', async (code, ipcCode) => {
diff --git a/apps/desktop/src/main/device-link/sharedTaskApi.ts b/apps/desktop/src/main/device-link/sharedTaskApi.ts
index 68a9b9a401..95a0a41c90 100644
--- a/apps/desktop/src/main/device-link/sharedTaskApi.ts
+++ b/apps/desktop/src/main/device-link/sharedTaskApi.ts
@@ -1,4 +1,4 @@
-import { createSharedTaskApi, SharedTaskScopeChangedError } from '@cindy/device-link';
+import { buildSharedTaskInvitationLink, createSharedTaskApi, parseSharedTaskInvitation, sharedTaskAccountName, SharedTaskScopeChangedError } from '@cindy/device-link';
import { activeOwnerScopeKey, isAppSessionBoundaryPending } from '../appSessionState.js';
import { getAccessToken, getActiveAuthRealm, getAuthState, getCurrentUserId } from '../authManager.js';
import { getClientEndpoint } from '../clientEndpointsService.js';
@@ -6,7 +6,7 @@ import { serverApiFetch } from '../serverApiClient.js';
import { throwIpcError } from '../utils/ipcValidate.js';
/** Main-owned adapter. Tokens remain inside the existing authenticated HTTP client. */
-export const sharedTaskApi = createSharedTaskApi({
+const accountApi = createSharedTaskApi({
captureScope() {
const key = activeOwnerScopeKey();
const endpoint = getClientEndpoint('deviceLinkApiBaseUrl');
@@ -47,6 +47,23 @@ export const sharedTaskApi = createSharedTaskApi({
},
});
+export const sharedTaskApi = {
+ ...accountApi,
+ async invite(sharedTaskId: string) {
+ const endpoint = getClientEndpoint('deviceLinkApiBaseUrl');
+ const result = await accountApi.invite(sharedTaskId);
+ // Keep the bare token for older controlling clients; new clients copy the link.
+ const region = import.meta.env.VITE_CINDY_AUTH_REGION;
+ const app = region === 'cn' ? 'cindycn' : region === 'dev' ? 'cindydev' : 'cindy';
+ return { ...result, invitationLink: buildSharedTaskInvitationLink(result.invitation, endpoint, app) };
+ },
+ async join(input: string, _displayName: string) {
+ const parsed = parseSharedTaskInvitation(input, getClientEndpoint('deviceLinkApiBaseUrl'));
+ if (!parsed.ok) throwIpcError(parsed.reason === 'different-server' ? 'REGION_MISMATCH' : 'INVALID_PARAMS', 'Invalid shared task invitation or service mismatch');
+ return accountApi.join(parsed.invitation, sharedTaskAccountName(getAuthState().user?.name));
+ },
+};
+
/** Capture only while the outgoing identity still owns the credentials. Unlike
* ordinary requests, this close-only cleanup may cross the pending boundary:
* its endpoint/token never refresh, and errors cannot log out the next account. */
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index eae807a9aa..1de1430ba6 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -3733,6 +3733,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
| { type: 'new-session'; workingDir: string }
| { type: 'share-import'; filePath: string }
| { type: 'provider-import'; importId: string }
+ | { type: 'shared-task-join'; invitation: string; server: string }
| { type: 'settings'; tab: 'voice-input' | 'providers'; connect?: string },
) => void,
): (() => void) =>
@@ -3744,6 +3745,8 @@ contextBridge.exposeInMainWorld('electronAPI', {
workingDir?: unknown;
filePath?: unknown;
importId?: unknown;
+ invitation?: unknown;
+ server?: unknown;
tab?: unknown;
connect?: unknown;
messageClientId?: unknown;
@@ -3769,6 +3772,8 @@ contextBridge.exposeInMainWorld('electronAPI', {
tab: p.tab,
...(p.tab === 'providers' && p.connect !== undefined ? { connect: p.connect } : {}),
});
+ } else if (p.type === 'shared-task-join' && typeof p.invitation === 'string' && /^[A-Za-z0-9_-]{43}$/.test(p.invitation) && typeof p.server === 'string' && p.server.length <= 2048) {
+ callback({ type: 'shared-task-join', invitation: p.invitation, server: p.server });
} else if (
p.type === 'provider-import' &&
typeof p.importId === 'string' &&
@@ -3805,6 +3810,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
| { type: 'new-session'; workingDir: string }
| { type: 'share-import'; filePath: string }
| { type: 'provider-import'; importId: string }
+ | { type: 'shared-task-join'; invitation: string; server: string }
| { type: 'settings'; tab: 'voice-input' | 'providers'; connect?: string }
| null
> => ipcRenderer.invoke('deep-link:take-pending'),
diff --git a/apps/desktop/src/renderer/components/layout/MainLayout.tsx b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
index e757e06b6e..8745ddbba7 100644
--- a/apps/desktop/src/renderer/components/layout/MainLayout.tsx
+++ b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
@@ -1,4 +1,6 @@
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
+import { buildSharedTaskInvitationLink } from '@cindy/device-link';
+import { JoinSharedTaskDialog } from '@/features/device-link/JoinSharedTaskDialog';
import { Outlet, useLocation, useNavigate } from 'react-router-dom';
import { useRememberMainEntry } from './MainEntryRedirect';
import { useTranslation } from 'react-i18next';
@@ -227,6 +229,8 @@ export function MainLayout() {
usePendingAlertAttention();
const splitGroup = useSplitGroup();
const [isSidebarCollapsed, setIsSidebarCollapsed] = useState(getInitialCollapsed);
+ const [sharedTaskInvitation, setSharedTaskInvitation] = useState<{ link: string; id: number } | null>(null);
+ const invitationSequence = useRef(0);
const [shareImportRequest, setShareImportRequest] = useState<{
id: number;
filePath: string;
@@ -627,8 +631,13 @@ export function MainLayout() {
| { type: 'new-session'; workingDir: string }
| { type: 'share-import'; filePath: string }
| { type: 'provider-import'; importId: string }
+ | { type: 'shared-task-join'; invitation: string; server: string }
| { type: 'settings'; tab: 'voice-input' | 'providers'; connect?: string },
) => {
+ if (payload.type === 'shared-task-join') {
+ setSharedTaskInvitation({ link: buildSharedTaskInvitationLink(payload.invitation, payload.server), id: ++invitationSequence.current });
+ return;
+ }
if (payload.type === 'session') {
navigateToSession(payload.id, payload.messageClientId);
return;
@@ -670,7 +679,7 @@ export function MainLayout() {
);
useEffect(() => {
const unsubscribe = window.electronAPI.onDeepLinkNavigate((payload) => {
- if (payload.type !== 'provider-import') {
+ if (payload.type !== 'provider-import' && payload.type !== 'shared-task-join') {
handleDeepLinkPayload(payload);
return;
}
@@ -1650,6 +1659,8 @@ export function MainLayout() {
)}
{/* FeiShu Bot conflict dialog -- subscribes to main process push and surfaces a global modal */}
<FeishuConflictDialogHost />
+ {sharedTaskInvitation && <JoinSharedTaskDialog key={sharedTaskInvitation.id} open initialInvitation={sharedTaskInvitation.link}
+ onOpenChange={(open) => { if (!open) setSharedTaskInvitation(null); }} />}
{/* 窗口级拖拽兜底:拖 .cshare 进窗口空白处 → 会话导入向导 */}
<GlobalDropImportListener onOpenShareImport={openShareImport} />
{shareImportRequest && (
diff --git a/apps/desktop/src/renderer/features/device-link/JoinSharedTaskDialog.tsx b/apps/desktop/src/renderer/features/device-link/JoinSharedTaskDialog.tsx
index 64ee30aa9e..9c8609fa62 100644
--- a/apps/desktop/src/renderer/features/device-link/JoinSharedTaskDialog.tsx
+++ b/apps/desktop/src/renderer/features/device-link/JoinSharedTaskDialog.tsx
@@ -1,5 +1,5 @@
import { SharedTaskDialog } from './SharedTaskDialog';
-export function JoinSharedTaskDialog(props: { open: boolean; onOpenChange(open: boolean): void }) {
+export function JoinSharedTaskDialog(props: { initialInvitation?: string; open: boolean; onOpenChange(open: boolean): void }) {
return <SharedTaskDialog {...props} />;
}
diff --git a/apps/desktop/src/renderer/features/device-link/SharedTaskDialog.tsx b/apps/desktop/src/renderer/features/device-link/SharedTaskDialog.tsx
index 5b4a9a1faa..537df1fd23 100644
--- a/apps/desktop/src/renderer/features/device-link/SharedTaskDialog.tsx
+++ b/apps/desktop/src/renderer/features/device-link/SharedTaskDialog.tsx
@@ -4,7 +4,7 @@ import { ArrowLeft, Check, Clock, FileText, Link2, Users, X } from 'lucide-react
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import {
- parseSharedTaskPeer, sharedTaskHostPeer, SHARED_TASK_HOST_CHANNEL,
+ parseSharedTaskPeer, sharedTaskHostPeer, sharedTaskAccountName, SHARED_TASK_HOST_CHANNEL,
type SharedTaskDetail, type SharedTaskHostCommand,
type SharedTaskHostState, type SharedTaskListItem, type SharedTaskOwnedItem,
} from '@cindy/device-link';
@@ -36,12 +36,14 @@ function host(target: Target, command: SharedTaskHostCommand) {
}
/** Both entry points share one window. Confirmations replace its content, not its identity. */
-export function SharedTaskDialog({ open, onOpenChange, session, returnFocus }: {
- open: boolean; onOpenChange(open: boolean): void; session?: Session; returnFocus?(): void;
+export function SharedTaskDialog({ open, onOpenChange, session, returnFocus, initialInvitation }: {
+ open: boolean; onOpenChange(open: boolean): void; session?: Session; returnFocus?(): void; initialInvitation?: string;
}) {
const { t } = useTranslation();
const navigate = useNavigate();
- const { dataOwnerId, isAuthenticated } = useAuth();
+ const { dataOwnerId, isAuthenticated, user } = useAuth();
+ const invitationOwner = useRef(getDataOwnerGeneration());
+ const autoAttempted = useRef<string | null>(null);
const ownerGeneration = getDataOwnerGeneration().generation;
const initialTarget = useMemo<Target | null>(() => {
if (!session) return null;
@@ -57,8 +59,7 @@ export function SharedTaskDialog({ open, onOpenChange, session, returnFocus }: {
const [joined, setJoined] = useState<SharedTaskListItem[] | null>(null);
const [listErrors, setListErrors] = useState({ owned: false, joined: false });
const [invitation, setInvitation] = useState('');
- const [nickname, setNickname] = useState('');
- const [errors, setErrors] = useState<{ invitation?: string; nickname?: string }>({});
+ const [errors, setErrors] = useState<{ invitation?: string }>({});
const [success, setSuccess] = useState<{ sharedTaskId: string; title: string } | null>(null);
const [confirm, setConfirm] = useState<Confirmation | null>(null);
const [busy, setBusy] = useState(false);
@@ -68,7 +69,6 @@ export function SharedTaskDialog({ open, onOpenChange, session, returnFocus }: {
const pending = useRef(false);
const lists = useRef({ owned: { sequence: 0, loading: false }, joined: { sequence: 0, loading: false } });
const codeInput = useRef<HTMLInputElement>(null);
- const nicknameInput = useRef<HTMLInputElement>(null);
const keep = useRef<HTMLButtonElement>(null);
const panel = useRef<HTMLDivElement>(null);
const confirmationOrigin = useRef<Origin>(null);
@@ -128,11 +128,12 @@ export function SharedTaskDialog({ open, onOpenChange, session, returnFocus }: {
epoch.current++; targetEpoch.current++; invalidateLists();
setTab('join'); setTarget(initialTarget); setState(null); setDetailError(null);
setOwned(null); setJoined(null); setListErrors({ owned: false, joined: false });
- setInvitation(''); setNickname(''); setErrors({}); setSuccess(null); setConfirm(null);
+ setInvitation(isDataOwnerGenerationCurrent(invitationOwner.current) ? initialInvitation ?? '' : '');
+ setErrors({}); setSuccess(null); setConfirm(null);
pending.current = false; setBusy(false);
if (open && isAuthenticated) { void loadList('owned'); void loadList('joined'); }
return () => { epoch.current++; targetEpoch.current++; invalidateLists(); };
- }, [open, dataOwnerId, ownerGeneration, isAuthenticated, initialTarget, loadList]);
+ }, [open, dataOwnerId, ownerGeneration, isAuthenticated, initialTarget, initialInvitation, loadList]);
useEffect(() => {
setState(null); setDetailError(null);
if (open && target && isAuthenticated) void loadDetail(target, target.connect);
@@ -232,23 +233,23 @@ export function SharedTaskDialog({ open, onOpenChange, session, returnFocus }: {
void loadList('joined');
}
});
- const join = () => {
- const next = { invitation: !/^[A-Za-z0-9_-]{43}$/.test(invitation.trim()) ? 'sharedTask.invalidInvitation' : undefined,
- nickname: !nickname.trim() ? 'sharedTask.missingNickname' : undefined };
+ const join = (enter = false) => {
+ const next = { invitation: !invitation.trim() || invitation.length > 8192 ? 'sharedTask.invalidInvitation' : undefined };
setErrors(next);
- if (next.invitation || next.nickname) { (next.invitation ? codeInput : nicknameInput).current?.focus(); return; }
+ if (next.invitation) { codeInput.current?.focus(); return; }
void run(async current => {
try {
- const result = await window.electronAPI.sharedTask.account({ action: 'join', invitation: invitation.trim(), displayName: nickname.trim() }) as { sharedTaskId: string };
+ const result = await window.electronAPI.sharedTask.account({ action: 'join', invitation: invitation.trim(), displayName: sharedTaskAccountName(user?.name) }) as { sharedTaskId: string };
if (!current()) return;
setInvitation(''); setSuccess({ sharedTaskId: result.sharedTaskId, title: '' });
invalidateLists(); void loadList('joined');
const joinedDetail = await window.electronAPI.sharedTask.account({ action: 'get', sharedTaskId: result.sharedTaskId }) as SharedTaskDetail;
if (current()) setSuccess({ sharedTaskId: result.sharedTaskId, title: joinedDetail.title });
+ if (enter && current()) await enterTask(result.sharedTaskId, current);
} catch (error) { if (current()) toast.error(t(sharedTaskErrorKey(error, 'join'))); }
});
};
- const openTask = (sharedTaskId: string) => void run(async current => {
+ const enterTask = async (sharedTaskId: string, current: Current) => {
const item = await window.electronAPI.sharedTask.account({ action: 'get', sharedTaskId }) as SharedTaskDetail;
if (!current()) return;
const peer = sharedTaskHostPeer(item.sharedTaskId, item.hostDeviceId);
@@ -263,12 +264,19 @@ export function SharedTaskDialog({ open, onOpenChange, session, returnFocus }: {
if (!current() || remoteSession?.id !== item.sessionId) return;
remoteProjectsStore.setDeviceSessions(peer, item.title, [remoteSession]);
navigate('/cc-agent/' + encodeURIComponent(item.sessionId)); onOpenChange(false);
- });
+ };
+ const openTask = (sharedTaskId: string) => void run(current => enterTask(sharedTaskId, current));
+ useEffect(() => {
+ if (!open || !isAuthenticated || !initialInvitation || invitation !== initialInvitation
+ || autoAttempted.current === initialInvitation || !isDataOwnerGenerationCurrent(invitationOwner.current)) return;
+ autoAttempted.current = initialInvitation;
+ join(true);
+ }, [open, isAuthenticated, initialInvitation, invitation, ownerGeneration]);
const invite = () => void run(async current => {
if (!detail || !target) return;
- const result = await host(target, { action: 'invite', sharedTaskId: detail.sharedTaskId }) as { invitation: string };
+ const result = await host(target, { action: 'invite', sharedTaskId: detail.sharedTaskId }) as { invitation: string; invitationLink?: string };
if (!current()) return;
- try { await navigator.clipboard.writeText(result.invitation); }
+ try { await navigator.clipboard.writeText(result.invitationLink ?? result.invitation); }
catch { if (current()) toast.error(t('sharedTask.invitationCopyFailed')); return; }
if (current()) toast.success(t('sharedTask.invitationCopied'));
});
@@ -363,7 +371,6 @@ export function SharedTaskDialog({ open, onOpenChange, session, returnFocus }: {
<p className="mb-5 text-13 text-[var(--text-secondary)]">{t('sharedTask.joinIntro')}</p>
<form onSubmit={event => { event.preventDefault(); join(); }} className="space-y-3">
<FormField label={t('sharedTask.invitation')} required reserveFeedback error={errors.invitation && t(errors.invitation)}>{props => <Input {...props} inputRef={codeInput} value={invitation} onChange={value => { setInvitation(value); setErrors(previous => ({ ...previous, invitation: undefined })); }} disabled={busy} surface="ivory" autoComplete="off" spellCheck={false} placeholder={t('sharedTask.invitationPlaceholder')} />}</FormField>
- <FormField label={t('sharedTask.joinNickname')} required reserveFeedback error={errors.nickname && t(errors.nickname)}>{props => <Input {...props} inputRef={nicknameInput} value={nickname} onChange={value => { setNickname(value); setErrors(previous => ({ ...previous, nickname: undefined })); }} maxLength={32} disabled={busy} surface="ivory" autoComplete="off" placeholder={t('sharedTask.nicknamePlaceholder')} />}</FormField>
{notice(t('sharedTask.joinNotice'))}<div className="flex justify-end pt-3"><Button type="submit" variant="cta" size="lg" loading={busy}>{t('sharedTask.join')}</Button></div>
</form>
</div>
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.tsx
index bbe38edf05..15ef879766 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
@@ -9,7 +9,7 @@ import { toast } from '@/lib/toast';
const state = vi.hoisted(() => ({ account: vi.fn(), host: vi.fn(), openLink: vi.fn(), closeLink: vi.fn(), invoke: vi.fn(), setSessions: vi.fn(), removeDevice: vi.fn(), getSessions: vi.fn(), bind: vi.fn(), reset: vi.fn() }));
vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string, args?: { title?: string }) => key + (args?.title ? ':' + args.title : '') }) }));
-vi.mock('@/contexts/AuthContext', () => ({ useAuth: () => ({ dataOwnerId: 'guest', isAuthenticated: true }) }));
+vi.mock('@/contexts/AuthContext', () => ({ useAuth: () => ({ dataOwnerId: 'guest', isAuthenticated: true, user: { name: 'Account Guest' } }) }));
vi.mock('@/lib/toast', () => ({ toast: { error: vi.fn(), success: vi.fn() } }));
vi.mock('../remoteProjectsStore', () => ({ remoteProjectsStore: { getDeviceName: () => undefined, setDeviceSessions: state.setSessions, removeDevice: state.removeDevice, getMergedRemoteSessions: state.getSessions }, isRemoteDeviceMarkedDisconnected: () => false }));
vi.mock('@/lib/remoteDataOwnerPushFence', () => ({ bindSharedTaskPushOwner: state.bind, resetRemoteDataOwnerPushFence: state.reset }));
@@ -53,7 +53,6 @@ function click(key: string) { fireEvent.click(screen.getByRole('button', { name:
function visibleText(text: string) { return screen.queryAllByText(text).filter(el => !el.closest('[hidden]')); }
function fill(submit = true) {
fireEvent.change(screen.getByLabelText('sharedTask.invitation'), { target: { value: 'A'.repeat(43) } });
- fireEvent.change(screen.getByLabelText('sharedTask.joinNickname'), { target: { value: 'Guest' } });
if (submit) click('join');
}
async function closeAll() { tab('owned'); await screen.findByRole('button', { name: 'sharedTask.closeAll' }); click('closeAll'); }
@@ -62,20 +61,19 @@ it('starts with three tabs and a compact join form without host actions', async
open(); await act(async () => {});
expect(screen.getAllByRole('tab')).toHaveLength(3);
expect(screen.getByLabelText('sharedTask.invitation').tagName).toBe('INPUT');
- expect(screen.getByLabelText('sharedTask.joinNickname').getAttribute('maxlength')).toBe('32');
+ expect(screen.queryByLabelText('sharedTask.joinNickname')).toBeNull();
expect(screen.queryByRole('button', { name: 'sharedTask.closeAll' })).toBeNull();
expect(document.activeElement).toBe(screen.getByLabelText('sharedTask.invitation'));
});
-it('validates each field and focuses the nickname when the code is valid', () => {
+it('requires an invitation and uses the account name for a link', async () => {
open(); click('join');
expect(screen.getByText('sharedTask.invalidInvitation')).toBeTruthy();
- expect(screen.getByText('sharedTask.missingNickname')).toBeTruthy();
expect(document.activeElement).toBe(screen.getByLabelText('sharedTask.invitation'));
- fireEvent.change(screen.getByLabelText('sharedTask.invitation'), { target: { value: 'A'.repeat(43) } });
+ const link = 'https://relay.example.test/shared-task/join#' + 'A'.repeat(43);
+ fireEvent.change(screen.getByLabelText('sharedTask.invitation'), { target: { value: link } });
click('join');
+ await waitFor(() => expect(state.account).toHaveBeenCalledWith({ action: 'join', invitation: link, displayName: 'Account Guest' }));
expect(screen.queryByText('sharedTask.invalidInvitation')).toBeNull();
- expect(document.activeElement).toBe(screen.getByLabelText('sharedTask.joinNickname'));
- expect(state.account).not.toHaveBeenCalledWith(expect.objectContaining({ action: 'join' }));
});
it.each([['NOT_FOUND', 'sharedTask.invitationUnavailable'], ['PERMISSION_DENIED', 'sharedTask.invitationRenew']])('explains rejected %s invitations without losing input', async (code, key) => {
state.account.mockImplementation(async ({ action }) => { if (action === 'join') throw new Error('[' + code + '] rejected'); return []; });
@@ -89,7 +87,6 @@ it('preserves the form across all tabs and supports arrow-key tab navigation', a
fireEvent.keyDown(screen.getByRole('tab', { name: /sharedTask.joinedTab/ }), { key: 'ArrowRight' });
expect(screen.getByRole('tab', { name: /sharedTask.tabOwned/ }).getAttribute('aria-selected')).toBe('true');
tab('join'); expect((screen.getByLabelText('sharedTask.invitation') as HTMLInputElement).value).toBe('A'.repeat(43));
- expect((screen.getByLabelText('sharedTask.joinNickname') as HTMLInputElement).value).toBe('Guest');
});
it.each(['closeAllKeep', 'cancelOperation'])('cancels in the same window through %s and preserves the form', async key => {
open(); fill(false); await closeAll();
@@ -195,3 +192,30 @@ it('does not clean up a new account after a late leave response', async () => {
await act(async () => { setDataOwnerGeneration('other'); finish({}); });
expect(state.removeDevice).not.toHaveBeenCalled(); expect(state.closeLink).not.toHaveBeenCalled();
});
+
+it('joins and enters an incoming invitation only once', async () => {
+ const close = vi.fn();
+ const invitation = 'https://relay.example.test/shared-task/join#' + 'A'.repeat(43);
+ const view = render(<MemoryRouter><JoinSharedTaskDialog open initialInvitation={invitation} onOpenChange={close} /></MemoryRouter>);
+ await waitFor(() => expect(close).toHaveBeenCalledWith(false));
+ view.rerender(<MemoryRouter><JoinSharedTaskDialog open initialInvitation={invitation} onOpenChange={close} /></MemoryRouter>);
+ expect(state.account.mock.calls.filter(([command]) => command.action === 'join')).toHaveLength(1);
+ expect(state.openLink).toHaveBeenCalledTimes(1);
+});
+it('does not carry an incoming invitation into another account', async () => {
+ const close = vi.fn();
+ const invitation = 'https://relay.example.test/shared-task/join#' + 'A'.repeat(43);
+ const original = state.account.getMockImplementation()!;
+ let finish!: (value: unknown) => void;
+ state.account.mockImplementation(command => command.action === 'join' ? new Promise(resolve => { finish = resolve; }) : original(command));
+ const view = render(<MemoryRouter><JoinSharedTaskDialog open initialInvitation={invitation} onOpenChange={close} /></MemoryRouter>);
+ await waitFor(() => expect(finish).toBeTypeOf('function'));
+ await act(async () => {
+ setDataOwnerGeneration('other');
+ view.rerender(<MemoryRouter><JoinSharedTaskDialog open initialInvitation={invitation} onOpenChange={close} /></MemoryRouter>);
+ finish({ sharedTaskId: joinedTask.sharedTaskId });
+ });
+ expect(state.openLink).not.toHaveBeenCalled();
+ expect(close).not.toHaveBeenCalled();
+ expect((screen.getByLabelText('sharedTask.invitation') as HTMLInputElement).value).toBe('');
+});
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.tsx
index 346509beee..511df821c3 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
@@ -75,10 +75,12 @@ it('starts an unshared task and loads its members', async () => {
it('distinguishes a clipboard failure from a request failure and allows retry', async () => {
const copy = vi.fn().mockRejectedValue(new DOMException('Not focused', 'NotAllowedError'));
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText: copy } });
- state.host.mockImplementation(async c => c.action === 'invite' ? { invitation: 'test-invitation' } : { available: true, detail });
+ const invitationLink = 'https://relay.example.test/shared-task/join#' + 'A'.repeat(43);
+ state.host.mockImplementation(async c => c.action === 'invite' ? { invitation: 'test-invitation', invitationLink } : { available: true, detail });
await openWindow(); click('invite'); await waitFor(() => expect(toast.error).toHaveBeenCalledWith('sharedTask.invitationCopyFailed'));
expect(toast.success).not.toHaveBeenCalled(); copy.mockResolvedValue(undefined); click('invite');
await waitFor(() => expect(toast.success).toHaveBeenCalledWith('sharedTask.invitationCopied'));
+ expect(copy).toHaveBeenLastCalledWith(invitationLink);
});
it('does not copy when generating an invitation fails', async () => {
const copy = vi.fn(); Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText: copy } });
diff --git a/apps/desktop/src/renderer/features/device-link/sharedTaskCompatibility.ts b/apps/desktop/src/renderer/features/device-link/sharedTaskCompatibility.ts
index 953f9a1c62..78dd385e75 100644
--- a/apps/desktop/src/renderer/features/device-link/sharedTaskCompatibility.ts
+++ b/apps/desktop/src/renderer/features/device-link/sharedTaskCompatibility.ts
@@ -3,6 +3,8 @@ import { extractIpcError } from '@/utils/ipcError';
/** Only explicit capability failures imply an upgrade; offline is retryable. */
export function sharedTaskErrorKey(error: unknown, context: 'join' | 'operation' = 'operation') {
const code = extractIpcError(error)?.code;
+ if (context === 'join' && code === 'INVALID_PARAMS') return 'sharedTask.invalid';
+ if (context === 'join' && code === 'REGION_MISMATCH') return 'sharedTask.invitationDifferentServer';
if (code === 'NOT_FOUND') return context === 'join' ? 'sharedTask.invitationUnavailable' : 'sharedTask.unavailable';
if (code === 'PERMISSION_DENIED') return context === 'join' ? 'sharedTask.invitationRenew' : 'sharedTask.permissionDenied';
if (code === 'DEVICE_LINK_ACCESS_REVOKED') return 'sharedTask.unavailable';
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index d24c3f3058..27ca9b3dbb 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -58,46 +58,44 @@
"leaveShort": "Leave Sharing",
"joinTab": "Join Shared Task",
"joinedEmptyTitle": "No Shared Tasks Joined",
- "joinedEmptyHint": "Enter the host’s invitation code in “Join Shared Task”.",
+ "joinedEmptyHint": "Enter the host’s invitation link in “Join Shared Task”.",
"joinedLoadFailed": "Could not load your joined shared tasks. Try again.",
"joinedTab": "Joined",
"reconnecting": "Reconnecting…",
"ownedLoadFailed": "Unable to load",
"loadingOwned": "Loading…",
"retryAction": "Retry",
- "invitationCopyFailed": "The invitation code was created but could not be copied. Return to this window and try again.",
- "accessEndedBody": "You no longer have access to this shared task. To rejoin, ask the host for a new invitation code.",
- "joinIntro": "Enter the invitation code from the host to join the shared task.",
- "invitationPlaceholder": "Enter or paste the invitation code",
- "joinNickname": "Your Name in This Task",
- "nicknamePlaceholder": "What should we call you?",
+ "invitationCopyFailed": "Could not copy the invitation link. Try again.",
+ "accessEndedBody": "You no longer have access to this shared task. To rejoin, ask the host for a new invitation link.",
+ "joinIntro": "Paste the host’s invitation link to join using your account name.",
+ "invitationPlaceholder": "Paste an invitation link or code",
"joinNotice": "After joining, you can view the full history and message the Agent directly, without waiting for host approval.",
"joinedTitle": "Joined “{{title}}”",
"joined": "Joined Shared Task",
"joinedBody": "You can view earlier messages, tool results and attachments, and message the same Agent.",
"enterTask": "Enter Task",
- "inviteBoxTitle": "Invite someone to join",
+ "inviteBoxTitle": "Send the invitation link to your teammates",
"roleGuest": "Guest",
"removeShort": "Remove",
"removeNamedTitle": "Remove {{name}}?",
"manage": "Manage",
"ended": "Sharing Ended",
- "rejoin": "Join with a new code",
+ "rejoin": "Join with a new link",
"otherDevice": "Other Computer",
"runsOnHostDevice": "Running on the host computer",
- "remoteHostOfflineNote": "Sharing ends automatically if the host computer stays offline. The host must start sharing again and send a new invitation code to resume.",
+ "remoteHostOfflineNote": "Sharing ends automatically if the host computer stays offline. The host must start sharing again and send a new invitation link to resume.",
"waitingHost": "Waiting for the host to respond. You can continue sending messages.",
"join": "Join Shared Task",
"login": "Sign in to Cindy to join a task.",
- "invitation": "Invitation Code",
+ "invitation": "Invitation Link",
"dismiss": "Close Dialog",
"title": "Share Task",
"hostLimit": "You've reached the current limit for hosted shared tasks. Close shared tasks until you're below the limit, then try again.",
"joinLimit": "You've reached the current limit for joined shared tasks. Leave shared tasks until you're below the limit, then try again.",
"guestLimit": "This shared task already has 2 guests. You cannot join it yet.",
- "invitationUnavailable": "This invitation code is invalid or expired. Ask the host for a new code.",
- "invitationRenew": "This invitation code cannot be used to rejoin. Ask the host for a new code.",
- "unavailable": "Sharing has ended or you no longer have access. Ask the host for a new invitation code.",
+ "invitationUnavailable": "This invitation link is invalid or expired. Ask the host for a new link.",
+ "invitationRenew": "This invitation link cannot be used to rejoin. Ask the host for a new link.",
+ "unavailable": "Sharing has ended or you no longer have access. Ask the host for a new invitation link.",
"permissionDenied": "You do not have permission for this action. Contact the host.",
"connectionFailed": "Cannot connect to the sharing service or the host computer. Check your network and try again.",
"requestTimedOut": "The request timed out. Check your network and the host computer’s connection, then try again.",
@@ -106,45 +104,46 @@
"open": "Start Sharing",
"host": "Host",
"remove": "Remove Guest",
- "invite": "Copy Invitation Code",
- "invitationCopied": "Invitation code copied",
+ "invite": "Copy Invitation Link",
+ "invitationCopied": "Invitation link copied",
"tabOwned": "Shared by Me",
"startIntro": "Invite a partner to read everything in this task and work with the same Agent.",
"runsOnThisDevice": "Runs on this device",
- "inviteNotice": "Anyone holding the invitation code can join after signing in, with the same Agent access as the host.",
+ "inviteNotice": "Anyone holding the invitation link can join after signing in, with the same Agent access as the host.",
"offlineAutoClose": "Sharing ends automatically if the host computer stays offline.",
"inviteBoxHint": "Teammates enter the code to join the shared task",
"membersWithLimit": "Members · {{count}} (up to 2 guests)",
"me": "Me",
"thisDevice": "This device",
"roleHost": "Host",
- "hostOfflineNote": "Sharing ends automatically if this computer stays offline. Start sharing again and send a new invitation code to resume.",
+ "hostOfflineNote": "Sharing ends automatically if this computer stays offline. Start sharing again and send a new invitation link to resume.",
"sharingBadge": "Sharing",
"ownedEmptyTitle": "Nothing is being shared",
"ownedEmptyHint": "Open any task and click “Share Task” to invite a partner.",
"closeAll": "Stop all sharing ({{count}})",
"closeAllTitle": "Stop all sharing?",
- "closeAllBody": "All guests will lose access to the tasks below, and their invitation codes will expire.",
+ "closeAllBody": "All guests will lose access to the tasks below, and their invitation links will expire.",
"closeAllKeep": "Keep Sharing",
"closeAllAction": "Stop sharing {{count}} tasks",
"closeAllScopeNote": "Task history and Agent work are kept; tasks you joined stay unaffected.",
- "closeOneBody": "All guests will lose access and the invitation code will expire.",
- "removeBody": "The guest will lose access. Rejoining requires a new invitation code from the host.",
+ "closeOneBody": "All guests will lose access and the invitation link will expire.",
+ "removeBody": "The guest will lose access. Rejoining requires a new invitation link from the host.",
"removeKeep": "Keep Guest",
"leaveTitle": "Leave this shared task?",
- "leaveBody": "You will lose access to this task. To rejoin, ask the host for a new invitation code.",
+ "leaveBody": "You will lose access to this task. To rejoin, ask the host for a new invitation link.",
"leaveKeep": "Stay in Task",
"closedToast": "Stopped sharing {{count}} tasks",
"closeFailedToast": "Could not stop sharing {{count}} tasks. Try again later.",
"back": "Back",
"cancelOperation": "Cancel action",
- "invalidInvitation": "Enter a valid invitation code",
- "missingNickname": "Enter your nickname for this task",
+ "invalidInvitation": "Paste a valid invitation link or code.",
"ownedManageIntro": "Manage tasks you share, including those on other computers.",
"joinedManageIntro": "Open a task to continue working, or leave a shared task you no longer need.",
"recordsKept": "Task history and Agent work are kept.",
"othersUnaffected": "Other members and Agent work are not affected.",
- "viewJoined": "View joined tasks"
+ "viewJoined": "View joined tasks",
+ "invalid": "Paste a valid invitation link or code.",
+ "invitationDifferentServer": "This invitation belongs to another Cindy service. Open the link in the matching app."
},
"privacyExit": {
"status": "This computer is being remotely controlled through Cindy",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index c76eacd766..b842d4296f 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -58,46 +58,44 @@
"leaveShort": "共有から退出",
"joinTab": "共有に参加",
"joinedEmptyTitle": "参加中の共有タスクはありません",
- "joinedEmptyHint": "「共有に参加」でホストの招待コードを入力してください。",
+ "joinedEmptyHint": "「共有に参加」でホストの招待リンクを入力してください。",
"joinedLoadFailed": "参加中の共有タスクを取得できませんでした。再試行してください。",
"joinedTab": "参加",
"reconnecting": "再接続中…",
"ownedLoadFailed": "取得できません",
"loadingOwned": "取得中…",
"retryAction": "再試行",
- "invitationCopyFailed": "招待コードは作成されましたが、コピーできませんでした。このウィンドウに戻って再試行してください。",
- "accessEndedBody": "この共有セッションにはアクセスできません。再参加するには、ホストから新しい招待コードを受け取ってください。",
- "joinIntro": "ホストから届いた招待コードを入力して、共有セッションに参加します。",
- "invitationPlaceholder": "招待コードを入力または貼り付け",
- "joinNickname": "タスク内でのニックネーム",
- "nicknamePlaceholder": "表示する名前",
+ "invitationCopyFailed": "招待リンクをコピーできませんでした。もう一度お試しください。",
+ "accessEndedBody": "この共有セッションにはアクセスできません。再参加するには、ホストから新しい招待リンクを受け取ってください。",
+ "joinIntro": "ホストからの招待リンクを貼り付けると、アカウント名でタスクに参加します。",
+ "invitationPlaceholder": "招待リンクまたは招待コードを貼り付け",
"joinNotice": "参加するとすべての履歴を閲覧でき、ホストの承認を待たずに Agent にメッセージを送信できます。",
"joinedTitle": "「{{title}}」に参加しました",
"joined": "共有タスクに参加しました",
"joinedBody": "参加前のメッセージ、ツールの結果、添付ファイルを確認し、同じ Agent にメッセージを送信できます。",
"enterTask": "タスクを開く",
- "inviteBoxTitle": "仲間を招待",
+ "inviteBoxTitle": "招待リンクを仲間に送信",
"roleGuest": "ゲスト",
"removeShort": "削除",
"removeNamedTitle": "{{name}}を削除しますか?",
"manage": "管理",
"ended": "共有が終了しました",
- "rejoin": "新しい招待コードで参加",
+ "rejoin": "新しい招待リンクで参加",
"otherDevice": "他のパソコン",
"runsOnHostDevice": "ホストのパソコンで実行中",
- "remoteHostOfflineNote": "ホストのパソコンがオフラインのままだと、共有は自動的に終了します。ホストによる共有の再開と新しい招待コードの送信が必要です。",
+ "remoteHostOfflineNote": "ホストのパソコンがオフラインのままだと、共有は自動的に終了します。ホストによる共有の再開と新しい招待リンクの送信が必要です。",
"waitingHost": "ホストの対応を待っています。引き続きメッセージを送信できます。",
"join": "共有セッションに参加",
"login": "セッションに参加するには Cindy にログインしてください。",
- "invitation": "招待コード",
+ "invitation": "招待リンク",
"dismiss": "ダイアログを閉じる",
"title": "セッションを共有",
"hostLimit": "共有タスクの開始数が現在の上限に達しました。上限を下回るまで共有タスクを終了してから再試行してください。",
"joinLimit": "参加中の共有タスクが現在の上限に達しました。上限を下回るまで共有タスクから退出してから再試行してください。",
"guestLimit": "この共有タスクにはすでにゲストが 2 人いるため、参加できません。",
- "invitationUnavailable": "招待コードが無効か期限切れです。ホストに新しいコードを依頼してください。",
- "invitationRenew": "この招待コードでは再参加できません。ホストに新しいコードを依頼してください。",
- "unavailable": "共有が終了したか、アクセス権がありません。ホストに新しい招待コードを依頼してください。",
+ "invitationUnavailable": "招待リンクが無効か期限切れです。ホストに新しいリンクを依頼してください。",
+ "invitationRenew": "この招待リンクでは再参加できません。ホストに新しいリンクを依頼してください。",
+ "unavailable": "共有が終了したか、アクセス権がありません。ホストに新しい招待リンクを依頼してください。",
"permissionDenied": "この操作を行う権限がありません。ホストに連絡してください。",
"connectionFailed": "共有サービスまたはホストのコンピューターに接続できません。ネットワークを確認して再試行してください。",
"requestTimedOut": "リクエストがタイムアウトしました。ネットワークとホストのコンピューターの接続を確認して再試行してください。",
@@ -106,45 +104,46 @@
"open": "共有を開始",
"host": "ホスト",
"remove": "ゲストを削除",
- "invite": "招待コードをコピー",
- "invitationCopied": "招待コードをコピーしました",
+ "invite": "招待リンクをコピー",
+ "invitationCopied": "招待リンクをコピーしました",
"tabOwned": "自分が共有中",
"startIntro": "パートナーを招待して、このセッションのすべての内容を共有し、同じ Agent で協力できます。",
"runsOnThisDevice": "このパソコンで実行中",
- "inviteNotice": "招待コードを持つユーザーはログイン後に参加でき、所有者と同じ Agent 権限を持ちます。",
+ "inviteNotice": "招待リンクを持つユーザーはログイン後に参加でき、所有者と同じ Agent 権限を持ちます。",
"offlineAutoClose": "ホストのパソコンがオフラインのままだと、共有は自動的に終了します。",
- "inviteBoxHint": "仲間は招待コードを入力して共有セッションに参加できます",
+ "inviteBoxHint": "仲間は招待リンクを入力して共有セッションに参加できます",
"membersWithLimit": "メンバー · {{count}} 人(ゲストは最大 2 人)",
"me": "自分",
"thisDevice": "このパソコン",
"roleHost": "ホスト",
- "hostOfflineNote": "このパソコンがオフラインのままだと、共有は自動的に終了します。再開するには共有を開始し、新しい招待コードを送信してください。",
+ "hostOfflineNote": "このパソコンがオフラインのままだと、共有は自動的に終了します。再開するには共有を開始し、新しい招待リンクを送信してください。",
"sharingBadge": "共有中",
"ownedEmptyTitle": "共有中のセッションはありません",
"ownedEmptyHint": "任意のセッションを開いて「セッションを共有」から招待できます。",
"closeAll": "すべての共有を停止({{count}})",
"closeAllTitle": "すべての共有を停止しますか?",
- "closeAllBody": "以下のセッションにすべてのゲストがアクセスできなくなり、招待コードは無効になります。",
+ "closeAllBody": "以下のセッションにすべてのゲストがアクセスできなくなり、招待リンクは無効になります。",
"closeAllKeep": "共有を続ける",
"closeAllAction": "{{count}} 件の共有を停止",
"closeAllScopeNote": "セッションの記録と Agent の作業は保持され、自分が参加している他のセッションには影響しません。",
- "closeOneBody": "すべてのゲストはアクセスできなくなり、招待コードは無効になります。",
- "removeBody": "そのゲストはアクセスできなくなります。再参加にはホストの新しい招待コードが必要です。",
+ "closeOneBody": "すべてのゲストはアクセスできなくなり、招待リンクは無効になります。",
+ "removeBody": "そのゲストはアクセスできなくなります。再参加にはホストの新しい招待リンクが必要です。",
"removeKeep": "ゲストを残す",
"leaveTitle": "共有セッションから退出しますか?",
- "leaveBody": "退出すると、このセッションにアクセスできなくなります。再参加するには、ホストから新しい招待コードを受け取ってください。",
+ "leaveBody": "退出すると、このセッションにアクセスできなくなります。再参加するには、ホストから新しい招待リンクを受け取ってください。",
"leaveKeep": "セッションに残る",
"closedToast": "{{count}} 件の共有を停止しました",
"closeFailedToast": "{{count}} 件の共有を停止できませんでした。後でもう一度お試しください。",
"back": "戻る",
"cancelOperation": "操作をキャンセル",
- "invalidInvitation": "有効な招待コードを入力してください",
- "missingNickname": "このセッションで使うニックネームを入力してください",
+ "invalidInvitation": "有効な招待リンクまたは招待コードを貼り付けてください。",
"ownedManageIntro": "他のパソコンを含め、自分が共有しているセッションを管理できます。",
"joinedManageIntro": "セッションを開いて作業を続けるか、参加しなくなった共有セッションから退出できます。",
"recordsKept": "セッションの履歴と Agent の作業は保持されます。",
"othersUnaffected": "他のメンバーや Agent の作業には影響しません。",
- "viewJoined": "参加中のセッションを表示"
+ "viewJoined": "参加中のセッションを表示",
+ "invalid": "有効な招待リンクまたは招待コードを貼り付けてください。",
+ "invitationDifferentServer": "この招待は別の Cindy サービスのものです。対応するアプリでリンクを開いてください。"
},
"privacyExit": {
"status": "Cindy でリモート操作されています",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index acf113d14e..ab353dcbdd 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -58,46 +58,44 @@
"leaveShort": "공유 나가기",
"joinTab": "공유 참여",
"joinedEmptyTitle": "참여 중인 공유 작업이 없습니다",
- "joinedEmptyHint": "“공유 참여”에서 호스트의 초대 코드를 입력하세요.",
+ "joinedEmptyHint": "“공유 참여”에서 호스트의 초대 링크를 입력하세요.",
"joinedLoadFailed": "참여 중인 공유 작업을 불러오지 못했습니다. 다시 시도하세요.",
"joinedTab": "참여",
"reconnecting": "다시 연결 중…",
"ownedLoadFailed": "불러올 수 없음",
"loadingOwned": "불러오는 중…",
"retryAction": "다시 시도",
- "invitationCopyFailed": "초대 코드가 생성되었지만 복사하지 못했습니다. 이 창으로 돌아와 다시 시도해 주세요.",
- "accessEndedBody": "이 공유 작업에 더 이상 접근할 수 없습니다. 다시 참여하려면 호스트에게 새 초대 코드를 요청하세요.",
- "joinIntro": "호스트가 보낸 초대 코드를 입력하여 공유 세션에 참여하세요.",
- "invitationPlaceholder": "초대 코드 입력 또는 붙여넣기",
- "joinNickname": "작업에서 사용할 닉네임",
- "nicknamePlaceholder": "표시할 이름",
+ "invitationCopyFailed": "초대 링크를 복사하지 못했습니다. 다시 시도하세요.",
+ "accessEndedBody": "이 공유 작업에 더 이상 접근할 수 없습니다. 다시 참여하려면 호스트에게 새 초대 링크를 요청하세요.",
+ "joinIntro": "호스트의 초대 링크를 붙여넣으면 계정 이름으로 작업에 참여합니다.",
+ "invitationPlaceholder": "초대 링크 또는 초대 코드 붙여넣기",
"joinNotice": "참여하면 전체 기록을 보고 호스트의 승인을 기다리지 않고 Agent에게 메시지를 보낼 수 있습니다.",
"joinedTitle": "「{{title}}」에 참여했습니다",
"joined": "공유 작업에 참여했습니다",
"joinedBody": "참여 전의 메시지, 도구 결과, 첨부 파일을 확인하고 같은 Agent에게 메시지를 보낼 수 있습니다.",
"enterTask": "작업 열기",
- "inviteBoxTitle": "함께할 사람 초대",
+ "inviteBoxTitle": "동료에게 초대 링크 보내기",
"roleGuest": "게스트",
"removeShort": "제거",
"removeNamedTitle": "{{name}} 님을 제거할까요?",
"manage": "관리",
"ended": "공유가 종료되었습니다",
- "rejoin": "새 초대 코드로 참여",
+ "rejoin": "새 초대 링크로 참여",
"otherDevice": "다른 컴퓨터",
"runsOnHostDevice": "호스트 컴퓨터에서 실행 중",
- "remoteHostOfflineNote": "호스트 컴퓨터가 계속 오프라인 상태이면 공유가 자동으로 종료됩니다. 호스트가 공유를 다시 시작하고 새 초대 코드를 보내야 합니다.",
+ "remoteHostOfflineNote": "호스트 컴퓨터가 계속 오프라인 상태이면 공유가 자동으로 종료됩니다. 호스트가 공유를 다시 시작하고 새 초대 링크를 보내야 합니다.",
"waitingHost": "호스트의 응답을 기다리고 있습니다. 메시지는 계속 보낼 수 있습니다.",
"join": "공유 세션 참여",
"login": "세션에 참가하려면 Cindy에 로그인하세요.",
- "invitation": "초대 코드",
+ "invitation": "초대 링크",
"dismiss": "대화 상자 닫기",
"title": "세션 공유",
"hostLimit": "공유 중인 작업 수가 현재 한도에 도달했습니다. 한도 미만이 될 때까지 공유 작업을 종료한 후 다시 시도하세요.",
"joinLimit": "참여 중인 공유 작업 수가 현재 한도에 도달했습니다. 한도 미만이 될 때까지 공유 작업에서 나간 후 다시 시도하세요.",
"guestLimit": "이 공유 작업에는 이미 게스트가 2명 있어 참여할 수 없습니다.",
- "invitationUnavailable": "초대 코드가 유효하지 않거나 만료되었습니다. 호스트에게 새 코드를 요청하세요.",
- "invitationRenew": "이 초대 코드로는 다시 참여할 수 없습니다. 호스트에게 새 코드를 요청하세요.",
- "unavailable": "공유가 종료되었거나 접근 권한이 없습니다. 호스트에게 새 초대 코드를 요청하세요.",
+ "invitationUnavailable": "초대 링크가 유효하지 않거나 만료되었습니다. 호스트에게 새 코드를 요청하세요.",
+ "invitationRenew": "이 초대 링크로는 다시 참여할 수 없습니다. 호스트에게 새 코드를 요청하세요.",
+ "unavailable": "공유가 종료되었거나 접근 권한이 없습니다. 호스트에게 새 초대 링크를 요청하세요.",
"permissionDenied": "이 작업을 수행할 권한이 없습니다. 호스트에게 문의하세요.",
"connectionFailed": "공유 서비스 또는 호스트 컴퓨터에 연결할 수 없습니다. 네트워크를 확인한 후 다시 시도하세요.",
"requestTimedOut": "요청 시간이 초과되었습니다. 네트워크와 호스트 컴퓨터의 연결을 확인한 후 다시 시도하세요.",
@@ -106,45 +104,46 @@
"open": "공유 시작",
"host": "호스트",
"remove": "게스트 내보내기",
- "invite": "초대 코드 복사",
- "invitationCopied": "초대 코드를 복사했습니다",
+ "invite": "초대 링크 복사",
+ "invitationCopied": "초대 링크를 복사했습니다",
"tabOwned": "내가 공유한 항목",
"startIntro": "파트너를 초대해 이 세션의 모든 내용을 함께 보고, 같은 Agent로 협업하세요.",
"runsOnThisDevice": "이 PC에서 실행 중",
- "inviteNotice": "초대 코드를 가진 사용자는 로그인 후 참여할 수 있으며, 호스트와 동일한 Agent 권한을 갖습니다.",
+ "inviteNotice": "초대 링크를 가진 사용자는 로그인 후 참여할 수 있으며, 호스트와 동일한 Agent 권한을 갖습니다.",
"offlineAutoClose": "호스트 컴퓨터가 계속 오프라인 상태이면 공유가 자동으로 종료됩니다.",
- "inviteBoxHint": "동료가 초대 코드를 입력하면 공유 세션에 참여할 수 있습니다",
+ "inviteBoxHint": "동료가 초대 링크를 입력하면 공유 세션에 참여할 수 있습니다",
"membersWithLimit": "멤버 · {{count}}명 (최대 게스트 2명)",
"me": "나",
"thisDevice": "이 PC",
"roleHost": "호스트",
- "hostOfflineNote": "이 컴퓨터가 계속 오프라인 상태이면 공유가 자동으로 종료됩니다. 다시 공유하려면 공유를 시작하고 새 초대 코드를 보내세요.",
+ "hostOfflineNote": "이 컴퓨터가 계속 오프라인 상태이면 공유가 자동으로 종료됩니다. 다시 공유하려면 공유를 시작하고 새 초대 링크를 보내세요.",
"sharingBadge": "공유 중",
"ownedEmptyTitle": "공유 중인 세션이 없습니다",
"ownedEmptyHint": "아무 세션이나 열고 \"세션 공유\"를 눌러 파트너를 초대하세요.",
"closeAll": "모든 공유 중지 ({{count}})",
"closeAllTitle": "모든 공유를 중지할까요?",
- "closeAllBody": "모든 게스트가 아래 작업에 접근할 수 없게 되며 초대 코드가 만료됩니다.",
+ "closeAllBody": "모든 게스트가 아래 작업에 접근할 수 없게 되며 초대 링크가 만료됩니다.",
"closeAllKeep": "공유 유지",
"closeAllAction": "작업 {{count}}개 공유 중지",
"closeAllScopeNote": "세션 기록과 Agent 작업은 유지되며, 내가 참여한 다른 세션에는 영향이 없습니다.",
- "closeOneBody": "모든 게스트가 접근할 수 없게 되고 초대 코드는 만료됩니다.",
- "removeBody": "해당 게스트는 접근할 수 없게 됩니다. 다시 참여하려면 호스트의 새 초대 코드가 필요합니다.",
+ "closeOneBody": "모든 게스트가 접근할 수 없게 되고 초대 링크는 만료됩니다.",
+ "removeBody": "해당 게스트는 접근할 수 없게 됩니다. 다시 참여하려면 호스트의 새 초대 링크가 필요합니다.",
"removeKeep": "게스트 유지",
"leaveTitle": "공유 세션에서 나설까요?",
- "leaveBody": "나가면 이 작업에 접근할 수 없습니다. 다시 참여하려면 호스트에게 새 초대 코드를 요청하세요.",
+ "leaveBody": "나가면 이 작업에 접근할 수 없습니다. 다시 참여하려면 호스트에게 새 초대 링크를 요청하세요.",
"leaveKeep": "세션에 남기",
"closedToast": "작업 {{count}}개의 공유를 중지했습니다",
"closeFailedToast": "작업 {{count}}개의 공유를 중지하지 못했습니다. 나중에 다시 시도하세요.",
"back": "뒤로",
"cancelOperation": "작업 취소",
- "invalidInvitation": "유효한 초대 코드를 입력하세요",
- "missingNickname": "이 작업에서 사용할 닉네임을 입력하세요",
+ "invalidInvitation": "유효한 초대 링크 또는 초대 코드를 붙여넣으세요.",
"ownedManageIntro": "다른 컴퓨터의 작업을 포함하여 내가 공유한 작업을 관리합니다.",
"joinedManageIntro": "작업을 열어 계속 진행하거나 더 이상 참여하지 않는 공유 작업에서 나갈 수 있습니다.",
"recordsKept": "작업 기록과 Agent 작업은 유지됩니다.",
"othersUnaffected": "다른 멤버와 Agent 작업에는 영향을 주지 않습니다.",
- "viewJoined": "참여한 작업 보기"
+ "viewJoined": "참여한 작업 보기",
+ "invalid": "유효한 초대 링크 또는 초대 코드를 붙여넣으세요.",
+ "invitationDifferentServer": "다른 Cindy 서비스의 초대입니다. 해당 앱에서 링크를 여세요."
},
"privacyExit": {
"status": "Cindy를 통해 원격 제어 중입니다",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 36a7de60d5..282bdc6b4e 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -58,46 +58,44 @@
"leaveShort": "退出共享",
"joinTab": "加入共享",
"joinedEmptyTitle": "还没有加入共享任务",
- "joinedEmptyHint": "在「加入共享」中填入房主提供的邀请码。",
+ "joinedEmptyHint": "在「加入共享」中填入房主提供的邀请链接。",
"joinedLoadFailed": "暂时无法获取已加入的共享任务,请重试",
"joinedTab": "我加入的",
"reconnecting": "正在重新连接…",
"ownedLoadFailed": "暂时无法获取",
"loadingOwned": "正在获取…",
"retryAction": "重试",
- "invitationCopyFailed": "邀请码已生成,但未能复制。请回到此窗口后重试。",
- "accessEndedBody": "当前已无法访问这个共享任务。如需再次加入,请联系房主发送新的邀请码。",
- "joinIntro": "填入房主发来的邀请码,加入共享任务。",
- "invitationPlaceholder": "请输入或粘贴邀请码",
- "joinNickname": "你在任务中的昵称",
- "nicknamePlaceholder": "怎么称呼你",
+ "invitationCopyFailed": "未能复制邀请链接,请重试",
+ "accessEndedBody": "当前已无法访问这个共享任务。如需再次加入,请联系房主发送新的邀请链接。",
+ "joinIntro": "粘贴房主发来的邀请链接,使用你的账号昵称加入任务。",
+ "invitationPlaceholder": "粘贴邀请链接或邀请码",
"joinNotice": "加入后可查看全部历史,并直接向 Agent 发消息,无需等待房主审批。",
"joinedTitle": "已加入「{{title}}」",
"joined": "已加入共享任务",
"joinedBody": "你可以查看加入前的消息、工具结果和附件,也可以向同一个 Agent 发消息。",
"enterTask": "进入任务",
- "inviteBoxTitle": "邀请伙伴加入",
+ "inviteBoxTitle": "将邀请链接发给你的伙伴",
"roleGuest": "访客",
"removeShort": "移除",
"removeNamedTitle": "移除{{name}}?",
"manage": "管理",
"ended": "共享已结束",
- "rejoin": "使用新邀请码加入",
+ "rejoin": "使用新邀请链接加入",
"otherDevice": "其他电脑",
"runsOnHostDevice": "运行在房主电脑",
- "remoteHostOfflineNote": "房主电脑持续离线后,共享会自动结束。再次共享需重新开启并发送新的邀请码。",
+ "remoteHostOfflineNote": "房主电脑持续离线后,共享会自动结束。再次共享需重新开启并发送新的邀请链接。",
"waitingHost": "等待房主处理,你可以继续发送消息。",
"join": "加入共享任务",
"login": "请登录 Cindy 后加入任务",
- "invitation": "邀请码",
+ "invitation": "邀请链接",
"dismiss": "关闭窗口",
"title": "共享任务",
"hostLimit": "开启的共享任务已达当前上限,请关闭共享任务,直到数量低于上限后再试。",
"joinLimit": "加入的共享任务已达当前上限,请退出共享任务,直到数量低于上限后再试。",
"guestLimit": "此共享任务已有 2 名访客,暂时无法加入。",
- "invitationUnavailable": "邀请码无效或已失效,请向房主获取新的邀请码",
- "invitationRenew": "旧邀请码无法再次加入,请向房主获取新的邀请码",
- "unavailable": "共享已结束或你已无权访问,请向房主获取新的邀请码",
+ "invitationUnavailable": "邀请链接无效或已失效,请向房主获取新的邀请链接",
+ "invitationRenew": "旧邀请链接无法再次加入,请向房主获取新的邀请链接",
+ "unavailable": "共享已结束或你已无权访问,请向房主获取新的邀请链接",
"permissionDenied": "你没有权限执行此操作,请联系房主",
"connectionFailed": "无法连接共享服务或房主电脑,请检查网络后重试",
"requestTimedOut": "请求超时,请检查网络和房主电脑的连接后重试",
@@ -106,45 +104,46 @@
"open": "开启共享",
"host": "房主",
"remove": "移除访客",
- "invite": "复制邀请码",
- "invitationCopied": "邀请码已复制",
+ "invite": "复制邀请链接",
+ "invitationCopied": "邀请链接已复制",
"tabOwned": "我发起的",
"startIntro": "邀请伙伴查看这个任务的全部内容,一起与同一个 Agent 协作。",
"runsOnThisDevice": "运行在这台电脑",
- "inviteNotice": "持有邀请码的用户登录后即可加入,拥有与房主相同的 Agent 使用权限。",
+ "inviteNotice": "持有邀请链接的用户登录后即可加入,拥有与房主相同的 Agent 使用权限。",
"offlineAutoClose": "房主电脑持续离线后,共享会自动结束。",
- "inviteBoxHint": "伙伴填入邀请码后,即可加入共享任务",
+ "inviteBoxHint": "伙伴打开链接后,即可加入共享任务",
"membersWithLimit": "成员 · {{count}} 人(最多 2 位访客)",
"me": "我",
"thisDevice": "这台电脑",
"roleHost": "房主",
- "hostOfflineNote": "这台电脑持续离线后,共享会自动结束。再次共享需重新开启并发送新的邀请码。",
+ "hostOfflineNote": "这台电脑持续离线后,共享会自动结束。再次共享需重新开启并发送新的邀请链接。",
"sharingBadge": "共享中",
"ownedEmptyTitle": "没有正在共享的任务",
"ownedEmptyHint": "回到任意任务,点击「共享任务」邀请伙伴。",
"closeAll": "取消全部共享({{count}})",
"closeAllTitle": "取消全部共享?",
- "closeAllBody": "以下任务的所有访客将无法继续访问,原邀请码将失效。",
+ "closeAllBody": "以下任务的所有访客将无法继续访问,原邀请链接将失效。",
"closeAllKeep": "保持共享",
"closeAllAction": "取消 {{count}} 个共享",
"closeAllScopeNote": "任务记录和 Agent 工作保留;你加入别人的任务不受影响。",
- "closeOneBody": "所有访客将无法继续访问,原邀请码将失效。",
- "removeBody": "该访客将无法继续访问。再次加入需要房主生成新的邀请码。",
+ "closeOneBody": "所有访客将无法继续访问,原邀请链接将失效。",
+ "removeBody": "该访客将无法继续访问。再次加入需要房主生成新的邀请链接。",
"removeKeep": "保留访客",
"leaveTitle": "退出共享任务?",
- "leaveBody": "退出后将无法访问这个任务。再次加入需要房主发送新的邀请码。",
+ "leaveBody": "退出后将无法访问这个任务。再次加入需要房主发送新的邀请链接。",
"leaveKeep": "留在任务",
"closedToast": "已取消 {{count}} 个任务的共享",
"closeFailedToast": "部分共享未能取消({{count}} 项),可稍后重试。",
"back": "返回",
"cancelOperation": "取消操作",
- "invalidInvitation": "请输入有效的邀请码",
- "missingNickname": "请输入你在任务中的昵称",
+ "invalidInvitation": "请粘贴有效的邀请链接或邀请码",
"ownedManageIntro": "管理你发起的共享,包括其他电脑上的任务。",
"joinedManageIntro": "打开任务继续工作,或退出不再参与的共享。",
"recordsKept": "任务记录和 Agent 工作保留。",
"othersUnaffected": "其他成员与 Agent 的工作不受影响。",
- "viewJoined": "查看我加入的"
+ "viewJoined": "查看我加入的",
+ "invalid": "请粘贴有效的邀请链接或邀请码",
+ "invitationDifferentServer": "此邀请属于其他 Cindy 服务,请用对应的客户端打开链接"
},
"privacyExit": {
"status": "正在通过 Cindy 被远程控制",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index c7c3b084db..d1c40b700b 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -58,46 +58,44 @@
"leaveShort": "退出共享",
"joinTab": "加入共享",
"joinedEmptyTitle": "尚未加入共享任務",
- "joinedEmptyHint": "在「加入共享」中填入房主提供的邀請碼。",
+ "joinedEmptyHint": "在「加入共享」中填入房主提供的邀請連結。",
"joinedLoadFailed": "暫時無法取得已加入的共享任務,請重試",
"joinedTab": "我加入的",
"reconnecting": "正在重新連線…",
"ownedLoadFailed": "暫時無法取得",
"loadingOwned": "正在取得…",
"retryAction": "重試",
- "invitationCopyFailed": "邀請碼已產生,但未能複製。請回到此視窗後重試。",
- "accessEndedBody": "目前已無法存取此共享任務。如需再次加入,請聯絡房主傳送新的邀請碼。",
- "joinIntro": "填入房主傳來的邀請碼,加入共享任務。",
- "invitationPlaceholder": "請輸入或貼上邀請碼",
- "joinNickname": "你在任務中的暱稱",
- "nicknamePlaceholder": "怎麼稱呼你",
+ "invitationCopyFailed": "無法複製邀請連結,請重試",
+ "accessEndedBody": "目前已無法存取此共享任務。如需再次加入,請聯絡房主傳送新的邀請連結。",
+ "joinIntro": "貼上房主傳來的邀請連結,使用你的帳號暱稱加入任務。",
+ "invitationPlaceholder": "貼上邀請連結或邀請碼",
"joinNotice": "加入後可查看全部歷史,並直接向 Agent 傳送訊息,無需等待房主審批。",
"joinedTitle": "已加入「{{title}}」",
"joined": "已加入共享任務",
"joinedBody": "你可以查看加入前的訊息、工具結果和附件,也可以向同一個 Agent 傳送訊息。",
"enterTask": "進入任務",
- "inviteBoxTitle": "邀請夥伴加入",
+ "inviteBoxTitle": "將邀請連結傳給你的夥伴",
"roleGuest": "訪客",
"removeShort": "移除",
"removeNamedTitle": "移除{{name}}?",
"manage": "管理",
"ended": "共享已結束",
- "rejoin": "使用新邀請碼加入",
+ "rejoin": "使用新邀請連結加入",
"otherDevice": "其他電腦",
"runsOnHostDevice": "在房主電腦上執行",
- "remoteHostOfflineNote": "房主電腦持續離線後,共享會自動結束。再次共享需重新開啟並傳送新的邀請碼。",
+ "remoteHostOfflineNote": "房主電腦持續離線後,共享會自動結束。再次共享需重新開啟並傳送新的邀請連結。",
"waitingHost": "等待房主處理,你可以繼續傳送訊息。",
"join": "加入共享任務",
"login": "請登入 Cindy 後加入任務",
- "invitation": "邀請碼",
+ "invitation": "邀請連結",
"dismiss": "關閉視窗",
"title": "共享任務",
"hostLimit": "開啟的共享任務已達目前上限,請關閉共享任務,直到數量低於上限後再試。",
"joinLimit": "加入的共享任務已達目前上限,請退出共享任務,直到數量低於上限後再試。",
"guestLimit": "此共享任務已有 2 名訪客,暫時無法加入。",
- "invitationUnavailable": "邀請碼無效或已失效,請向房主取得新的邀請碼",
- "invitationRenew": "舊邀請碼無法再次加入,請向房主取得新的邀請碼",
- "unavailable": "共享已結束或你已無權存取,請向房主取得新的邀請碼",
+ "invitationUnavailable": "邀請連結無效或已失效,請向房主取得新的邀請連結",
+ "invitationRenew": "舊邀請連結無法再次加入,請向房主取得新的邀請連結",
+ "unavailable": "共享已結束或你已無權存取,請向房主取得新的邀請連結",
"permissionDenied": "你沒有權限執行此操作,請聯絡房主",
"connectionFailed": "無法連接共享服務或房主電腦,請檢查網路後重試",
"requestTimedOut": "請求逾時,請檢查網路和房主電腦的連線後重試",
@@ -106,45 +104,46 @@
"open": "開啟共享",
"host": "主持人",
"remove": "移除訪客",
- "invite": "複製邀請碼",
- "invitationCopied": "邀請碼已複製",
+ "invite": "複製邀請連結",
+ "invitationCopied": "邀請連結已複製",
"tabOwned": "我發起的",
"startIntro": "邀請夥伴查看這個任務的全部內容,一起與同一個 Agent 協作。",
"runsOnThisDevice": "執行在這台電腦",
- "inviteNotice": "持有邀請碼的使用者登入後即可加入,擁有與房主相同的 Agent 使用權限。",
+ "inviteNotice": "持有邀請連結的使用者登入後即可加入,擁有與房主相同的 Agent 使用權限。",
"offlineAutoClose": "房主電腦持續離線後,共享會自動結束。",
- "inviteBoxHint": "夥伴填入邀請碼後,即可加入共享任務",
+ "inviteBoxHint": "夥伴開啟連結後,即可加入共享任務",
"membersWithLimit": "成員 · {{count}} 人(最多 2 位訪客)",
"me": "我",
"thisDevice": "這台電腦",
"roleHost": "房主",
- "hostOfflineNote": "這台電腦持續離線後,共享會自動結束。再次共享需重新開啟並傳送新的邀請碼。",
+ "hostOfflineNote": "這台電腦持續離線後,共享會自動結束。再次共享需重新開啟並傳送新的邀請連結。",
"sharingBadge": "共享中",
"ownedEmptyTitle": "沒有正在共享的任務",
"ownedEmptyHint": "回到任意任務,點擊「共享任務」邀請夥伴。",
"closeAll": "取消全部共享({{count}})",
"closeAllTitle": "取消全部共享?",
- "closeAllBody": "以下任務的所有訪客將無法繼續存取,原邀請碼將失效。",
+ "closeAllBody": "以下任務的所有訪客將無法繼續存取,原邀請連結將失效。",
"closeAllKeep": "保持共享",
"closeAllAction": "取消 {{count}} 個共享",
"closeAllScopeNote": "任務記錄和 Agent 工作保留;你加入別人的任務不受影響。",
- "closeOneBody": "所有訪客將無法繼續存取,原邀請碼將失效。",
- "removeBody": "該訪客將無法繼續存取。再次加入需要房主產生新的邀請碼。",
+ "closeOneBody": "所有訪客將無法繼續存取,原邀請連結將失效。",
+ "removeBody": "該訪客將無法繼續存取。再次加入需要房主產生新的邀請連結。",
"removeKeep": "保留訪客",
"leaveTitle": "離開共享任務?",
- "leaveBody": "退出後將無法存取這個任務。再次加入需要房主傳送新的邀請碼。",
+ "leaveBody": "退出後將無法存取這個任務。再次加入需要房主傳送新的邀請連結。",
"leaveKeep": "留在任務",
"closedToast": "已取消 {{count}} 個任務的共享",
"closeFailedToast": "部分共享未能取消({{count}} 項),可稍後重試。",
"back": "返回",
"cancelOperation": "取消操作",
- "invalidInvitation": "請輸入有效的邀請碼",
- "missingNickname": "請輸入你在任務中的暱稱",
+ "invalidInvitation": "請貼上有效的邀請連結或邀請碼",
"ownedManageIntro": "管理你發起的共享,包括其他電腦上的任務。",
"joinedManageIntro": "開啟任務繼續工作,或退出不再參與的共享。",
"recordsKept": "任務記錄和 Agent 工作會保留。",
"othersUnaffected": "其他成員與 Agent 的工作不受影響。",
- "viewJoined": "查看我加入的"
+ "viewJoined": "查看我加入的",
+ "invalid": "請貼上有效的邀請連結或邀請碼",
+ "invitationDifferentServer": "此邀請屬於其他 Cindy 服務,請用對應的用戶端開啟連結"
},
"privacyExit": {
"status": "正在透過 Cindy 被遠端控制",
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 4967502218..9476a0dc04 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -2938,6 +2938,7 @@ interface ElectronAPI {
| { type: 'new-session'; workingDir: string }
| { type: 'share-import'; filePath: string }
| { type: 'provider-import'; importId: string }
+ | { type: 'shared-task-join'; invitation: string; server: string }
| { type: 'settings'; tab: 'voice-input' | 'providers'; connect?: string },
) => void,
) => () => void;
@@ -2954,6 +2955,7 @@ interface ElectronAPI {
| { type: 'new-session'; workingDir: string }
| { type: 'share-import'; filePath: string }
| { type: 'provider-import'; importId: string }
+ | { type: 'shared-task-join'; invitation: string; server: string }
| { type: 'settings'; tab: 'voice-input' | 'providers'; connect?: string }
| null
>;
diff --git a/apps/mobile/app/+native-intent.ts b/apps/mobile/app/+native-intent.ts
index 812c1b4c03..42b1591e78 100644
--- a/apps/mobile/app/+native-intent.ts
+++ b/apps/mobile/app/+native-intent.ts
@@ -14,6 +14,7 @@
//
// 纯 JS(不进 @expo/fingerprint / 不改 runtimeVersion),可随热更下发。
+import { clearSharedTaskInvitationIntent, receiveSharedTaskInvitationIntent } from '@/device-link/sharedTaskInvitationIntent';
import { WECHAT_APP_ID, WECHAT_UNIVERSAL_LINK } from '@/config/env';
import { isWechatSdkCallback } from '@/auth/wechatCallback';
@@ -26,6 +27,8 @@ export function redirectSystemPath({ path, initial }: { path: string; initial: b
appId: WECHAT_APP_ID,
universalLink: WECHAT_UNIVERSAL_LINK,
})) return '/';
+ const invitationUrl = path.startsWith('/shared-session?') ? `cindy:/${path}` : path;
+ if (receiveSharedTaskInvitationIntent(invitationUrl)) return '/shared-session';
// path 可能是完整 URL('cindycn://auth?code=...')或路径('/auth?code=...'),统一取出 pathname。
const noScheme = path.replace(/^[a-zA-Z][\w+.-]*:\/\//, '/');
const pathname = noScheme.split('?')[0].split('#')[0].replace(/\/+$/, '') || '/';
@@ -34,6 +37,11 @@ export function redirectSystemPath({ path, initial }: { path: string; initial: b
// A restored launch URL is not proof of an unconsumed share. On cold start,
// let IncomingShareBridge navigate only after reading an actual pending batch.
if (pathname === '/expo-sharing') return initial ? '/' : '/sessions/new';
+ // Invalid invitations must not leave secrets in router state or diagnostics.
+ if (pathname === '/shared-session' || pathname === '/shared-task/join') {
+ clearSharedTaskInvitationIntent();
+ return '/shared-session';
+ }
return path;
} catch {
return path;
diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsx
index d77e606a84..f1ab17bf9b 100644
--- a/apps/mobile/app/_layout.tsx
+++ b/apps/mobile/app/_layout.tsx
@@ -77,12 +77,14 @@ import {
recoverPendingPrecreatedWorktrees,
} from '@/session/precreatedWorktreeRecovery';
import { IncomingShareBridge } from '@/session/IncomingShareBridge';
+import { usePendingSharedTaskInvitationIntent } from '@/device-link/sharedTaskInvitationIntent';
import { HomeEntryProvider, useHomeEntrySplashRelease } from '@/session/HomeEntryProvider';
import { RemoteDesktopHost } from '@/remote-desktop/RemoteDesktopHost';
const holdSplash = () => undefined;
function NavigationGate() {
+ const pendingSharedTaskInvitation = usePendingSharedTaskInvitationIntent();
const windowGeometry = useAdaptiveWindow();
// Establish chrome before push starts, rather than revealing a hidden bar after mount.
const sessionHeaderShown = Platform.OS === 'ios'
@@ -131,9 +133,12 @@ function NavigationGate() {
return;
}
if (auth.isAuthenticated && inAuthGroup) {
- router.replace('/');
+ if (pendingSharedTaskInvitation) router.replace('/shared-session');
+ else router.replace('/');
+ } else if (auth.isAuthenticated && pendingSharedTaskInvitation && segments.join('/') !== 'shared-session') {
+ router.replace('/shared-session');
}
- }, [auth.initialized, auth.isAuthenticated, router, segments]);
+ }, [auth.initialized, auth.isAuthenticated, pendingSharedTaskInvitation, router, segments]);
useEffect(() => {
if (!auth.isAuthenticated || !auth.accountDeletionRestored) return;
diff --git a/apps/mobile/app/shared-session.tsx b/apps/mobile/app/shared-session.tsx
index b3bccb06ea..a330a30929 100644
--- a/apps/mobile/app/shared-session.tsx
+++ b/apps/mobile/app/shared-session.tsx
@@ -1,11 +1,14 @@
import { useCallback, useEffect, useRef, useState } from 'react';
-import { AppState, Keyboard, StyleSheet, View } from 'react-native';
+import { AppState, Keyboard, Platform, StyleSheet, View } from 'react-native';
+import * as Clipboard from 'expo-clipboard';
import { useFocusEffect, useLocalSearchParams, useRouter } from 'expo-router';
import { useTranslation } from 'react-i18next';
import { Check, Clock, FileText, Laptop, Link, Users } from 'lucide-react-native';
-import { sharedTaskHostPeer, parseSharedTaskPeer, SHARED_TASK_HOST_CHANNEL,
+import { buildSharedTaskInvitationLink, parseSharedTaskInvitation, sharedTaskAccountName, sharedTaskHostPeer, parseSharedTaskPeer, SHARED_TASK_HOST_CHANNEL,
type SharedTaskHostCommand, type SharedTaskHostState, type SharedTaskListItem } from '@cindy/device-link';
import { useAuth } from '@/auth/AuthContext';
+import { APP_SCHEME, DEVICE_LINK_API_BASE_URL } from '@/config/env';
+import { clearSharedTaskInvitationIntent, usePendingSharedTaskInvitationIntent } from '@/device-link/sharedTaskInvitationIntent';
import { goBackGuarded } from '@/utils/backGuard';
import { getMobileAuthOwner, isMobileAuthOwnerCurrent } from '@/auth/authOwnerGeneration';
import { useDeviceLink } from '@/device-link/DeviceLinkContext';
@@ -29,14 +32,17 @@ export default function SharedSessionScreen() {
const { sessionId, deviceId, sharedTaskId } = useLocalSearchParams<{ sessionId?: string; deviceId?: string; sharedTaskId?: string }>();
const router = useRouter();
const { t } = useTranslation();
- const { isAuthenticated, accountGeneration } = useAuth();
+ const { isAuthenticated, accountGeneration, user } = useAuth();
+ const pasteOwner = getMobileAuthOwner();
+ const incomingInvitation = usePendingSharedTaskInvitationIntent();
const api = useSharedTaskApi();
const confirmation = useSharedTaskConfirmation();
const link = useDeviceLink();
const { colors } = useTheme();
const styles = useThemedStyles(makeStyles);
const [invitation, setInvitation] = useState('');
- const [name, setName] = useState('');
+ const [incomingLink, setIncomingLink] = useState<{ link: string; owner: ReturnType<typeof getMobileAuthOwner> } | null>(null);
+ const pasteVersion = useRef(0);
const [state, setState] = useState<SharedTaskHostState | null>(null);
const [owned, setOwned] = useState<SharedTaskListItem[]>([]);
const [guestCounts, setGuestCounts] = useState<Record<string, number>>({});
@@ -114,7 +120,8 @@ export default function SharedSessionScreen() {
mounted.current = true;
epoch.current++; pending.current = false; setBusy(false);
setState(null); setOwned([]); setGuestCounts({}); setJoinedId(undefined); setEnded(false);
- setInvitation(''); setName(''); setNotice(''); setLoadError(''); setTab('current'); confirmationPending.current = null;
+ setInvitation(''); setIncomingLink(null); pasteVersion.current++;
+ setNotice(''); setLoadError(''); setTab('current'); confirmationPending.current = null;
return () => { mounted.current = false; epoch.current++; };
}, [accountGeneration, deviceId, sessionId, sharedTaskId]);
useFocusEffect(useCallback(() => {
@@ -205,6 +212,50 @@ export default function SharedSessionScreen() {
else remoteSessionStore.setDeviceSessions(target, targetName, [task]);
router.replace({ pathname: '/sessions/[sessionId]', params: { sessionId: detail.sessionId, deviceId: target, deviceName: targetName } });
};
+ const joinInvitation = (input: string, enter = false) => void run(async (current) => {
+ const parsed = parseSharedTaskInvitation(input, DEVICE_LINK_API_BASE_URL);
+ if (!parsed.ok) { setNotice(t(parsed.reason === 'different-server' ? 'sharedTask.invitationDifferentServer' : 'sharedTask.invalid')); return; }
+ const joined = await api.join(parsed.invitation, sharedTaskAccountName(user?.name));
+ if (!current()) return;
+ Keyboard.dismiss(); setInvitation(''); setJoinedId(joined.sharedTaskId);
+ if (enter) await openTask(joined.sharedTaskId, current);
+ }, false, 'join');
+ useEffect(() => {
+ if (!incomingInvitation || !isAuthenticated || sessionId || deviceId || sharedTaskId) return;
+ const input = buildSharedTaskInvitationLink(incomingInvitation.invitation, incomingInvitation.server);
+ // Claim before waiting for relay capability. Leaving this screen discards the invitation.
+ epoch.current++; pending.current = false; setBusy(false);
+ setJoinedId(undefined); setState(null); setEnded(false); setTab('current');
+ setIncomingLink({ link: input, owner: getMobileAuthOwner() });
+ clearSharedTaskInvitationIntent();
+ setInvitation(input);
+ }, [incomingInvitation, isAuthenticated, sessionId, deviceId, sharedTaskId]);
+ useEffect(() => {
+ if (!incomingLink || !isMobileAuthOwnerCurrent(incomingLink.owner) || !isAuthenticated || link.sharedTaskAvailable !== true || guestId || pending.current) return;
+ setIncomingLink(null);
+ joinInvitation(incomingLink.link, true);
+ });
+ const acceptPaste = (text: string) => {
+ if (pending.current) return;
+ pasteVersion.current++;
+ setIncomingLink(null);
+ setInvitation(text.slice(0, 8192));
+ const parsed = parseSharedTaskInvitation(text, DEVICE_LINK_API_BASE_URL);
+ setNotice(parsed.ok ? '' : t(parsed.reason === 'different-server' ? 'sharedTask.invitationDifferentServer' : 'sharedTask.invalid'));
+ };
+ const pasteInvitation = async () => {
+ const owner = getMobileAuthOwner();
+ const page = pageGeneration.current;
+ const captured = epoch.current;
+ const version = ++pasteVersion.current;
+ const current = () => mounted.current && captured === epoch.current && version === pasteVersion.current && page === pageGeneration.current && isMobileAuthOwnerCurrent(owner);
+ try {
+ const text = await Clipboard.getStringAsync();
+ if (current()) acceptPaste(text);
+ } catch {
+ if (current()) setNotice(t('sharedTask.pasteFailed'));
+ }
+ };
const detail = state?.detail?.status === 'active' ? state.detail : null;
const ownDetail = !!detail && detail.ownerAccountId === getMobileAuthOwner().accountId;
const task = remoteSessionStore.getSessions().find((task) => task.id === sessionId && task.deviceLinkDeviceId === deviceId);
@@ -241,7 +292,7 @@ export default function SharedSessionScreen() {
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 <SharedTaskScreen
title={t(ended ? 'sharedTask.ended' : !guestId && tab === 'owned' ? 'sharedTask.ownedTitle' : hostContext || guestId ? 'sharedTask.title' : 'sharedTask.join')}
- onClose={() => goBackGuarded(router, '/devices')}>
+ onClose={() => { clearSharedTaskInvitationIntent(); setIncomingLink(null); goBackGuarded(router, '/devices'); }}>
{confirmation.dialog}
{!isAuthenticated ? <Text style={styles.intro}>{t('sharedTask.login')}</Text> : ended ? <SharedTaskEndedState onRejoin={() => {
setJoinedId(undefined); setEnded(false); setState(null); setNotice(''); setLoadError('');
@@ -283,7 +334,8 @@ export default function SharedSessionScreen() {
<SharedTaskAction compact action={{ label: t('sharedTask.invite'), tone: 'primary', disabled: busy, onPress: () => void run(async (current) => {
const result = await host({ action: 'invite', sharedTaskId: detail.sharedTaskId }) as { invitation: string };
if (!current()) return;
- try { await writeClipboardText(result.invitation); if (current()) setNotice(t('sharedTask.invitationCopied')); }
+ const invitationApp = APP_SCHEME === 'cindycn' ? 'cindycn' : APP_SCHEME === 'cindydev' ? 'cindydev' : 'cindy';
+ try { await writeClipboardText(buildSharedTaskInvitationLink(result.invitation, DEVICE_LINK_API_BASE_URL, invitationApp)); if (current()) setNotice(t('sharedTask.invitationCopied')); }
catch { if (current()) setNotice(t('sharedTask.invitationCopyFailed')); }
}, false) }} />
</View>
@@ -296,20 +348,23 @@ export default function SharedSessionScreen() {
<View style={styles.footer}><SharedTaskAction grow action={{ label: t('sharedTask.closeCurrent'), tone: 'danger', disabled: busy, onPress: () => confirm(t('sharedTask.closeOneTitle'), t('sharedTask.closeOneBody'), t('sharedTask.closeAllKeep'), t('sharedTask.close'), async () => { await host({ action: 'close', sharedTaskId: detail.sharedTaskId }); }) }} /></View>
</> : <>
<Text style={styles.intro}>{t('sharedTask.joinIntro')}</Text>
- <View style={styles.field}><Text style={styles.label}>{t('sharedTask.invitation')}</Text><TextInput accessibilityLabel={t('sharedTask.invitation')} placeholder={t('sharedTask.invitationPlaceholder')} placeholderTextColor={colors.textPlaceholder} style={[styles.input, styles.invitation]} value={invitation} onChangeText={setInvitation} multiline textAlignVertical="top" autoCapitalize="none" autoCorrect={false} editable={!busy} /></View>
- <View style={styles.field}><Text style={styles.label}>{t('sharedTask.joinNickname')}</Text><TextInput accessibilityLabel={t('sharedTask.joinNickname')} placeholder={t('sharedTask.nicknamePlaceholder')} placeholderTextColor={colors.textPlaceholder} style={styles.input} value={name} onChangeText={setName} maxLength={32} editable={!busy} /></View>
+ <View style={styles.field}><Text style={styles.label}>{t('sharedTask.invitation')}</Text><TextInput accessibilityLabel={t('sharedTask.invitation')} placeholder={t('sharedTask.invitationPlaceholder')} placeholderTextColor={colors.textPlaceholder} style={[styles.input, styles.invitation]} value={invitation} onChangeText={(text) => { pasteVersion.current++; setIncomingLink(null); setInvitation(text); }} maxLength={8192} multiline textAlignVertical="top" autoCapitalize="none" autoCorrect={false} editable={!busy} /></View>
+ <View style={styles.field}>
+ {Platform.OS === 'ios' && Clipboard.isPasteButtonAvailable ? <Clipboard.ClipboardPasteButton
+ key={accountGeneration}
+ acceptedContentTypes={['plain-text', 'url']} displayMode="iconAndLabel" cornerStyle="capsule"
+ backgroundColor={colors.surface} foregroundColor={colors.textPrimary} style={styles.pasteButton}
+ onPress={(data) => { if (data.type === 'text' && isMobileAuthOwnerCurrent(pasteOwner)) acceptPaste(data.text); }} />
+ : <SharedTaskAction action={{ label: t('sharedTask.pasteInvitation'), disabled: busy, onPress: () => void pasteInvitation() }} />}
+ </View>
<View style={styles.noticeBox}><Users size={iconSize.sm} color={colors.textTertiary} /><Text style={[styles.smallMuted, styles.grow]}>{t('sharedTask.joinNotice')}</Text></View>
- <View style={styles.footer}><SharedTaskAction grow action={{ label: t('sharedTask.join'), tone: 'primary', busy, disabled: !invitation.trim() || !name.trim(), onPress: () => void run(async (current) => {
- if (!/^[A-Za-z0-9_-]{43}$/.test(invitation.trim()) || name.trim().length > 32) { setNotice(t('sharedTask.invalid')); return; }
- const joined = await api.join(invitation.trim(), name.trim());
- if (!current()) return;
- Keyboard.dismiss(); setInvitation(''); setJoinedId(joined.sharedTaskId);
- }, false, 'join') }} /></View>
+ <View style={styles.footer}><SharedTaskAction grow action={{ label: t('sharedTask.join'), tone: 'primary', busy, disabled: !invitation.trim(), onPress: () => joinInvitation(invitation) }} /></View>
</>}
</>}
</SharedTaskScreen>;
}
const makeStyles = (colors: ThemeColors) => StyleSheet.create({
+ pasteButton: { minHeight: 44, width: 160 },
intro: { color: colors.textTertiary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption, marginBottom: spacing.lg },
small: { color: colors.textPrimary, fontSize: typeScale.caption, lineHeight: lineHeight.caption },
smallMuted: { color: colors.textTertiary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption },
diff --git a/apps/mobile/src/__tests__/nativeIntent.test.ts b/apps/mobile/src/__tests__/nativeIntent.test.ts
index fb2da4705a..4201756311 100644
--- a/apps/mobile/src/__tests__/nativeIntent.test.ts
+++ b/apps/mobile/src/__tests__/nativeIntent.test.ts
@@ -1,13 +1,40 @@
-import { describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
vi.mock('@/config/env', () => ({
WECHAT_APP_ID: 'wx-test-mobile',
WECHAT_UNIVERSAL_LINK: 'https://login.example.com/app/',
}));
+import { setMobileAuthOwner, invalidateMobileAuthOwnerForSwitch } from '@/auth/authOwnerGeneration';
+import { clearSharedTaskInvitationIntent, getPendingSharedTaskInvitationIntent } from '@/device-link/sharedTaskInvitationIntent';
import { redirectSystemPath } from '../../app/+native-intent';
+const invitation = 'A'.repeat(43);
+const incoming = 'cindy://shared-session?invitation=' + invitation + '&server=https%3A%2F%2Frelay.example.test';
+beforeEach(() => { vi.useFakeTimers(); clearSharedTaskInvitationIntent(); setMobileAuthOwner(null); });
+afterEach(() => { clearSharedTaskInvitationIntent(); vi.useRealTimers(); });
+
describe('mobile native deep-link redirects', () => {
+ it('keeps the invitation out of router state, survives login, and clears on an account change', () => {
+ expect(redirectSystemPath({ path: incoming, initial: true })).toBe('/shared-session');
+ expect(getPendingSharedTaskInvitationIntent()).toMatchObject({ invitation, server: 'https://relay.example.test' });
+ setMobileAuthOwner('first');
+ expect(getPendingSharedTaskInvitationIntent()).not.toBeNull();
+ invalidateMobileAuthOwnerForSwitch();
+ expect(getPendingSharedTaskInvitationIntent()).toBeNull();
+ });
+ it('handles a warm path and expires an unclaimed invitation', () => {
+ redirectSystemPath({ path: incoming.replace('cindy:/', ''), initial: false });
+ expect(getPendingSharedTaskInvitationIntent()).not.toBeNull();
+ vi.advanceTimersByTime(15 * 60_000);
+ expect(getPendingSharedTaskInvitationIntent()).toBeNull();
+ });
+ it('drops an earlier pending invitation when a malformed one arrives', () => {
+ redirectSystemPath({ path: incoming, initial: false });
+ expect(redirectSystemPath({ path: incoming + '&invitation=bad', initial: false })).toBe('/shared-session');
+ expect(getPendingSharedTaskInvitationIntent()).toBeNull();
+ });
+
it.each([true, false])('keeps WeChat SDK callbacks out of navigation (initial=%s)', (initial) => {
for (const path of [
'cindycn://oauth?code=test-wechat-code&state=test-state',
diff --git a/apps/mobile/src/__tests__/sharedSessionCompatibility.test.tsx b/apps/mobile/src/__tests__/sharedSessionCompatibility.test.tsx
index 7413bca86a..50d6a6209f 100644
--- a/apps/mobile/src/__tests__/sharedSessionCompatibility.test.tsx
+++ b/apps/mobile/src/__tests__/sharedSessionCompatibility.test.tsx
@@ -11,6 +11,8 @@ const state = vi.hoisted(() => ({
t: (key: string) => key,
}));
vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: state.t }) }));
+vi.mock('@/config/env', () => ({ DEVICE_LINK_API_BASE_URL: 'https://relay.example.test', APP_SCHEME: 'cindy' }));
+vi.mock('expo-clipboard', () => ({ getStringAsync: vi.fn(), isPasteButtonAvailable: false }));
vi.mock('@/i18n', () => ({ i18n: { t: (key: string) => key } }));
vi.mock('lucide-react-native', () => ({ Check: () => null, Laptop: () => null, Link: () => null, Users: () => null, Clock: () => null, FileText: () => null, Square: () => null, X: () => null }));
vi.mock('@/device-link/accessRevoked', () => ({ markDeviceAccessRevoked: vi.fn() }));
diff --git a/apps/mobile/src/__tests__/sharedTaskFlow.test.tsx b/apps/mobile/src/__tests__/sharedTaskFlow.test.tsx
index ffcf97865c..01317a6522 100644
--- a/apps/mobile/src/__tests__/sharedTaskFlow.test.tsx
+++ b/apps/mobile/src/__tests__/sharedTaskFlow.test.tsx
@@ -6,6 +6,8 @@ import { sharedTaskHostPeer } from '@cindy/device-link';
import { setMobileAuthOwner } from '@/auth/authOwnerGeneration';
import { ApiError } from '@/api/client';
import { Platform } from 'react-native';
+import * as Clipboard from 'expo-clipboard';
+import { clearSharedTaskInvitationIntent, receiveSharedTaskInvitationIntent, getPendingSharedTaskInvitationIntent } from '@/device-link/sharedTaskInvitationIntent';
import SharedSessionScreen from '../../app/shared-session';
const h = vi.hoisted(() => ({
@@ -17,6 +19,8 @@ const h = vi.hoisted(() => ({
t: (key: string, options?: { title?: string }) => options?.title ? key + ':' + options.title : key,
}));
vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: h.t }) }));
+vi.mock('@/config/env', () => ({ DEVICE_LINK_API_BASE_URL: 'https://relay.example.test', APP_SCHEME: 'cindy' }));
+vi.mock('expo-clipboard', () => ({ getStringAsync: vi.fn(), isPasteButtonAvailable: false }));
vi.mock('@/i18n', () => ({ i18n: { t: (key: string) => key } }));
vi.mock('lucide-react-native', () => ({ Check: () => null, Laptop: () => null, Link: () => null, Users: () => null, Clock: () => null, FileText: () => null, Square: () => null, X: () => null }));
vi.mock('@/device-link/accessRevoked', () => ({ markDeviceAccessRevoked: h.revoked }));
@@ -24,7 +28,7 @@ vi.mock('expo-router', async () => {
const { useEffect } = await import('react');
return { Stack: { Screen: () => null }, useLocalSearchParams: () => h.params, useRouter: () => h.router, useFocusEffect: (effect: () => void) => useEffect(effect, [effect]) };
});
-vi.mock('@/auth/AuthContext', () => ({ useAuth: () => ({ isAuthenticated: true, accountGeneration: h.generation }) }));
+vi.mock('@/auth/AuthContext', () => ({ useAuth: () => ({ isAuthenticated: true, accountGeneration: h.generation, user: { name: 'Account Guest' } }) }));
vi.mock('@/device-link/DeviceLinkContext', () => ({ useDeviceLink: () => h.link }));
vi.mock('@/device-link/useSharedTaskApi', () => ({ useSharedTaskApi: () => h.api }));
vi.mock('@/session/remoteSessionStore', () => ({ remoteSessionStore: h.store }));
@@ -77,7 +81,7 @@ async function fill(label: string, value: string) {
const confirmation = () => h.alert.mock.lastCall![2] as { style: string; onPress(): void }[];
beforeEach(() => {
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
- vi.useFakeTimers(); vi.resetAllMocks(); h.params = {}; h.generation = 1;
+ vi.useFakeTimers(); vi.resetAllMocks(); clearSharedTaskInvitationIntent(); h.params = {}; h.generation = 1;
Platform.OS = 'android';
setMobileAuthOwner('owner'); h.link.sharedTaskAvailable = true;
h.api.list.mockResolvedValue([]); h.api.get.mockResolvedValue(detail);
@@ -86,7 +90,63 @@ beforeEach(() => {
h.link.readDeviceList.mockResolvedValue({ devices: [{ deviceId: 'host', name: 'Test computer' }] });
element = document.createElement('div'); root = createRoot(element);
});
-afterEach(async () => { await act(async () => root.unmount()); vi.useRealTimers(); });
+afterEach(async () => { await act(async () => root.unmount()); clearSharedTaskInvitationIntent(); vi.useRealTimers(); });
+const invitationLink = 'https://relay.example.test/shared-task/join#' + 'A'.repeat(43);
+const invitationIntent = 'cindy://shared-session?invitation=' + 'A'.repeat(43) + '&server=https%3A%2F%2Frelay.example.test';
+it('reads the clipboard only on request and joins a pasted link with the account nickname', async () => {
+ vi.mocked(Clipboard.getStringAsync).mockResolvedValue('Join me: ' + invitationLink);
+ await render();
+ expect(Clipboard.getStringAsync).not.toHaveBeenCalled();
+ await click('sharedTask.pasteInvitation');
+ expect((element.querySelector('textarea') as HTMLTextAreaElement).value).toContain(invitationLink);
+ await click('sharedTask.join');
+ expect(h.api.join).toHaveBeenCalledExactlyOnceWith('A'.repeat(43), 'Account Guest');
+ expect(element.querySelector('[aria-label="sharedTask.joinNickname"]')).toBeNull();
+});
+it('rejects an invitation from another service without joining', async () => {
+ await render(); await fill('sharedTask.invitation', invitationLink.replace('relay.example.test', 'other.example.test'));
+ await click('sharedTask.join');
+ expect(h.api.join).not.toHaveBeenCalled();
+ expect(element.textContent).toContain('sharedTask.invitationDifferentServer');
+});
+it('does not overwrite manual input with a delayed clipboard read', async () => {
+ let finish!: (value: string) => void;
+ vi.mocked(Clipboard.getStringAsync).mockImplementation(() => new Promise(resolve => { finish = resolve; }));
+ await render(); await click('sharedTask.pasteInvitation');
+ await fill('sharedTask.invitation', 'B'.repeat(43));
+ await act(async () => finish(invitationLink));
+ expect((element.querySelector('textarea') as HTMLTextAreaElement).value).toBe('B'.repeat(43));
+});
+it('claims a received invitation while capability loads, then joins and enters only once', async () => {
+ h.link.sharedTaskAvailable = false;
+ receiveSharedTaskInvitationIntent(invitationIntent);
+ h.link.invoke.mockResolvedValue({ id: 'task' });
+ await render();
+ expect(getPendingSharedTaskInvitationIntent()).toBeNull();
+ expect(h.api.join).not.toHaveBeenCalled();
+ h.link.sharedTaskAvailable = true;
+ await render(); await render();
+ expect(h.api.join).toHaveBeenCalledExactlyOnceWith('A'.repeat(43), 'Account Guest');
+ expect(h.router.replace).toHaveBeenCalledWith({ pathname: '/sessions/[sessionId]', params: {
+ sessionId: 'task', deviceId: sharedTaskHostPeer('shared', 'desktop'), deviceName: 'Design review',
+ } });
+});
+it('does not carry a claimed invitation across an account change', async () => {
+ h.link.sharedTaskAvailable = false;
+ receiveSharedTaskInvitationIntent(invitationIntent);
+ await render();
+ setMobileAuthOwner('other'); h.generation++;
+ h.link.sharedTaskAvailable = true;
+ await render();
+ expect(h.api.join).not.toHaveBeenCalled();
+});
+it('can receive another link while the previous joined task is still shown', async () => {
+ await render(); await fill('sharedTask.invitation', invitationLink); await click('sharedTask.join');
+ h.link.invoke.mockResolvedValue({ id: 'task' });
+ await act(async () => { receiveSharedTaskInvitationIntent(invitationIntent); });
+ expect(h.api.join).toHaveBeenCalledTimes(2);
+ expect(h.router.replace).toHaveBeenCalledOnce();
+});
it('keeps joined tasks out of the invitation form while retaining the owner tab', async () => {
h.api.list.mockResolvedValue([{ ...owned('Already joined'), ownerAccountId: 'someone' }, owned('My share')]);
await render();
@@ -163,7 +223,7 @@ it.each([['NOT_FOUND', 'sharedTask.invitationUnavailable'], ['PERMISSION_DENIED'
'keeps the invitation form and explains joining failure %s', async (code, key) => {
h.api.join.mockRejectedValue({ code });
await render();
- await fill('sharedTask.invitation', 'a'.repeat(43)); await fill('sharedTask.joinNickname', 'Guest');
+ await fill('sharedTask.invitation', 'a'.repeat(43));
await click('sharedTask.join');
expect(element.textContent).toContain(key);
expect(element.querySelector('textarea')?.value).toBe('a'.repeat(43));
@@ -172,10 +232,10 @@ it.each([['NOT_FOUND', 'sharedTask.invitationUnavailable'], ['PERMISSION_DENIED'
it('uses a multiline invitation and stops at the joined screen before opening the task', async () => {
await render();
expect(element.querySelector('textarea')).not.toBeNull();
- expect(element.querySelector('input')?.maxLength).toBe(32);
- await fill('sharedTask.invitation', 'a'.repeat(43)); await fill('sharedTask.joinNickname', ' Guest ');
+ expect(element.querySelector('input')).toBeNull();
+ await fill('sharedTask.invitation', 'a'.repeat(43));
await click('sharedTask.join');
- expect(h.api.join).toHaveBeenCalledWith('a'.repeat(43), 'Guest');
+ expect(h.api.join).toHaveBeenCalledWith('a'.repeat(43), 'Account Guest');
expect(element.textContent).toContain('sharedTask.joinedTitle:Design review');
expect(element.querySelector('textarea')).toBeNull();
expect(h.link.openLink).not.toHaveBeenCalled();
diff --git a/apps/mobile/src/device-link/sharedTaskInvitationIntent.ts b/apps/mobile/src/device-link/sharedTaskInvitationIntent.ts
new file mode 100644
index 0000000000..d5a5e82267
--- /dev/null
+++ b/apps/mobile/src/device-link/sharedTaskInvitationIntent.ts
@@ -0,0 +1,39 @@
+import { useSyncExternalStore } from 'react';
+import { parseSharedTaskInvitationIntent, type SharedTaskInvitationIntent } from '@cindy/device-link';
+import { getMobileAuthOwner, isMobileAuthOwnerCurrent, subscribeMobileAuthOwner } from '@/auth/authOwnerGeneration';
+
+let pending: (SharedTaskInvitationIntent & { id: number }) | null = null;
+let sequence = 0;
+let stopWatching: (() => void) | undefined;
+let expiry: ReturnType<typeof setTimeout> | undefined;
+const listeners = new Set<() => void>();
+const notify = () => { for (const listener of listeners) listener(); };
+
+/** Memory-only intent: login can continue it, but account switching cannot inherit it. */
+export function clearSharedTaskInvitationIntent(): void {
+ pending = null;
+ stopWatching?.(); stopWatching = undefined;
+ clearTimeout(expiry); expiry = undefined;
+ notify();
+}
+
+export function receiveSharedTaskInvitationIntent(url: string): boolean {
+ const value = parseSharedTaskInvitationIntent(url);
+ if (!value) return false;
+ clearSharedTaskInvitationIntent();
+ let owner = getMobileAuthOwner();
+ if (owner.switching) return true;
+ pending = { ...value, id: ++sequence };
+ stopWatching = subscribeMobileAuthOwner(() => {
+ const next = getMobileAuthOwner();
+ if (next.switching || (owner.accountKey && !isMobileAuthOwnerCurrent(owner))) clearSharedTaskInvitationIntent();
+ else if (next.accountKey) owner = next; // The first login claims an unsigned intent.
+ });
+ expiry = setTimeout(clearSharedTaskInvitationIntent, 15 * 60_000);
+ notify();
+ return true;
+}
+
+export const getPendingSharedTaskInvitationIntent = () => pending;
+const subscribe = (listener: () => void) => { listeners.add(listener); return () => { listeners.delete(listener); }; };
+export const usePendingSharedTaskInvitationIntent = () => useSyncExternalStore(subscribe, getPendingSharedTaskInvitationIntent, getPendingSharedTaskInvitationIntent);
diff --git a/apps/mobile/src/i18n/locales/en/sharedTask.json b/apps/mobile/src/i18n/locales/en/sharedTask.json
index 17ad5fae5f..0101297eac 100644
--- a/apps/mobile/src/i18n/locales/en/sharedTask.json
+++ b/apps/mobile/src/i18n/locales/en/sharedTask.json
@@ -1,13 +1,12 @@
{
"waitingHost": "Waiting for the host to respond. You can continue sending messages.",
"join": "Join Shared Task",
- "joinHint": "Paste an invitation to open the shared task.",
+ "joinHint": "Paste an invitation link to open the shared task.",
"login": "Sign in to Cindy to join a task.",
"openTask": "Open Task",
"notJoined": "This task is no longer shared with you.",
- "invitation": "Invitation",
- "invalid": "Enter a valid invitation and your display name.",
- "nickname": "Display Name",
+ "invitation": "Invitation Link",
+ "invalid": "Paste a valid invitation link or code.",
"requestJoin": "Join",
"dismiss": "Close Dialog",
"title": "Share Task",
@@ -28,21 +27,19 @@
"host": "Host",
"remove": "Remove Guest",
"leave": "Leave Shared Task",
- "invite": "Copy Invitation",
+ "invite": "Copy Invitation Link",
"close": "Stop Sharing",
- "invitationCopied": "Invitation copied",
- "invitationCopyFailed": "The invitation was created but could not be copied. Return to this window and try again.",
+ "invitationCopied": "Invitation link copied",
+ "invitationCopyFailed": "Could not copy the invitation link. Try again.",
"accessEndedBody": "You can no longer access this shared task. To join again, ask the host for a new invitation.",
- "joinIntro": "Paste the invitation from the host to enter the same task.",
- "invitationPlaceholder": "Paste the invitation",
- "joinNickname": "Your Name in This Task",
- "nicknamePlaceholder": "What should we call you?",
+ "joinIntro": "Paste the host’s invitation link to join using your account name.",
+ "invitationPlaceholder": "Paste an invitation link or code",
"joinNotice": "After joining, you can view the full history and message the Agent directly, without waiting for host approval.",
"joinedTitle": "Joined “{{title}}”",
"joined": "Joined Shared Task",
"joinedBody": "You can view earlier messages, tool results and attachments, and message the same Agent.",
"enterTask": "Enter Task",
- "inviteBoxTitle": "Send the invitation to your teammates",
+ "inviteBoxTitle": "Send the invitation link to your teammates",
"roleGuest": "Guest",
"removeShort": "Remove",
"removeNamedTitle": "Remove {{name}}?",
@@ -91,5 +88,8 @@
"hostOfflineTitle": "Host is offline",
"hostOfflineBody": "Sharing for this task is closed and the invitation has expired. Ask the host to share again and send a new invitation.",
"closedToast": "Stopped sharing for {{count}} tasks",
- "closeFailedToast": "Some shares could not be closed ({{count}}). Retry later."
+ "closeFailedToast": "Some shares could not be closed ({{count}}). Retry later.",
+ "pasteInvitation": "Paste Invitation Link",
+ "pasteFailed": "Could not read the clipboard. Paste the invitation link into the field.",
+ "invitationDifferentServer": "This invitation belongs to another Cindy service. Open the link in the matching app."
}
diff --git a/apps/mobile/src/i18n/locales/ja/sharedTask.json b/apps/mobile/src/i18n/locales/ja/sharedTask.json
index e2c7bad025..14ca97ecbc 100644
--- a/apps/mobile/src/i18n/locales/ja/sharedTask.json
+++ b/apps/mobile/src/i18n/locales/ja/sharedTask.json
@@ -1,13 +1,12 @@
{
"waitingHost": "ホストの対応を待っています。引き続きメッセージを送信できます。",
"join": "共有セッションに参加",
- "joinHint": "招待を貼り付けて共有セッションを開きます。",
+ "joinHint": "招待リンクを貼り付けて、共有タスクを開きます。",
"login": "セッションに参加するには Cindy にログインしてください。",
"openTask": "セッションを開く",
"notJoined": "この共有セッションにはアクセスできません。",
- "invitation": "招待",
- "invalid": "有効な招待と表示名を入力してください。",
- "nickname": "表示名",
+ "invitation": "招待リンク",
+ "invalid": "有効な招待リンクまたは招待コードを貼り付けてください。",
"requestJoin": "参加",
"dismiss": "ダイアログを閉じる",
"title": "セッションを共有",
@@ -28,21 +27,19 @@
"host": "ホスト",
"remove": "ゲストを削除",
"leave": "共有セッションから退出",
- "invite": "招待をコピー",
+ "invite": "招待リンクをコピー",
"close": "共有を停止",
- "invitationCopied": "招待をコピーしました",
- "invitationCopyFailed": "招待は作成されましたが、コピーできませんでした。このウィンドウに戻って再試行してください。",
+ "invitationCopied": "招待リンクをコピーしました",
+ "invitationCopyFailed": "招待リンクをコピーできませんでした。もう一度お試しください。",
"accessEndedBody": "この共有タスクにはアクセスできなくなりました。再参加するには、ホストに新しい招待を依頼してください。",
- "joinIntro": "ホストから届いた招待を貼り付けて、同じタスクに参加します。",
- "invitationPlaceholder": "招待内容を貼り付け",
- "joinNickname": "タスク内でのニックネーム",
- "nicknamePlaceholder": "表示する名前",
+ "joinIntro": "ホストからの招待リンクを貼り付けると、アカウント名でタスクに参加します。",
+ "invitationPlaceholder": "招待リンクまたは招待コードを貼り付け",
"joinNotice": "参加するとすべての履歴を閲覧でき、ホストの承認を待たずに Agent にメッセージを送信できます。",
"joinedTitle": "「{{title}}」に参加しました",
"joined": "共有タスクに参加しました",
"joinedBody": "参加前のメッセージ、ツールの結果、添付ファイルを確認し、同じ Agent にメッセージを送信できます。",
"enterTask": "タスクを開く",
- "inviteBoxTitle": "仲間に招待を送信",
+ "inviteBoxTitle": "招待リンクを仲間に送信",
"roleGuest": "ゲスト",
"removeShort": "削除",
"removeNamedTitle": "{{name}}を削除しますか?",
@@ -91,5 +88,8 @@
"hostOfflineTitle": "ホストがオフラインです",
"hostOfflineBody": "このセッションの共有は終了し、招待は無効になりました。ホストに再度共有を開始してもらい、新しい招待を送ってもらってください。",
"closedToast": "{{count}} 件のセッションの共有を停止しました",
- "closeFailedToast": "停止できなかった共有があります({{count}} 件)。後ほど再試行できます。"
+ "closeFailedToast": "停止できなかった共有があります({{count}} 件)。後ほど再試行できます。",
+ "pasteInvitation": "招待リンクを貼り付け",
+ "pasteFailed": "クリップボードを読み取れませんでした。入力欄に招待リンクを貼り付けてください。",
+ "invitationDifferentServer": "この招待は別の Cindy サービスのものです。対応するアプリでリンクを開いてください。"
}
diff --git a/apps/mobile/src/i18n/locales/ko/sharedTask.json b/apps/mobile/src/i18n/locales/ko/sharedTask.json
index 1260e766a0..10e169e46e 100644
--- a/apps/mobile/src/i18n/locales/ko/sharedTask.json
+++ b/apps/mobile/src/i18n/locales/ko/sharedTask.json
@@ -1,13 +1,12 @@
{
"waitingHost": "호스트의 응답을 기다리고 있습니다. 메시지는 계속 보낼 수 있습니다.",
"join": "공유 세션 참여",
- "joinHint": "초대를 붙여넣어 공유 세션을 여세요.",
+ "joinHint": "초대 링크를 붙여넣어 공유 작업을 여세요.",
"login": "세션에 참가하려면 Cindy에 로그인하세요.",
"openTask": "세션 열기",
"notJoined": "이 공유 세션에 더 이상 접근할 수 없습니다.",
- "invitation": "초대",
- "invalid": "유효한 초대와 표시 이름을 입력하세요.",
- "nickname": "표시 이름",
+ "invitation": "초대 링크",
+ "invalid": "유효한 초대 링크 또는 초대 코드를 붙여넣으세요.",
"requestJoin": "참여",
"dismiss": "대화 상자 닫기",
"title": "세션 공유",
@@ -28,21 +27,19 @@
"host": "호스트",
"remove": "게스트 내보내기",
"leave": "공유 세션 나가기",
- "invite": "초대 복사",
+ "invite": "초대 링크 복사",
"close": "공유 중지",
- "invitationCopied": "초대를 복사했습니다",
- "invitationCopyFailed": "초대가 생성되었지만 복사하지 못했습니다. 이 창으로 돌아와 다시 시도해 주세요.",
+ "invitationCopied": "초대 링크를 복사했습니다",
+ "invitationCopyFailed": "초대 링크를 복사하지 못했습니다. 다시 시도하세요.",
"accessEndedBody": "이 공유 작업에 더 이상 접근할 수 없습니다. 다시 참여하려면 호스트에게 새 초대를 요청하세요.",
- "joinIntro": "호스트가 보낸 초대를 붙여넣어 같은 작업에 참여하세요.",
- "invitationPlaceholder": "초대 내용 붙여넣기",
- "joinNickname": "작업에서 사용할 닉네임",
- "nicknamePlaceholder": "표시할 이름",
+ "joinIntro": "호스트의 초대 링크를 붙여넣으면 계정 이름으로 작업에 참여합니다.",
+ "invitationPlaceholder": "초대 링크 또는 초대 코드 붙여넣기",
"joinNotice": "참여하면 전체 기록을 보고 호스트의 승인을 기다리지 않고 Agent에게 메시지를 보낼 수 있습니다.",
"joinedTitle": "「{{title}}」에 참여했습니다",
"joined": "공유 작업에 참여했습니다",
"joinedBody": "참여 전의 메시지, 도구 결과, 첨부 파일을 확인하고 같은 Agent에게 메시지를 보낼 수 있습니다.",
"enterTask": "작업 열기",
- "inviteBoxTitle": "동료에게 초대 보내기",
+ "inviteBoxTitle": "동료에게 초대 링크 보내기",
"roleGuest": "게스트",
"removeShort": "제거",
"removeNamedTitle": "{{name}} 님을 제거할까요?",
@@ -91,5 +88,8 @@
"hostOfflineTitle": "호스트가 오프라인입니다",
"hostOfflineBody": "이 세션의 공유는 종료되었고 초대는 만료되었습니다. 호스트에게 공유를 다시 시작하고 새 초대를 보내달라고 요청하세요.",
"closedToast": "{{count}}개 세션의 공유를 중지했습니다",
- "closeFailedToast": "중지하지 못한 공유가 있습니다({{count}}건). 나중에 다시 시도할 수 있습니다."
+ "closeFailedToast": "중지하지 못한 공유가 있습니다({{count}}건). 나중에 다시 시도할 수 있습니다.",
+ "pasteInvitation": "초대 링크 붙여넣기",
+ "pasteFailed": "클립보드를 읽지 못했습니다. 입력란에 초대 링크를 붙여넣으세요.",
+ "invitationDifferentServer": "다른 Cindy 서비스의 초대입니다. 해당 앱에서 링크를 여세요."
}
diff --git a/apps/mobile/src/i18n/locales/zh-CN/sharedTask.json b/apps/mobile/src/i18n/locales/zh-CN/sharedTask.json
index cfdbfc347d..d388f68d28 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/sharedTask.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/sharedTask.json
@@ -1,13 +1,12 @@
{
"waitingHost": "等待房主处理,你可以继续发送消息。",
"join": "加入共享任务",
- "joinHint": "粘贴邀请,进入同一个共享任务。",
+ "joinHint": "粘贴邀请链接,进入同一个共享任务。",
"login": "请登录 Cindy 后加入任务",
"openTask": "打开任务",
"notJoined": "你已无法访问此共享任务。",
- "invitation": "邀请内容",
- "invalid": "请输入有效的邀请内容和昵称",
- "nickname": "昵称",
+ "invitation": "邀请链接",
+ "invalid": "请粘贴有效的邀请链接或邀请码",
"requestJoin": "加入",
"dismiss": "关闭窗口",
"title": "共享任务",
@@ -28,21 +27,19 @@
"host": "房主",
"remove": "移除访客",
"leave": "退出共享任务",
- "invite": "复制邀请",
+ "invite": "复制邀请链接",
"close": "关闭共享",
- "invitationCopied": "邀请已复制",
- "invitationCopyFailed": "邀请已生成,但未能复制。请回到此窗口后重试。",
+ "invitationCopied": "邀请链接已复制",
+ "invitationCopyFailed": "未能复制邀请链接,请重试",
"accessEndedBody": "当前已无法访问这个共享任务。如需再次加入,请联系房主发送新邀请。",
- "joinIntro": "粘贴房主发来的邀请,进入同一个任务。",
- "invitationPlaceholder": "粘贴邀请内容",
- "joinNickname": "你在任务中的昵称",
- "nicknamePlaceholder": "怎么称呼你",
+ "joinIntro": "粘贴房主发来的邀请链接,使用你的账号昵称加入任务。",
+ "invitationPlaceholder": "粘贴邀请链接或邀请码",
"joinNotice": "加入后可查看全部历史,并直接向 Agent 发消息,无需等待房主审批。",
"joinedTitle": "已加入「{{title}}」",
"joined": "已加入共享任务",
"joinedBody": "你可以查看加入前的消息、工具结果和附件,也可以向同一个 Agent 发消息。",
"enterTask": "进入任务",
- "inviteBoxTitle": "将邀请发给你的伙伴",
+ "inviteBoxTitle": "将邀请链接发给你的伙伴",
"roleGuest": "访客",
"removeShort": "移除",
"removeNamedTitle": "移除{{name}}?",
@@ -91,5 +88,8 @@
"hostOfflineTitle": "房主已离线",
"hostOfflineBody": "这个任务的共享已关闭,原邀请已失效。请联系房主重新开启共享并发送新邀请。",
"closedToast": "已关闭 {{count}} 个任务的共享",
- "closeFailedToast": "部分共享未能关闭({{count}} 项),可稍后重试。"
+ "closeFailedToast": "部分共享未能关闭({{count}} 项),可稍后重试。",
+ "pasteInvitation": "粘贴邀请链接",
+ "pasteFailed": "未能读取剪贴板,请在输入框中粘贴邀请链接",
+ "invitationDifferentServer": "此邀请属于其他 Cindy 服务,请用对应的客户端打开链接"
}
diff --git a/apps/mobile/src/i18n/locales/zh-TW/sharedTask.json b/apps/mobile/src/i18n/locales/zh-TW/sharedTask.json
index 66156ea162..2f4e8e9d0e 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/sharedTask.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/sharedTask.json
@@ -1,13 +1,12 @@
{
"waitingHost": "等待房主處理,你可以繼續傳送訊息。",
"join": "加入共享任務",
- "joinHint": "貼上邀請,進入同一個共享任務。",
+ "joinHint": "貼上邀請連結,進入同一個共享任務。",
"login": "請登入 Cindy 後加入任務",
"openTask": "開啟任務",
"notJoined": "你已無法存取此共享任務。",
- "invitation": "邀請內容",
- "invalid": "請輸入有效的邀請內容和暱稱",
- "nickname": "暱稱",
+ "invitation": "邀請連結",
+ "invalid": "請貼上有效的邀請連結或邀請碼",
"requestJoin": "加入",
"dismiss": "關閉視窗",
"title": "共享任務",
@@ -28,21 +27,19 @@
"host": "主持人",
"remove": "移除訪客",
"leave": "離開共享任務",
- "invite": "複製邀請",
+ "invite": "複製邀請連結",
"close": "停止共享",
- "invitationCopied": "已複製邀請",
- "invitationCopyFailed": "邀請已產生,但未能複製。請回到此視窗後重試。",
+ "invitationCopied": "邀請連結已複製",
+ "invitationCopyFailed": "無法複製邀請連結,請重試",
"accessEndedBody": "目前已無法存取此共享任務。如需再次加入,請聯絡房主傳送新邀請。",
- "joinIntro": "貼上房主傳來的邀請,進入同一個任務。",
- "invitationPlaceholder": "貼上邀請內容",
- "joinNickname": "你在任務中的暱稱",
- "nicknamePlaceholder": "怎麼稱呼你",
+ "joinIntro": "貼上房主傳來的邀請連結,使用你的帳號暱稱加入任務。",
+ "invitationPlaceholder": "貼上邀請連結或邀請碼",
"joinNotice": "加入後可查看全部歷史,並直接向 Agent 傳送訊息,無需等待房主審批。",
"joinedTitle": "已加入「{{title}}」",
"joined": "已加入共享任務",
"joinedBody": "你可以查看加入前的訊息、工具結果和附件,也可以向同一個 Agent 傳送訊息。",
"enterTask": "進入任務",
- "inviteBoxTitle": "將邀請傳給你的夥伴",
+ "inviteBoxTitle": "將邀請連結傳給你的夥伴",
"roleGuest": "訪客",
"removeShort": "移除",
"removeNamedTitle": "移除{{name}}?",
@@ -91,5 +88,8 @@
"hostOfflineTitle": "房主已離線",
"hostOfflineBody": "這個任務的共享已關閉,原邀請已失效。請聯絡房主重新開啟共享並傳送新邀請。",
"closedToast": "已關閉 {{count}} 個任務的共享",
- "closeFailedToast": "部分共享未能關閉({{count}} 項),可稍後重試。"
+ "closeFailedToast": "部分共享未能關閉({{count}} 項),可稍後重試。",
+ "pasteInvitation": "貼上邀請連結",
+ "pasteFailed": "無法讀取剪貼簿,請在輸入欄位中貼上邀請連結",
+ "invitationDifferentServer": "此邀請屬於其他 Cindy 服務,請用對應的用戶端開啟連結"
}
diff --git a/docs/product-rules/shared-task-mode.md b/docs/product-rules/shared-task-mode.md
index 10f2ba468a..1f8a2015bd 100644
--- a/docs/product-rules/shared-task-mode.md
+++ b/docs/product-rules/shared-task-mode.md
@@ -1,6 +1,6 @@
# 共享任务:远程连接的多人版本
-> 产品裁决更新:2026-09-20。实现与验证进度见文末;本文不代表已上线。
+> 产品裁决更新:2026-09-28。实现与验证进度见文末;本文不代表已上线。
> 产品、代码、协议与存储统一使用“共享任务 / SharedTask”,开发期旧协议不保留兼容别名。
## 定位
@@ -11,13 +11,24 @@
## 用户流程
-1. 房主在任务内点击“共享任务”,开启共享并复制邀请。
-2. 访客在菜单“加入共享任务”粘贴邀请,登录后直接加入,无申请或批准步骤。
+1. 房主在任务内点击“共享任务”,开启共享并复制邀请链接。
+2. 访客点击链接,通过网页唤起已安装的客户端;登录后直接加入并进入任务。也可在菜单“加入共享任务”粘贴链接或旧邀请码,无申请或批准步骤。
3. 双方进入现有任务页面,查看全部历史、工具结果、上下文和附件,向同一个 Agent 发消息。
4. 房主可复制新邀请、移除访客、停止共享;访客可退出。
不增加申请记录、审批通知、在线人数、正在输入、编辑标记或独立会议页面。成员列表和消息作者只用于识别参与者。
+### 邀请链接第一步(2026-09-28)
+
+- 复用现有 device-link 服务提供公开页面,无需单独建立官网。链接为 `<deviceLinkApiBaseUrl>/shared-task/join#<invitation>`,凭据放 fragment,不进入网页 HTTP 请求;网页不展示任务内容或操作成员关系。
+- 页面尝试通过已有 URL Scheme 唤起桌面或移动端,居中展示品牌图、打开状态与一句提示,下方仅保留再次打开、复制邀请链接和下载三个文字入口。按浏览器语言支持简中、繁中、英、日、韩,并适配浅深色。浏览器限制自动唤起时由用户点击再次打开;应用内浏览器可转到系统浏览器或复制后粘贴。
+- Windows 协议注册时补齐协议专属的 Cindy 应用显示名,避免开发环境中的通用 Electron 名称出现在浏览器唤起提示中;不更改其他 Electron 应用或协议的名称与启动命令。
+- 链接默认唤起 Cindy;发起客户端按自身构建身份在 fragment 追加 `?app=cindycn` 或 `?app=cindydev`,网页据此选择移动端已有 Scheme,不让用户选择版本。
+- 客户端只向当前配置的服务提交邀请。链接中的 `server` 仅用于比较,不能覆盖请求目标;不同服务的邀请显示对应提示。仍接受旧的裸邀请码,REST 和 device-link 既有入参保持兼容。
+- 访客加入时直接使用已登录用户的账号昵称,不再要求填写自定义昵称。昵称只作为展示信息,成员身份仍由服务端的账号与成员关系决定。
+- 移动端由用户主动点击粘贴入口读取剪贴板;iOS 可用时采用系统粘贴控件,不在启动或回前台时静默读取。收到的邀请只在内存中暂存,支持首次登录后继续,切换账号、关闭页面或过期后不自动沿用。
+- 本阶段不修改移动端原生配置或 runtime fingerprint;Universal Links / Android App Links 另行实施。先部署服务端页面,再发布客户端;旧客户端尚不能解析新链接,需更新。
+
## 权限与顺序
- 任务由原桌面运行,模型费用沿用房主连接;同账号远控行为不变。
diff --git a/packages/device-link/src/__tests__/sharedTaskInvitation.test.ts b/packages/device-link/src/__tests__/sharedTaskInvitation.test.ts
new file mode 100644
index 0000000000..8d4e21a289
--- /dev/null
+++ b/packages/device-link/src/__tests__/sharedTaskInvitation.test.ts
@@ -0,0 +1,60 @@
+import { describe, expect, it } from 'vitest';
+import { buildSharedTaskInvitationLink, parseSharedTaskInvitation, parseSharedTaskInvitationIntent, sharedTaskAccountName } from '../sharedTaskInvitation.js';
+
+const token = 'A'.repeat(43);
+const server = 'https://relay.example.test';
+const link = `${server}/shared-task/join#${token}`;
+
+describe('shared task invitation handoff', () => {
+ it('keeps the secret out of the HTTP request while retaining old codes', () => {
+ expect(buildSharedTaskInvitationLink(token, server + '/')).toBe(link);
+ const url = new URL(link);
+ expect(url.pathname + url.search).not.toContain(token);
+ for (const input of [token, link, `Join this task: ${link}.`, `[Join](${link})`, `「${link}」`]) {
+ expect(parseSharedTaskInvitation(input, server)).toEqual({ ok: true, invitation: token });
+ }
+ });
+ it('accepts only the originating build hint in the fragment', () => {
+ for (const app of ['cindycn', 'cindydev'] as const) {
+ const value = buildSharedTaskInvitationLink(token, server, app);
+ expect(value).toBe(link + '?app=' + app);
+ expect(new URL(value).search).toBe('');
+ expect(parseSharedTaskInvitation(value, server)).toEqual({ ok: true, invitation: token });
+ }
+ for (const hint of ['?app=other', '?app=cindy&app=cindycn', '?app=cindy?extra=1', '?redirect=https://other.example.test']) {
+ expect(parseSharedTaskInvitation(link + hint, server)).toEqual({ ok: false, reason: 'invalid' });
+ }
+ });
+ it('does not extract credentials from arbitrary URLs or ambiguous invitations', () => {
+ for (const input of [link + 'B', link + '/more', link.replace('/join#', '/join?token='), link.replace('https:', 'javascript:'),
+ link.replace('https://', 'https://user:password@'), `${link} ${link}`, 'a'.repeat(8193)]) {
+ expect(parseSharedTaskInvitation(input, server)).toEqual({ ok: false, reason: 'invalid' });
+ }
+ expect(parseSharedTaskInvitation(link, 'https://other.example.test')).toEqual({ ok: false, reason: 'different-server' });
+ expect(parseSharedTaskInvitation(link, server + '/prefix')).toEqual({ ok: false, reason: 'different-server' });
+ });
+ it('handles prefixed endpoints and local development without accepting arbitrary HTTP servers', () => {
+ for (const base of [server + '/prefix', 'http://127.0.0.1:1234', 'http://localhost:1234']) {
+ expect(parseSharedTaskInvitation(buildSharedTaskInvitationLink(token, base), base)).toEqual({ ok: true, invitation: token });
+ }
+ expect(() => buildSharedTaskInvitationLink(token, 'http://public.example.test')).toThrow();
+ });
+ it('accepts only bounded invitation handoffs with one token and service', () => {
+ const query = `?invitation=${token}&server=${encodeURIComponent(server)}`;
+ for (const path of ['cindy://shared-task/join', 'cindy://shared-session', 'cindycn://shared-session', 'cindydev://shared-session']) {
+ expect(parseSharedTaskInvitationIntent(path + query)).toEqual({ invitation: token, server });
+ }
+ for (const value of ['https://shared-task/join', 'other://shared-session', 'cindy://shared-session/extra', 'cindy://user@shared-session']) {
+ expect(parseSharedTaskInvitationIntent(value + query)).toBeNull();
+ }
+ for (const suffix of ['&invitation=' + token, '&server=' + server, '&redirect=https://evil.test', '#extra']) {
+ expect(parseSharedTaskInvitationIntent('cindy://shared-session' + query + suffix)).toBeNull();
+ }
+ });
+ it('uses the account name within the existing label limit without splitting Unicode', () => {
+ expect(sharedTaskAccountName(' Account Name ')).toBe('Account Name');
+ expect(sharedTaskAccountName('a'.repeat(31) + '\u{1f600}')).toBe('a'.repeat(31));
+ expect(sharedTaskAccountName('A\nB')).toBe('AB');
+ expect(sharedTaskAccountName('')).toBe('Cindy');
+ });
+});
diff --git a/packages/device-link/src/index.ts b/packages/device-link/src/index.ts
index 69332bce0e..7378936994 100644
--- a/packages/device-link/src/index.ts
+++ b/packages/device-link/src/index.ts
@@ -37,6 +37,7 @@ export * from "./filePeerRuntime.js";
export { FILE_PEER_RUNTIME_SOURCE } from "./filePeerRuntimeSource.js";
export * from "./sharedTask.js";
export * from "./sharedTaskApi.js";
+export * from "./sharedTaskInvitation.js";
export * from "./sharedTaskProbe.js";
export * from "./modelFavorites.js";
export * from "./sessionListTransport.js";
diff --git a/packages/device-link/src/sharedTaskInvitation.ts b/packages/device-link/src/sharedTaskInvitation.ts
new file mode 100644
index 0000000000..18f4b40d2e
--- /dev/null
+++ b/packages/device-link/src/sharedTaskInvitation.ts
@@ -0,0 +1,76 @@
+/** Public invitation URLs carry the secret in the fragment, never the HTTP request. */
+export const SHARED_TASK_INVITATION_PATH = '/shared-task/join';
+const TOKEN = /^[A-Za-z0-9_-]{43}$/;
+
+export function isSharedTaskInvitation(value: unknown): value is string {
+ return typeof value === 'string' && TOKEN.test(value);
+}
+
+/** Only compare this value with the configured endpoint; never use it as a request target. */
+export function sharedTaskInvitationServer(value: string): string | null {
+ try {
+ const url = new URL(value);
+ if (url.username || url.password || url.search || url.hash) return null;
+ if (url.protocol !== 'https:' && !(url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname))) return null;
+ return url.origin + url.pathname.replace(/\/+$/, '');
+ } catch { return null; }
+}
+
+export type SharedTaskInvitationApp = 'cindy' | 'cindycn' | 'cindydev';
+const APPS = new Set(['cindy', 'cindycn', 'cindydev']);
+
+export function buildSharedTaskInvitationLink(invitation: string, server: string, app: SharedTaskInvitationApp = 'cindy'): string {
+ const base = sharedTaskInvitationServer(server);
+ if (!isSharedTaskInvitation(invitation) || !base || !APPS.has(app)) throw new Error('Invalid shared task invitation');
+ return `${base}${SHARED_TASK_INVITATION_PATH}#${invitation}${app === 'cindy' ? '' : '?app=' + app}`;
+}
+
+export type SharedTaskInvitationResult =
+ | { ok: true; invitation: string }
+ | { ok: false; reason: 'invalid' | 'different-server' };
+
+/** Accept one invitation URL in shared text, or an old bare invitation. */
+export function parseSharedTaskInvitation(input: string, server: string): SharedTaskInvitationResult {
+ const invalid = { ok: false, reason: 'invalid' } as const;
+ if (input.length > 8192) return invalid;
+ const text = input.trim();
+ if (TOKEN.test(text)) return { ok: true, invitation: text };
+ const links = text.match(/https?:\/\/[^\s<>"',。!?、()「」“”‘’\[\])]+/g);
+ if (links?.length !== 1) return invalid;
+ try {
+ const url = new URL(links[0].replace(/[.,;!?]+$/, ''));
+ if (url.search || url.username || url.password || !url.pathname.endsWith(SHARED_TASK_INVITATION_PATH)) return invalid;
+ const [invitation, hint, extra] = url.hash.slice(1).split('?');
+ if (extra !== undefined || (hint !== undefined && !/^app=(cindy|cindycn|cindydev)$/.test(hint))) return invalid;
+ if (!isSharedTaskInvitation(invitation)) return invalid;
+ const source = sharedTaskInvitationServer(url.origin + url.pathname.slice(0, -SHARED_TASK_INVITATION_PATH.length));
+ if (!source) return invalid;
+ if (source !== sharedTaskInvitationServer(server)) return { ok: false, reason: 'different-server' };
+ return { ok: true, invitation };
+ } catch { return invalid; }
+}
+
+export interface SharedTaskInvitationIntent { invitation: string; server: string }
+
+/** Strict custom-scheme handoff. Other deep links remain owned by their existing handlers. */
+export function parseSharedTaskInvitationIntent(value: string): SharedTaskInvitationIntent | null {
+ if (value.length > 4096) return null;
+ try {
+ const url = new URL(value);
+ if (!['cindy:', 'cindycn:', 'cindydev:'].includes(url.protocol) || url.username || url.password || url.port || url.hash) return null;
+ if (!(url.host === 'shared-task' && url.pathname === '/join') && !(url.host === 'shared-session' && !url.pathname)) return null;
+ if ([...url.searchParams.keys()].some(key => key !== 'invitation' && key !== 'server')) return null;
+ if (url.searchParams.getAll('invitation').length !== 1 || url.searchParams.getAll('server').length !== 1) return null;
+ const invitation = url.searchParams.get('invitation');
+ const server = sharedTaskInvitationServer(url.searchParams.get('server') ?? '');
+ return isSharedTaskInvitation(invitation) && server ? { invitation, server } : null;
+ } catch { return null; }
+}
+
+/** Account names are display metadata. Keep the existing admission label bound. */
+export function sharedTaskAccountName(name: string | null | undefined): string {
+ const text = (name ?? '').replace(/[\u0000-\u001f\u007f]/g, '').trim();
+ let end = Math.min(text.length, 32);
+ if (end < text.length && /[\uD800-\uDBFF]/.test(text[end - 1] ?? '') && /[\uDC00-\uDFFF]/.test(text[end] ?? '')) end--;
+ return text.slice(0, end) || 'Cindy';
+}